1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338: 339: 340: 341: 342: 343: 344: 345: 346: 347: 348: 349: 350: 351: 352: 353: 354: 355: 356: 357: 358: 359: 360: 361: 362: 363: 364: 365: 366: 367: 368: 369: 370: 371: 372: 373: 374: 375: 376: 377: 378: 379: 380: 381: 382: 383: 384: 385: 386: 387: 388: 389: 390: 391: 392: 393: 394: 395: 396: 397: 398: 399: 400: 401: 402: 403: 404: 405: 406: 407: 408: 409: 410: 411: 412: 413: 414: 415: 416: 417: 418: 419: 420: 421: 422: 423: 424: 425: 426: 427: 428: 429: 430: 431: 432: 433: 434: 435: 436: 437: 438: 439: 440: 441: 442: 443: 444: 445: 446: 447: 448: 449: 450: 451: 452: 453: 454: 455: 456: 457: 458: 459: 460: 461: 462: 463: 464: 465: 466: 467: 468: 469: 470: 471: 472: 473: 474: 475: 476: 477: 478: 479: 480: 481: 482: 483: 484: 485: 486: 487: 488: 489: 490: 491: 492: 493: 494: 495: 496: 497: 498: 499: 500: 501: 502: 503: 504: 505: 506: 507: 508: 509: 510: 511: 512: 513: 514: 515: 516: 517: 518: 519: 520: 521: 522: 523: 524: 525: 526: 527: 528: 529: 530: 531: 532: 533: 534: 535: 536: 537: 538: 539: 540: 541: 542: 543: 544: 545: 546: 547: 548: 549: 550: 551: 552: 553: 554: 555: 556: 557: 558: 559: 560: 561: 562: 563: 564: 565: 566: 567: 
<?php
    declare(strict_types=1);
    /**
     *  +------------------------------------------------------------+
     *  | apnscp                                                     |
     *  +------------------------------------------------------------+
     *  | Copyright (c) Apis Networks                                |
     *  +------------------------------------------------------------+
     *  | Licensed under Artistic License 2.0                        |
     *  +------------------------------------------------------------+
     *  | Author: Matt Saladna (msaladna@apisnetworks.com)           |
     *  +------------------------------------------------------------+
     */

    /**
     * htaccess driver
     *
     * @package core
     */

    use Module\Support\Personality\Helpers\CacheablePriorityHeap;
    use Tivie\HtaccessParser\HtaccessContainer;
    use Tivie\HtaccessParser\Token\BaseToken;

    class Personality_Module extends Module_Skeleton
    {
        const CONTROL_FILE = '.htaccess';
        const CACHE_KEY_PREFIX = 'pnlty:';
        // under modules/
        const PERSONALITY_MODULE_LOCATION = 'lib/Module/Support/Personality';

        public $exportedFunctions = array(
            '*' => PRIVILEGE_SITE
        );

        // loaded personalitiesv
        private $_personalities = array();
        private $_resolverCache = array();
        private $_instances = array();

        public function __wakeup()
        {
            $this->_personalities = array();
            $this->_instances = array();
            if (is_debug()) {
                $this->_resolverCache = array();
            }
        }

        public function scan($file)
        {
            if (!$this->file_exists($file)) {
                $this->file_touch($file);
            }
            $splfile = $this->_getSPLObjectFromFile($file);
            if (!is_object($splfile)) {
                return null;
            }
            if (false === ($parser = $this->_getCache($splfile))) {
                $parser = $this->_getParser($splfile);
                $this->_setCache($splfile, $parser);

                return $this->_parse($parser);
            }

            return $parser;
        }

        private function _getSPLObjectFromFile($file)
        {
            $path = $this->file_make_path($file);
            try {
                $splfile = new SplFileObject($path);
            } catch (Exception $e) {
                return error("unable to access control file `%s': %s",
                    $this->file_unmake_path($file),
                    $e->getMessage()
                );
            }

            return $splfile;

        }

        private function _getCache(SplFileObject $file, $which = 'entry')
        {
            $cache = Cache_Account::spawn($this->getAuthContext());
            $key = self::CACHE_KEY_PREFIX . $file->getInode();
            if (false !== ($res = $cache->get($key))) {
                if ($res['time'] == $file->getMTime()) {
                    return $res[$which];
                }
            }

            return false;
        }

        private function _getParser(SplFileObject $splfile)
        {
            $parser = new \Tivie\HtaccessParser\Parser();
            $parser->ignoreComments(false)->ignoreWhitelines(false);
            $parser->setFile($splfile);

            return $parser;
        }

        /**
         * Store Htaccess Parser
         *
         * @param SplFileObject                $file
         * @param \Tivie\HtaccessParser\Parser $parser
         * @return mixed
         * @throws \Tivie\HtaccessParser\Exception\Exception
         */
        private function _setCache(SplFileObject $file, \Tivie\HtaccessParser\Parser $parser)
        {
            $cache = Cache_Account::spawn($this->getAuthContext());
            $key = self::CACHE_KEY_PREFIX . $file->getInode();
            if (!($parsed = $this->_parse($parser, $file))) {
                return $parsed;
            }

            return $cache->set($key, array(
                'time'  => $file->getMTime(),
                'hash'  => $parsed->txtSerialize(),
                'entry' => $parsed
            ));
        }

        public function get_personalities()
        {
            $personalities = $this->_tryPersonalities();
            $ret = array();
            while (false !== ($personalities->valid())) {
                $name = $personalities->current();
                $ret[] = $name;
                $personalities->next();
            }

            return $ret;
        }

        private function _tryPersonalities()
        {
            $key = 'prsntly';
            $cache = Cache_Global::spawn();
            $personalities = $cache->get($key);
            if ($personalities) {
                // arg! enumeration consumes the queue
                $tmp = Util_PHP::unserialize($personalities, true);
                $this->_personalities = $tmp['personalities'];
                $this->_instances = $tmp['instances'];

                return $this->_personalities;
            }


            $queue = new CacheablePriorityHeap();

            $dir = INCLUDE_PATH . '/' . self::PERSONALITY_MODULE_LOCATION;
            $dh = opendir($dir);
            if (!$dh) {
                return error('unable to access personality module location');
            }
            while (false !== ($entry = readdir($dh))) {
                if ($entry[0] === '.') {
                    continue;
                }
                $pos = strrpos($entry, '.');
                if ($pos === false || substr($entry, $pos) !== '.php') {
                    continue;
                }

                $type = substr($entry, 0, strpos($entry, '.'));
                $class = $this->_getInstanceFromPersonality($type);
                $queue->insert($type, $class->getPriority());
            }

            closedir($dh);
            $queue->rewind();
            $this->_personalities = $queue;

            $data = array(
                'personalities' => $this->_personalities,
                'instances'     => $this->_instances
            );

            $cache->set($key, serialize($data));

            return $queue;
        }

        private function _getInstanceFromPersonality($personality)
        {
            if (!$personality) {
                return error('no personality specified');
            }

            if (isset($this->_instances[$personality])) {
                return $this->_instances[$personality];
            }
            $class = '\\Module\\Support\\Personality\\' . ucwords($personality);
            if (!class_exists($class)) {
                return error("unknown personality `%s'", $personality);
            }
            $this->_instances[$personality] = new $class;

            return $this->_instances[$personality];
        }

        public function insert(
            HtaccessContainer $config,
            $line,
            BaseToken $directive
        ) {
            if ($line < 0 || !$config->offsetExists($line)) {
                return error("invalid offset `%d'", $line);
            }

            if (!$this->verify($directive->getName(), $directive->getArguments())) {
                return error("unknown directive `%s'", $directive->getName());
            }
            $config->insertAt($line, $directive);

            return $config;
        }

        public function verify($directive, $val = null, $personality = null)
        {
            if (!$personality) {
                $personality = $this->resolve($directive);
            }
            if (!$personality) {
                return false;
            }
            if (!$val) {
                return true;
            }
            $instance = $this->_getInstanceFromPersonality($personality);
            if (!$instance->resolves($directive)) {
                return error("personality `%s' doesn't know how to resolve `%s'",
                    $personality,
                    $directive
                );
            }
            $response = $instance->test($directive, $val);
            // if directive/val isn't tested, null is returned
            if (null === $response) {
                return true;
            }

            return $response;
        }

        /**
         * Resolve a delegating personality
         *
         * @param string $token
         * @return array
         */
        public function resolve($token)
        {
            if (array_key_exists($token, $this->_resolverCache)) {
                // don't use isset; unmatched directives will return null
                return $this->_resolverCache[$token];
            }
            $personalities = $this->_tryPersonalities();
            while ($personalities->valid()) {
                $name = $personalities->current();
                $p = $this->_getPersonalityFromName($name);
                if ($p->resolves($token)) {
                    $this->_resolverCache[$token] = $name;

                    return $name;
                }
                $personalities->next();
            }

            $this->_resolverCache[$token] = null;

            return false;
        }

        private function _getPersonalityFromName($name)
        {
            if (isset($this->_instances[$name])) {
                return $this->_instances[$name];
            }


        }

        public function get_description($personality, $directive)
        {
            $personality = strtolower($personality);
            $instance = $this->_getInstanceFromPersonality($personality);
            if (!$instance) {
                return error("unknown personality `%s'", $personality);
            }

            return $instance->getTokenDescription($directive);
        }

        /**
         * @param HtaccessContainer $config
         * @param                   $line
         * @return bool|HtaccessContainer
         */
        public function remove(HtaccessContainer $config, $line)
        {
            if (!$config->offsetExists($line)) {
                return error("invalid offset `%d'", $line);
            }

            $config->offsetUnset($line);

            return $config;
        }

        /**
         * Replace a directive
         *
         * @param HtaccessContainer $config
         * @param        $line
         * @param        $directive
         * @param string $val
         * @return bool|void
         * @throws \Tivie\HtaccessParser\Exception\DomainException
         */
        public function replace($config, $directive, $val = '')
        {

            $directive = $this->_token2Object($directive);
            if (!$this->resolve($directive)) {
                return error("unknown directive `%s' specified", $directive);
            }

            if ($val && !$this->verify($directive, $val)) {
                return error("unknown directive value `%s'", $val);
            }

            $token = $config->search($directive);
            if ($token) {
                dd($token);
                if ($val) {
                    $config[$line] = $directive . ' ' . $val;
                } else {

                }
            } else {
                $config->append("${directive} ${val}");
            }

            return $config;
        }

        /**
         * Convert a string to a htaccess object
         *
         * @param string $token
         * @return BaseToken
         * @throws \Tivie\HtaccessParser\Exception\DomainException
         */
        private function _token2Object($token)
        {
            if ($token instanceof BaseToken) {
                return $token;
            }
            $token = trim($token);
            if (!isset($token[0])) {
                return new \Tivie\HtaccessParser\Token\WhiteLine($token);
            }
            switch ($token[0]) {
                case '#':
                    return new \Tivie\HtaccessParser\Token\Comment($token);
                case '<':
                    // do extra formatting here
                    break;
                default:
                    // normal directive
                    $tokens = explode(' ', $token);

                    return new \Tivie\HtaccessParser\Token\Directive($tokens[0], array_slice($tokens, 1));

            }
            $args = explode(' ', substr($token, 1, strpos($token, '>') - 1));

            $block = new \Tivie\HtaccessParser\Token\Block($args[0]);
            if (isset($args[1])) {
                $block->setArguments(array_slice($args, 1));
            }

            // CRLF LF and CR
            $lines = preg_split('/\R/m', $token);
            unset($lines[0]);
            // skip final closing /IfDefine
            for ($i = 1, $n = sizeof($lines); $i < $n; $i++) {
                $block->addChild($this->_token2Object($lines[$i]));
            }

            return $block;

        }

        public function get_directives($personality)
        {
            $instance = $this->_getInstanceFromPersonality($personality);
            if (!$instance) {
                return error("unknown personality `%s'", $instance);
            }

            return $instance->getDirectives();
        }

        /**
         * Write changes to control file
         *
         * @param array|string $host hostname or host + path
         * @param              $data
         * @param              $hash validation hash @see hash()
         * @return bool
         */
        public function commit($host, $hash, $data)
        {
            $path = '';
            if (is_array($host)) {
                if (count($host) != 2) {
                    return error('host parameter expects at most 2 elements: host and path');
                }
                [$host, $path] = $host;
            }
            $docroot = rtrim($this->web_get_docroot($host) . '/' . $path, '/');
            if (!$docroot) {
                return error("unknown host `%s'", $host);
            }
            $controlpath = $docroot . DIRECTORY_SEPARATOR . self::CONTROL_FILE;
            $olddata = '';
            // do a check to make sure data is consistent
            if ($this->file_exists($controlpath)) {
                $olddata = $this->scan($controlpath);
                if ($this->hash($olddata) !== $hash) {
                    return error("control file `%s' out of sync", $controlpath);
                }
            }
            if ($data instanceof HtaccessContainer) {
                $data = $data->txtSerialize();
            }

            $data = trim($data);
            $res = $this->file_put_file_contents($controlpath, $data);
            if (!$res || $res instanceof Exception) {
                $reason = 'unknown';
                if ($res instanceof Exception) {
                    $reason = $res->getMessage();
                }

                return error("failed to update htaccess contents in `%s', reason: %s", $controlpath, $reason);
            }
            // global subdomain -> plop on active domain to make request
            if (false === strpos($host, '.')) {
                $host = $host . '.' . $this->domain;
                info('personality applied to global subdomain, ' .
                    "converting to fqdn `%s'", $host);
            }
            $myip = (array)$this->common_get_ip_address();
            try {
                $http = new HTTP_Request2('http://' . $myip[0]);
                $http->setHeader('Host', $host);
                $status = $http->send()->getStatus();
                if ($status < 200 || $status >= 500) {
                    warn("inconsistent status `%d' returned, reverted control file %s",
                        $status,
                        $controlpath
                    );

                    $this->file_put_file_contents($controlpath, (string)$olddata);

                    return false;
                }
            } catch (\Exception $e) {
                $this->file_put_file_contents($controlpath, (string)$olddata);

                return error("unable to connect to server to test control file, reverting. Error message: `%s'",
                    $e->getMessage()
                );
            }

            return true;
        }

        /**
         * Calculate hash of a control file or htaccess object
         *
         * @param mixed $obj
         * @return bool|null|string hash or error
         */
        public function hash($obj)
        {
            if ($obj instanceof \Tivie\HtaccessParser\Parser) {
                $obj = $this->_parse($obj);
            } else if (!$obj instanceof HtaccessContainer) {
                if ($obj[0] !== '/') {
                    // raw file
                    /**
                     * this should only be the case after undergoing Htaccess
                     * parsing @see scan()
                     */

                } else {
                    if (!$this->file_exists($obj)) {
                        return error("unknown control file `%s'", $obj);
                    }

                    $spl = $this->_getSPLObjectFromFile($obj);
                    if (!is_object($spl)) {
                        return error("unknown control hash object `%s'", $obj);
                    }
                    $hash = $this->_getCache($spl, 'hash');
                    if ($hash) {
                        //return $hash;
                    }
                    $obj = $this->_parse($this->_getParser($spl));
                }
            }

            return md5(is_object($obj) ? $obj->txtSerialize() : (string)$obj);
        }

        private function _loadPersonalityFromName($name)
        {
            //return $personalities->offsetGet($name);
        }

        /**
         * @param \Tivie\HtaccessParser\Parser $parser
         * @param null                         $file
         * @return array|ArrayAccess|bool|HtaccessContainer
         */
        private function _parse(\Tivie\HtaccessParser\Parser $parser, $file = null)
        {
            try {
                $parsed = $parser->parse($file);
            } catch (\Tivie\HtaccessParser\Exception\SyntaxException $e) {
                return error("`%s' file is malformed! Check that all blocks are balanced with proper case: %s",
                    $this->unwrapFileFromParser($parser),
                    $e->getMessage()
                );
            } catch (Exception $e) {
                return error("unable to parse control file `%s': %s",
                    $this->unwrapFileFromParser($parser),
                    $e->getMessage()
                );
            }

            return $parsed;
        }

        private function unwrapFileFromParser(\Tivie\HtaccessParser\Parser $p): string
        {
            $property = (new ReflectionProperty($p, 'file'));
            $property->setAccessible(true);
            $file = $property->getValue($p);
            $file = $file instanceof SplFileObject ? $file->getPathname() : $file;
            return $this->file_unmake_path($file);
        }

    }