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: 
<?php
    declare(strict_types=1);

    /**
     *  +------------------------------------------------------------+
     *  | apnscp                                                     |
     *  +------------------------------------------------------------+
     *  | Copyright (c) Apis Networks                                |
     *  +------------------------------------------------------------+
     *  | Licensed under Artistic License 2.0                        |
     *  +------------------------------------------------------------+
     *  | Author: Matt Saladna (msaladna@apisnetworks.com)           |
     *  +------------------------------------------------------------+
     */

    /**
     * Class Php_Module
     *
     * @package core
     */
    class Php_Module extends Module_Support_Php implements \Opcenter\Contracts\Hookable
    {
        const COMPOSER_LOCATION = '/usr/bin/composer.phar';

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

        /**
         * Install PEAR package
         *
         * @param  string $module
         * @return bool
         */
        public function install_package($module)
        {
            if (!IS_CLI) {
                return $this->query('php_install_package', $module);
            }


            if (!preg_match('!^[a-zA-Z0-9_-]+$!', $module)) {
                return error($module . ": invalid package name");
            }

            $args = '-d display_errors=0 -d track_errors=1 -d include_path=/usr/local/share/pear:/usr/share/pear';
            if (version_compare(platform_version(), '4.5', '<')) {
                $args .= ' -d disable_functions=ini_set';
            }
            $pearcmd = '/usr/share/pear/pearcmd.php';
            $proc = Util_Process_Tee::watch(new Util_Process_Sudo);
            $proc->log("Installing " . $module);
            if (file_exists($this->domain_fs_path() . '/usr/local/share/pear/pearcmd.php')) {
                $this->_unsetPearIni();
                $pearcmd = '/usr/local/share/pear/pearcmd.php';
            }

            $status = $proc->exec("php %s %s install -f -o %s",
                $args,
                $pearcmd,
                escapeshellarg($module)
            );
            return $status['success'];
        }

        private function _unsetPearIni()
        {
            $pearfile = $this->domain_fs_path() . '/usr/local/share/pear/PEAR.php';
            if (!file_exists($pearfile)) {
                return false;
            }
            $content = file_get_contents($pearfile, 0, null, 0, 1024);
            $changed = false;
            $pos = strpos($content, 'ini_set');
            if ($pos === false) {
                return false;
            }
            $content = file_get_contents($pearfile);
            file_put_contents($pearfile, str_replace('@ini_set', '// @ini_set', $content));
            return true;
        }

        /**
         * List PEAR packages installed for account
         *
         * Keys-
         * is_local (bool) : package is local to account
         * version (double): version number
         *
         * @return array
         */
        public function list_installed_packages()
        {
            if (!IS_CLI) {
                return $this->query('php_list_installed_packages');
            }
            $status = Util_Process::exec("pear list");
            if ($status instanceof Exception) {
                return $status;
            }
            $packages = array();

            $packageSizeSys = preg_match_all('!^([^\s]+)\s+([0-9,\. ]+)!m', $status['output'], $packageMatches);

            for ($i = 1; $i < $packageSizeSys; $i++) {
                $packages[$packageMatches[1][$i]] = array('is_local' => false, 'version' => $packageMatches[2][$i]);
            }


            $status = Util_Process_Sudo::exec("pear list");
            if ($status instanceof Exception) {
                return $status;
            }
            $packageSize = preg_match_all('!^([^\s]+)\s+([0-9,\. ]+)!m', $status['output'], $packageMatches);

            for ($i = 1; $i < $packageSize; $i++) {

                $packages[$packageMatches[1][$i]] = array(
                    'is_local' => true,
                    'version'  => trim($packageMatches[2][$i])
                );
            }
            ksort($packages);
            return $packages;
        }

        /**
         * string get_pear_description (string)
         * Fetches the description for a PEAR package
         *
         * @param  string $mModule package name
         * @return string description of the package
         */

        public function package_description($mModule)
        {
            $packages = $this->list_remote_packages();
            if (!isset($packages[$mModule])) {
                return false;
            }
            return $packages[$mModule]['description'];
        }

        /**
         * array list_remote_packages (void)
         * Queries PEAR for all available PEAR packages, analogous to
         * running pear list-all from the command line.
         *
         * @return array Listing of PEAR modules with the following indexes:
         * versions, description.  :KLUDGE: versions only contains one version
         * number, the most current on PEAR at this time.  This index is kept for
         * consistency with the "Package Manager" component of the control panel
         */
        public function list_remote_packages()
        {
            if (file_exists(TEMP_DIR . '/pear-cache') && ((time() - filemtime(TEMP_DIR . '/pear-cache')) < 86400)) {
                $data = unserialize(file_get_contents(TEMP_DIR . '/pear-cache'));
                return $data;
            }
            $status = Util_Process::exec("/usr/bin/pear list-all");
            if ($status instanceof Exception) {
                return $status;
            }
            $pear = array();
            $pearCount = preg_match_all('!^pear/([^\s]+)\s+([^\s]+)\s+([0-9\.]*)\s+(.*)$!m', $status['output'],
                $pearTmp);

            for ($i = 0; $i < $pearCount; $i++) {
                $pear[$pearTmp[1][$i]] = array(
                    'versions'    => array(trim($pearTmp[2][$i])),
                    'description' => $pearTmp[4][$i]
                );
            }
            file_put_contents(TEMP_DIR . '/pear-cache', serialize($pear));
            return $pear;
        }

        /**
         * Add PHP channel to PEAR package manager
         *
         * @param  string $xml URL reference to package.xml
         * @return bool
         */
        public function add_pear_channel($xml)
        {
            if (substr($xml, -4) != '.xml') {
                return error("channel `$xml' must refer to .xml");
            }
            $status = Util_Process_Sudo::exec('pear add-channel %s', $xml);
            return $status['success'];
        }

        /**
         * Remove PEAR channel from PEAR package manager
         *
         * @param  string $channel channel previously added
         * @return bool
         */

        public function remove_channel($channel)
        {
            $status = Util_Process_Sudo::exec('pear remove-channel %s', $channel);
            return $status['success'];
        }

        /**
         * List all channels configured in PHP PEAR package manager
         *
         * Sample response-
         * array(2) {
         *      [0]=>
         *      array(5) {
         *        ["channel"]=>    string(12) "pear.php.net"
         *        ["summary"]=>    string(40) "PHP Extension and Application Repository"
         *      }
         *      [1]=>
         *      array(5) {
         *        ["channel"]=>    string(12) "pecl.php.net"
         *        ["summary"]=>    string(31) "PHP Extension Community Library"
         *      }
         *    }
         *
         * @return array
         */
        public function list_channels()
        {
            $channels = array();
            $status = Util_Process_Sudo::exec('pear list-channels');
            if (!$status['success']) {
                return $channels;
            }
            $chmatches = null;
            if (!preg_match_all(Regex::PEAR_CHANNELS_LONG, $status['output'], $chmatches, PREG_SET_ORDER)) {
                return $channels;
            }
            foreach ($chmatches as $channel) {
                $channels[] = array(
                    'channel' => $channel['channel'],
                    'summary' => $channel['summary']
                );
            }
            return $channels;
        }

        /**
         * Retrieve PEAR channel information
         *
         * Basic wrapper to pear channel-info <channel> command
         * Sample response-
         * array(4) {
         *      ["server"]=>
         *      string(12) "pear.php.net"
         *      ["alias"]=>
         *      string(4) "pear"
         *      ["summary"]=>
         *      string(40) "PHP Extension and Application Repository"
         *      ["version"]=>
         *      NULL
         * }
         *
         * @param string $channel
         * @return array
         */
        public function get_channel_info($channel)
        {
            $info = array();
            $status = Util_Process_Sudo::exec('pear channel-info %s', $channel);
            if (!$status['success']) {
                return false;
            }
            $line = strtok($status['output'], "=");
            $parse = false;

            for ($idx = null; $line !== false; $line = strtok("\n")) {
                // delimiter ===
                if (!$parse) {
                    if ($line[0] != '=') {
                        continue;
                    } else {
                        $parse = true;
                    }
                }

                if ($idx) {
                    $info[$idx] = trim($line);
                }
                $idx = null;

                $lookup = strtok(" \n");
                if ($lookup == "Name") {
                    strtok(" ");
                    strtok(" ");
                    $idx = 'server';
                } else {
                    if ($lookup == "Alias") {
                        $idx = 'alias';
                    } else {
                        if ($lookup == "Summary") {
                            $idx = 'summary';
                        } else {
                            if ($lookup == "Version") {
                                // Special case if Version field is null
                                $version = null;
                                $line = strtok("\n");
                                if (false === strpos($line, "SERVER CAPABILITIES")) {
                                    $version = trim($line);
                                }
                                $info['version'] = $version;
                            } else {
                                if ($lookup[0] == "=") {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            return $info;
        }

        /**
         * string get_php_version()
         * Returns the available PHP interpreter version on the server
         *
         * @cache     yes
         * @privilege PRIVILEGE_ALL
         *
         * @return string
         */
        public function version()
        {
            $key = 'php.version';
            $ver = apcu_fetch($key);
            if ($ver) {
                return $ver;
            }
            $ver = \Opcenter\Php::version();
            apcu_add($key, $ver, 86400);
            return $ver;
        }

        /**
         * Enable fallback interpreter support
         *
         * @param null|string $mode specific personality in multi-personality environments
         * @return bool
         */
        public function enable_fallback($mode = null)
        {
            if (!IS_CLI) {
                return $this->query('php_enable_fallback', $mode);
            }
            if (!$mode) {
                $mode = $this->getPersonalities();
            }

            $file = file_get_contents($this->web_config_dir() . '/virtual/' .
                $this->site);
            // @todo helper function?
            $config = preg_replace(Regex::compile(
                Regex::PHP_COMPILABLE_STRIP_NONHTTP_APACHE_CONTAINER,
                ['port' => 80]
            ), '', $file);
            $serverip = $this->common_get_ip_address();
            $in = $serverip . ':80';
            foreach ((array)$mode as $m) {
                if (!$this->personalityExists($m)) {
                    error("unknown personality `%s' - not enabling", $m);
                    continue;
                }
                $port = $this->getPersonalityPort($m);
                $out = $serverip . ':' . $port;
                $newconfig = str_replace($in, $out, $config);
                $confpath = $this->getPersonalityPathFromPersonality($m, $this->site);
                file_put_contents($confpath, $newconfig) && info("enabled fallback for `%s'", $m);
            }
            Util_Account_Hooks::run('reload', ['php']);
            return true;
        }

        public function _housekeeping()
        {
            // composer.phar seems standard nowadays..
            if ($this->composer_exists()) {
                return true;
            }

            $versions = file_get_contents('https://getcomposer.org/versions');
            if (!$versions) {
                return false;
            }
            $versions = json_decode($versions, true);
            $url = 'https://getcomposer.org/' . $versions['stable'][0]['path'];
            $res = Util_HTTP::download($url, self::COMPOSER_LOCATION);
            if (!$res) {
                return error("failed to download composer");
            }
            chmod(self::COMPOSER_LOCATION, 0755);
            copy(self::COMPOSER_LOCATION, $this->service_template_path("siteinfo") . self::COMPOSER_LOCATION);

            info("installed %s!", basename(self::COMPOSER_LOCATION));
            return true;
        }

        public function composer_exists()
        {
            return file_exists(self::COMPOSER_LOCATION);
        }

        public function get_fallbacks()
        {
            return $this->getPersonalities();
        }

        /**
         * Verify if fallback enabled for given personality
         *
         * @param string|null $mode
         * @return bool
         */
        public function fallback_enabled($mode = null)
        {
            if (is_null($mode)) {
                $mode = $this->getPersonalities();
                $mode = array_pop($mode);
            }
            return file_exists($this->getPersonalityPathFromPersonality($mode, $this->site));
        }

        /**
         * Disable PHP fallback support
         *
         * @return bool
         */
        public function disable_fallback($mode = '')
        {
            if (!IS_CLI) {
                return $this->query('php_disable_fallback');
            }
            if ($mode) {
                $personalities = [$mode];
            } else {
                $personalities = $this->getPersonalities();
            }
            foreach ($personalities as $personality) {
                if (!$this->personalityExists($personality)) {
                    error("unknown personality `%s', skipping", $personality);
                    continue;
                }
                $path = $this->getPersonalityPathFromPersonality($personality, $this->site);
                if (file_exists($path)) {
                    unlink($path);
                } else {
                    warn("fallback `%s' not enabled", $personality);
                }
            }
            // defer reloading to a later date
            return true;
        }

        public function _delete()
        {
            foreach ($this->get_fallbacks() as $fallback) {
                if ($this->fallback_enabled($fallback)) {
                    $this->disable_fallback($fallback);
                }
            }
        }

        public function _verify_conf(\Opcenter\Service\ConfigurationContext $ctx): bool
        {
            // TODO: Implement _verify_conf() method.
        }

        public function _create()
        {
            // TODO: Implement _create() method.
        }

        public function _edit()
        {
            foreach ($this->get_fallbacks() as $fallback) {
                if ($this->fallback_enabled($fallback)) {
                    $this->disable_fallback($fallback) && $this->enable_fallback($fallback);
                }
            }
        }

        public function _create_user(string $user)
        {
            // TODO: Implement _create_user() method.
        }

        public function _delete_user(string $user)
        {
            // TODO: Implement _delete_user() method.
        }

        public function _edit_user(string $userold, string $usernew, array $oldpwd)
        {
            // TODO: Implement _edit_user() method.
        }
    }