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: 568: 569: 570: 571: 572: 573: 574: 575: 576: 577: 578: 579: 580: 581: 582: 583: 584: 585: 586: 587: 588: 589: 590: 591: 592: 593: 594: 595: 596: 597: 598: 599: 600: 601: 602: 603: 604: 605: 606: 607: 608: 609: 610: 611: 612: 613: 614: 615: 616: 617: 618: 619: 620: 621: 622: 623: 624: 625: 626: 627: 628: 629: 630: 631: 632: 633: 634: 635: 636: 637: 638: 639: 640: 641: 642: 643: 644: 645: 646: 647: 648: 649: 650: 651: 652: 653: 654: 655: 656: 657: 658: 659: 660: 661: 662: 663: 664: 665: 666: 667: 668: 669: 670: 671: 672: 673: 674: 675: 676: 677: 678: 679: 680: 681: 682: 683: 684: 685: 686: 687: 688: 689: 690: 691: 692: 693: 694: 695: 696: 697: 698: 699: 700: 701: 702: 703: 704: 705: 706: 707: 708: 709: 710: 711: 712: 713: 714: 715: 716: 717: 718: 719: 720: 721: 722: 723: 724: 725: 726: 727: 728: 729: 730: 731: 732: 733: 734: 735: 736: 737: 738: 739: 740: 741: 742: 743: 744: 745: 746: 747: 748: 749: 750: 751: 752: 753: 754: 755: 756: 757: 758: 759: 760: 761: 762: 763: 764: 765: 766: 767: 768: 769: 770: 771: 772: 773: 774: 775: 776: 777: 778: 779: 780: 781: 782: 783: 784: 785: 786: 787: 788: 789: 790: 791: 792: 793: 794: 795: 796: 797: 798: 799: 800: 801: 802: 803: 804: 805: 806: 807: 808: 809: 810: 811: 812: 813: 814: 815: 816: 817: 818: 819: 820: 821: 822: 823: 824: 825: 826: 827: 828: 829: 830: 831: 832: 833: 834: 835: 836: 837: 838: 839: 840: 841: 842: 843: 844: 845: 
<?php
    declare(strict_types=1);

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

    use Daphnie\Collector;
    use Daphnie\Metrics\Php as PhpMetrics;
    use Module\Support\Php;
    use Opcenter\Http\Php\Fpm;
    use Opcenter\Http\Php\Fpm\CacheInspector;

    /**
     * Class Php_Module
     *
     * @package core
     */
    class Php_Module extends Php implements \Opcenter\Contracts\Hookable
    {
        const COMPOSER_LOCATION = '/usr/share/pear/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()
        {
            static $ver;
            if (null === $ver) {
                $key = 'php.version';
                $ver = apcu_fetch($key);
                if ($ver) {
                    return $ver;
                }
                $ver = \Opcenter\Php::version();
                apcu_add($key, $ver, 86400);
            }

            return $ver;
        }

        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 _delete()
        {
            foreach ($this->get_fallbacks() as $fallback) {
                if ($this->fallback_enabled($fallback)) {
                    $this->disable_fallback($fallback);
                }
            }
        }

        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 ($this->jailed()) {
                return false;
            }
            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 ($this->jailed()) {
                return false;
            }

            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 _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);
                }
            }
        }

        /**
         * 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 ($this->jailed()) {
                return error('Fallbacks may be used when PHP jails are disabled');
            }
            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 = (array)$this->common_get_ip_address();
            $in = $serverip[0] . ':80';
            foreach ((array)$mode as $m) {
                if (!$this->personalityExists($m)) {
                    error("unknown personality `%s' - not enabling", $m);
                    continue;
                }
                $port = $this->getPersonalityPort($m);
                $out = $serverip[0] . ':' . $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::instantiateContexted($this->getAuthContext())->run('reload', ['php']);

            return true;
        }

        /**
         * PHP is jailed with PHP-FPM
         *
         * @return bool
         */
        public function jailed(): bool
        {
            return (bool)$this->getConfig('apache', 'jail');
        }

        /**
         * Change pool owner
         *
         * @param string      $owner
         * @param string|null $pool  optional pool name
         * @return bool
         */
        public function pool_change_owner(string $owner, string $pool = null): bool
        {
            if (!IS_CLI) {
                return $this->query('php_pool_change_owner', $owner, $pool);
            }

            if (!HTTPD_FPM_USER_CHANGE) {
                return error('Pool ownership disallowed');
            }

            if (!$this->jailed()) {
                return error('Pools not utilized for site');
            }

            $pools = $pools = $this->pools();
            if ($pool && !\in_array($pool, $pools, true)) {
                return error("Unknown pool `%s'", $pool);
            } else if ($pool) {
                warn('Per-pool ownership not supported yet - applying bulk change');
            }

            if (!$this->user_exists($owner)) {
                return error("User `%s' does not exist", $owner);
            }
            if ($owner !== $this->web_get_sys_user() && $owner !== $this->username) {
                return error("Unknown or unsupported pool owner `%s'", $owner);
            }

            $editor = new \Util_Account_Editor($this->getAuthContext()->getAccount(), $this->getAuthContext());
            $editor->setConfig('apache', 'webuser', $owner);
            if (!$editor->edit()) {
                return false;
            }

            $systemd = Fpm\SystemdSynthesizer::mock($this->site . '-' . ($pool ?? array_shift($pools)));
            return $systemd::waitFor(10);
        }

        /**
         * Get pool cache statistics
         *
         * @param string|null $pool
         * @return array
         */
        public function pool_cache_status(string $pool = null): ?array
        {
            if (!IS_CLI) {
                return $this->query('php_pool_cache_status', $pool);
            }
            if (!$this->jailed()) {
                error('Jails disabled for site');
                return null;
            }

            $ip = $this->site_ip_address();
            // @TODO pull configuration, determine deets in multipool
            $hostname = $this->domain ?? SERVER_NAME;
            $docroot = $this->web_get_docroot($hostname);
            return CacheInspector::instantiateContexted($this->getAuthContext(), [$ip, $hostname])->readFromPath($docroot);
        }

        /**
         * Restart PHP-FPM pool state
         *
         * @param string $pool
         * @return bool
         */
        public function pool_restart(string $pool = null): bool
        {
            return $this->pool_set_state($pool, 'restart');
        }

        /**
         * Set PHP-FPM pool state
         *
         * @param string $pool
         * @param string $state active systemd state type (stop, start, restart)
         * @return bool
         */
        public function pool_set_state(?string $pool = null, string $state = 'stop'): bool
        {
            if (!IS_CLI) {
                return $this->query('php_pool_set_state', $pool, $state);
            }
            if (!\in_array($state, ['stop', 'start', 'restart'], true)) {
                return error("Unknown pool state `%s'", $state);
            }

            if ($pool && !\in_array($pool, $this->pools(), true)) {
                return error("Invalid pool specified `%s'", $pool);
            }
            if (!$pool) {
                $pool = $this->pools();
            }
            foreach ((array)$pool as $p)
            {
                if (!Fpm\SystemdSynthesizer::mock($this->site . '-' . $p)->run($state)) {
                    warn('Failed to %s %s-%s', $state, $this->site, $p);
                }
            }

            return true;
        }

        /**
         * Get jail pools
         *
         * @return array
         */
        public function pools(): array
        {
            if (!$this->jailed()) {
                return [];
            }
            $key = 'php.pools';
            $cache = \Cache_Account::spawn($this->getAuthContext());
            if (false !== ($pools = $cache->get($key))) {
                return $pools;
            }
            $pools = array_map(function (string $pool) {
                return substr($pool, strlen($this->site) + 1);
            }, Fpm::getPoolsFromGroup($this->site));
            // @todo possible ghosting
            $cache->set($key, $pools, 30);
            return $pools;
        }

        /**
         * Get pool status
         *
         * @param string $pool named pool or default
         * @return array
         */
        public function pool_status(string $pool = ''): array
        {
            if (!($status = $this->pool_info($pool))) {
                return [];
            }
            return (new Fpm\PoolStatus($status))->getMetrics();
        }

        public function _cron(Cronus $c) {
            static $ctr = 0;

            if (!TELEMETRY_ENABLED || ++$ctr < 600 / CRON_RESOLUTION) {
                return;
            }

            $ctr = 0;
            $oldex = \Error_Reporter::exception_upgrade(Error_Reporter::E_FATAL, true);
            $collector = new Collector(PostgreSQL::pdo());
            foreach (\Opcenter\Account\Enumerate::active() as $site) {
                try {
                    $ctx = \Auth::context(null, $site);
                    $afi = \apnscpFunctionInterceptor::factory($ctx);
                    if (!$afi->php_jailed() || !($service = $afi->php_pool_info())) {
                        continue;
                    }

                    $inspector = new Fpm\PoolStatus($service);
                    if (!$inspector->running()) {
                        continue;
                    }
                    $cacheMetrics = $inspector->getCacheMetrics($ctx);
                    $stats = $afi->php_pool_status();
                    if (null === array_get($stats, 'traffic')) {
                        // pool outage/not started - let's not trigger the pool
                        $stats = PhpMetrics::fill(0);
                    } else {
                        $stats['uptime'] = time() - $inspector->getStart();
                        $stats['cache-used'] = array_get($cacheMetrics, 'memory_usage.used_memory', 0)/1024;
                        $stats['cache-total'] = (array_get($cacheMetrics, 'memory_usage.free_memory') + $stats['cache-used'])/1024;
                        $stats['cache-hits']  = array_get($cacheMetrics, 'opcache_statistics.hits', 0);
                        $stats['cache-misses'] = array_get($cacheMetrics, 'opcache_statistics.misses', 0);
                        $stats['traffic'] *= 100;
                    }


                    foreach (PhpMetrics::getAttributeMap() as $attr => $metric) {
                        $val = $stats[$metric];

                        if ($val instanceof Closure) {
                            $val = $val($stats);
                        }
                        // @TODO register additional pool names
                        $collector->add("php-${attr}", $ctx->site_id, $val);
                    }
                } catch (\apnscpException $e) {
                    // site doesn't exist
                    continue;
                }
            }
            \Error_Reporter::exception_upgrade($oldex);

        }
        /**
         * Get pool info
         *
         * @param string $pool named pool or default
         * @return array
         */
        public function pool_info(string $pool = ''): array
        {
            $pools = $this->pools();
            if ($pool && !in_array($pool, $pools, true)) {
                error("Invalid pool specified `%s'", $pool);

                return [];
            }

            if (!$pool) {
                if (\in_array($this->domain, $pools, true)) {
                    $pool = $this->domain;
                } else {
                    $pool = array_shift($pools);
                }
            }

            // assume default is named after the domain otherwise grab first
            return Fpm\SystemdSynthesizer::mock($this->site . '-' . $pool)->status() ?: [];
        }

        /**
         * Migrate PHP directives to configured engine format
         *
         * @param string      $hostname
         * @param string      $path
         * @param string|null $from null to auto-detect (jail=1 implies "isapi", otherwise "fpm")
         * @return bool
         */
        public function migrate_directives(string $hostname, string $path = '', string $from = null): bool
        {
            if (!IS_CLI) {
                return $this->query('php_migrate_directives', $hostname, $path, $from);
            }
            if (null === $from) {
                $from = $this->jailed() ? 'isapi' : 'fpm';
            }

            if ($from !== 'isapi' && $from !== 'fpm') {
                return error("Unknown underlying PHP engine `%s'", $from);
            }

            if (! ($docroot = $this->web_get_docroot($hostname, $path)) ) {
                return false;
            }

            $srcFile = $docroot . DIRECTORY_SEPARATOR . ($from === 'isapi' ? '.htaccess' : '.user.ini');
            $destFile = $docroot . DIRECTORY_SEPARATOR . ($from === 'isapi' ? '.user.ini' : '.htaccess');
            if (!$this->file_exists($srcFile)) {
                return true;
            }
            $srcContents = $destContents = '';
            if ($this->file_exists($srcFile)) {
                $srcContents = $this->file_get_file_contents($srcFile);
            }
            if ($this->file_exists($destFile)) {
                $destContents = $this->file_get_file_contents($destFile);
            }
            $directives = [];
            $lines = explode("\n", $srcContents);
            if ($from === 'fpm') {
                foreach ($lines as $line) {
                    if (false === strpos($line, '=')) {
                        continue;
                    } else if (strpos($line, ';') === strcspn(';', $line)) {
                        // comment
                        continue;
                    }
                    [$ini, $val] = explode('=', trim($line), 2);
                    $directive = 'php_value';
                    if (strtolower($val) === 'on' || strtolower($val) === 'off') {
                        $directive = 'php_flag';
                    }
                    $directives[] = "${directive} ${ini} ${val}";
                }
            } else {
                foreach ($lines as &$line) {
                    if (false === strpos($line, 'php_flag') && false === strpos($line, 'php_value')) {
                        continue;
                    }
                    if (!preg_match('/^\s*(?<directive>php_(?:flag|value))\s+(?<ini>[^ ]+)\s+(?<value>.+)$/', $line, $match)) {
                        debug("Unknown line `%s' encountered - ignoring", $line);
                        continue;
                    }

                    $directives[] = $match['ini'] . '=' . $match['value'];
                    $line = null;
                }
            }

            // @TODO validate consistency
            return $this->file_put_file_contents($destFile, rtrim(rtrim($destContents) . "\n" . implode("\n", $directives)) . "\n") &&
                $this->file_put_file_contents($srcFile, implode("\n", array_filter($lines)) . "\n");
        }

        public function _create_user(string $user)
        { }

        public function _delete_user(string $user)
        { }

        public function _edit_user(string $userold, string $usernew, array $oldpwd)
        { }
    }