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: 
<?php
    /**
     *  +------------------------------------------------------------+
     *  | apnscp                                                     |
     *  +------------------------------------------------------------+
     *  | Copyright (c) Apis Networks                                |
     *  +------------------------------------------------------------+
     *  | Licensed under Artistic License 2.0                        |
     *  +------------------------------------------------------------+
     *  | Author: Matt Saladna (msaladna@apisnetworks.com)           |
     *  +------------------------------------------------------------+
     */

    use Lararia\Bootstrapper;
    use Module\Support\Webapps\Composer;
    use Module\Support\Webapps\Mailer;
    use Module\Support\Webapps\Traits\PublicRelocatable;

    /**
     * Laravel management
     *
     * An interface to wp-cli
     *
     * @package core
     */
    class Laravel_Module extends Composer
    {
        use PublicRelocatable {
            getAppRoot as getAppRootReal;
        }
        const APP_NAME = 'Laravel';
        const PACKAGIST_NAME = 'laravel/laravel';

        // every Laravel app should contain artisan one level down...
        const LARAVEL_CLI = 'artisan';
        const DEFAULT_VERSION_LOCK = 'minor';

        protected $_aclList = array(
            'min' => array(
                'storage',
                'bootstrap/cache'
            ),
            'max' => array(
                'storage/framework/cache',
                'storage/framework/views',
                'storage/framework/sessions',
                'storage/logs',
                'storage/app/public',
                'bootstrap/cache'
            )
        );

        /**
         * Install Laravel into a pre-existing location
         *
         * @param string $hostname domain or subdomain to install Laravel
         * @param string $path     optional path under hostname
         * @param array  $opts     additional install options
         * @return bool
         */
        public function install(string $hostname, string $path = '', array $opts = array()): bool
        {
            if (!$this->mysql_enabled()) {
                return error("MySQL must be enabled to install %s", ucwords($this->getInternalName()));
            }
            if (!version_compare($this->php_version(), '7', '>=')) {
                return error('Laravel requires PHP7');
            }

            if (!$this->php_composer_exists()) {
                return error('composer missing! contact sysadmin');
            }

            // Same situation as with Ghost. We can't install under a path for fear of
            // leaking information
            if ($path) {
                return error("Composer projects may only be installed directly on a subdomain or domain without a child path, e.g. https://domain.com but not https://domain.com/laravel");
            }

            if (!($docroot = $this->getDocumentRoot($hostname, $path))) {
                return error("failed to normalize path for `%s'", $hostname);
            }

            if (!$this->parseInstallOptions($opts, $hostname, $path)) {
                return false;
            }

            $args['version'] = $opts['version'];

            $lock = $this->parseLock($opts['verlock'], $opts['version']);
            $ret = $this->_execComposer($docroot,
                'create-project --prefer-dist %(package)s %(docroot)s \'%(version)s\'',
                [
                    'package' => static::PACKAGIST_NAME,
                    'docroot' => $docroot,
                    'version' => $lock
                ]
            );
            if (!$ret['success']) {
                $this->file_delete($docroot, true);

                return error("failed to download laravel/laravel package: %s %s",
                    $ret['stderr'], $ret['stdout']
                );
            }

            if (null === ($docroot = $this->remapPublic($hostname, $path))) {
                $this->file_delete($this->getDocumentRoot($hostname, $path), true);

                return error("Failed to remap Laravel to public/, manually remap from `%s' - Laravel setup is incomplete!",
                    $docroot);
            }

            $oldex = \Error_Reporter::exception_upgrade();
            $approot = $this->getAppRoot($hostname, $path);
            try {
                $this->_execComposer($approot, 'config name %(hostname)s/laravel', ['hostname' => $hostname]);
                $docroot = $this->getDocumentRoot($hostname, $path);

                // ensure it's reachable
                $this->_fixCache($approot);

                $db = $this->_suggestDB($hostname);
                if (!$db) {
                    return false;
                }

                $dbuser = $this->_suggestUser($db);
                if (!$dbuser) {
                    return false;
                }
                $dbpass = $this->suggestPassword();
                $credentials = array(
                    'db'       => $db,
                    'user'     => $dbuser,
                    'password' => $dbpass
                );

                if (!$this->setupDatabase($credentials, 'mysql')) {
                    return error("Failed to create database");
                }

                $fqdn = $this->web_normalize_hostname($hostname);
                $args['uri'] = rtrim($fqdn . '/' . $path, '/');
                $args['proto'] = empty($opts['ssl']) ? 'http://' : 'https://';

                if (!$this->setConfiguration($approot, $docroot, array_merge([
                    'dbname'     => $credentials['db'],
                    'dbuser'     => $credentials['user'],
                    'dbpassword' => $credentials['password'],
                    'dbhost'     => 'localhost'
                ], $args))) {
                    return error("failed to set .env configuration");
                }
            } catch (\apnscpException $e) {
                $this->remapPublic($hostname, $path, '');
                $this->file_delete($approot, true);
                if (isset($credentials['db']) && $this->mysql_database_exists($credentials['db'])) {
                    $this->mysql_delete_database($credentials['db']);
                }
                if (isset($credentials['user']) && $this->mysql_user_exists($credentials['user'], 'localhost')) {
                    $this->mysql_delete_user($credentials['user'], 'localhost');
                }
                return error("Failed to install Laravel: %s", $e->getMessage());
            } finally {
                \Error_Reporter::exception_upgrade($oldex);
            }


            $commands = [
                'key:generate',
                'queue:seed',
                'migrate'
            ];
            foreach ($commands as $cmd) {
                $this->_exec($approot, './artisan ' . $cmd);
            }

            // by default, let's only open up ACLs to the bare minimum

            $params = array(
                'version'    => $this->get_version($hostname, $path),
                'hostname'   => $hostname,
                'autoupdate' => (bool)$opts['autoupdate'],
                'options'    => array_except($opts, 'version'),
            );
            $this->map('add', $docroot, $params);

            $this->fortify($hostname, $path, 'max');

            $this->fixRewriteBase($docroot);
            if (!$this->file_exists($approot . '/public/storage')) {
                $this->file_symlink($approot . '/storage/app/public', $approot . '/public/storage');
                $this->file_chown_symlink($approot . '/public/storage', $this->file_stat($approot . '/storage/app/public')['owner']);
            }
            $email = $opts['email'] ?? $this->common_get_email();
            $this->buildConfig($approot, $docroot);
            if (array_get($opts, 'notify', true)) {
                Bootstrapper::minstrap();
                \Illuminate\Support\Facades\Mail::to($email)->
                send((new Mailer('install.laravel', [
                    'uri'     => $args['uri'],
                    'proto'   => $args['proto'],
                    'appname' => static::APP_NAME,
                    'approot' => $approot
                ]))->setAppName(static::APP_NAME));
            }

            if (!$opts['squash']) {
                parent::unsquash(dirname($docroot));
            }

            return info("Laravel installed on %s", $args['uri']);
        }

        protected function checkVersion(array &$options): bool
        {
            if (!isset($options['version'])) {
                $versions = $this->get_installable_versions();
                $options['version'] = array_pop($versions);
            }
            if (!parent::checkVersion($options)) {
                return false;
            }
            $phpversion = $this->php_version();

            $cap = null;
            if (version_compare($phpversion, '5.6.4', '<')) {
                $cap = '5.3';
            } else if (version_compare($phpversion, '7.0.0', '<')) {
                $cap = '5.4';
            } else if (version_compare($phpversion, '7.1.3', '<')) {
                $cap = '5.5';
            }

            if ($cap && version_compare($options['version'], $cap, '>=')) {
                info("PHP version `%s' detected, capping Laravel to %s", $phpversion, $cap);
                $options['version'] = $cap;
            }

            return true;
        }

        private function _execComposer($path = null, $cmd, array $args = array()): array
        {
            $debug = is_debug() ? '-vvv ' : '';
            $cmd = '/usr/bin/composer --no-interaction -q ' . $debug . $cmd;
            if (!is_array($args)) {
                $args = array_slice(func_get_args(), 2);
            }

            $ret = $this->_exec($path, $cmd, $args);
            if (!$ret['success']) {
                error(
                    "Failed executing Composer command `%(cmd)s': %(resp)s",
                    ['cmd' => $cmd, 'resp' => coalesce($ret['stderr'], $ret['stdout'])]
                );
            }

            return $ret;
        }

        private function _exec($path = null, $cmd, array $args = array())
        {
            // client may override tz, propagate to bin
            $cmd = $this->_getCommand() . $cmd;
            if (!is_array($args)) {
                $args = array_slice(func_get_args(), 2);
            }

            $user = $this->username;
            if ($path) {
                $cmd = 'cd %(path)s && /bin/bash -c -- ' . escapeshellarg($cmd);
                $args['path'] = $path;
                $user = $this->file_stat($path)['owner'] ?? $this->username;
            }

            if ($path) {
                $cmd = 'cd %(chdir)s && ' . $cmd;
                $args['chdir'] = $path;
            }
            $memory = (int)($this->getMaximalMemory() * 0.85);
            $ret = $this->pman_run($cmd, $args, ['COMPOSER_MEMORY_LIMIT' => "${memory}m"], ['user' => $user]);

            return $ret;
        }

        private function _getCommand()
        {
            $tz = date_default_timezone_get();
            $cli = 'php -d mysqli.default_socket=' . escapeshellarg(ini_get('mysqli.default_socket')) .
                ' -d date.timezone=' . $tz . ' -d memory_limit=128m ';

            return $cli;
        }

        protected function getAppRoot(string $hostname, string $path = ''): ?string
        {
            return $this->getAppRootReal($hostname, $path);
        }

        /**
         * Inject custom bootstrapper
         *
         * @param $approot
         * @return bool|int|void
         */
        protected function _fixCache($approot)
        {
            $file = $this->domain_fs_path() . '/' . $approot . '/app/ApplicationWrapper.php';
            $tmpfile = tempnam($this->domain_fs_path() . '/tmp', 'appwrapper');
            chmod($tmpfile, 0644);
            if (!copy(resource_path('storehouse/laravel/ApplicationWrapper.php'), $tmpfile)) {
                return warn('failed to copy optimized cache bootstrap');
            }
            if (!posix_getuid()) {
                chown($tmpfile, File_Module::UPLOAD_UID);
            }


            $this->file_endow_upload(basename($tmpfile));
            $this->file_move($this->file_unmake_path($tmpfile), $approot . '/app/ApplicationWrapper.php');

            $file = dirname(dirname($file)) . '/bootstrap/app.php';
            if (!file_exists($file)) {
                return error('unable to alter app.php - file is missing (Laravel corrupted?)');
            }
            $contents = file_get_contents($file);
            $contents = preg_replace('/new\sIlluminate\\\\Foundation\\\\Application/m', 'new App\\ApplicationWrapper',
                $contents);
            if (!$this->file_put_file_contents($this->file_unmake_path($file), $contents)) {
                return false;
            }
            $ret = $this->_execComposer($approot, 'dumpautoload -o');

            return $ret['success'];
        }

        private function setConfiguration(string $approot, string $docroot, array $config)
        {
            $envcfg = (new \Opcenter\Provisioning\ConfigurationWriter("webapps.laravel.env",
                \Opcenter\SiteConfiguration::import($this->getAuthContext())))
                ->compile($config);
            $this->file_put_file_contents("${approot}/.env", (string)$envcfg);

            return $this->buildConfig($approot, $docroot);
        }

        /**
         * Rebuild config and force frontend cache
         *
         * @param string $approot
         * @param string $docroot
         * @return bool
         */
        private function buildConfig(string $approot, string $docroot): bool
        {
            $ret = $this->_exec($approot, 'artisan config:cache');
            if (!$ret['success']) {
                return error("config rebuild failed: %s", coalesce($ret['stderr'], $ret['stdout']));
            }
            if (!($uri = $this->web_get_hostname_from_docroot($docroot))) {
                return error("no URI specified, cannot deduce URI from docroot `%s'", $docroot);
            }
            $uri = $this->web_normalize_hostname($uri);
            $ctx = stream_context_create(array(
                'http' =>
                    array(
                        'timeout'          => 5,
                        'method'           => 'HEAD',
                        'header'           => [
                            "User-agent: " . PANEL_BRAND . " Internal check",
                            "Host: ${uri}"
                        ],
                        'protocol_version' => '1.1'
                    )
            ));

            return (bool)@get_headers('http://' . $this->site_ip_address(), 0, $ctx) ?:
                warn("failed to cache configuration directly, visit `%s' to cache configuration", $uri);
        }

        /**
         * Restrict write-access by the app
         *
         * @param string $hostname
         * @param string $path
         * @param string $mode
         * @return bool
         */
        public function fortify(string $hostname, string $path = '', string $mode = 'max'): bool
        {
            return parent::fortify($hostname, $path, $mode);
        }

        /**
         * Get installed version
         *
         * @param string $hostname
         * @param string $path
         * @return string version number
         */
        public function get_version(string $hostname, string $path = ''): ?string
        {
            // laravel/laravel installs laravel/illuminate, which breaks the composer helper
            $approot = $this->getAppRoot($hostname, $path);
            if (!$this->valid($hostname, $path)) {
                return null;
            }
            $ret = $this->_exec($approot, './artisan --version');
            if (!$ret['success']) {
                return null;
            }

            return rtrim(substr($ret['stdout'], strrpos($ret['stdout'], ' ')+1));
        }

        /**
         * Location is a valid Laravel install
         *
         * @param string $hostname or $docroot
         * @param string $path
         * @return bool
         */
        public function valid(string $hostname, string $path = ''): bool
        {
            if ($hostname[0] === '/') {
                if (!($path = realpath($this->domain_fs_path($hostname)))) {
                    return false;
                }
                $approot = \dirname($path);
            } else {
                $approot = $this->getAppRoot($hostname, $path);
                if (!$approot) {
                    return false;
                }
                $approot = $this->domain_fs_path($approot);
            }

            return file_exists($approot . '/artisan');
        }

        /**
         * Get Laravel framework versions
         *
         * @return array
         */
        public function get_versions(): array
        {
            return parent::getPackagistVersions('laravel/framework');
        }

        /**
         * Get installable versions
         *
         * Checks laravel/laravel bootstrapper package
         *
         * @return array
         */
        public function get_installable_versions(): array
        {
            return parent::get_versions();
        }

        /**
         * Uninstall Laravel from a location
         *
         * @param        $hostname
         * @param string $path
         * @param string $delete remove all files under docroot
         * @return bool
         */
        public function uninstall(string $hostname, string $path = '', string $delete = 'all'): bool
        {
            return parent::uninstall($hostname, $path, $delete);
        }

        /**
         * Get database configuration for a blog
         *
         * @param string $hostname domain or subdomain of wp blog
         * @param string $path     optional path
         * @return array|bool
         */
        public function db_config(string $hostname, string $path = '')
        {
            $this->web_purge();
            $docroot = $this->getAppRoot($hostname, $path);
            if (!$docroot) {
                return error('failed to determine Laravel');
            }
            if (!file_exists($this->domain_fs_path($docroot . '/bootstrap/cache/config.php'))) {
                // prime it
                warn("Cache not found, priming with request");
                try {
                    (new \HTTP\SelfReferential($hostname, $this->site_ip_address()))->get($path);
                } catch (\GuzzleHttp\Exception\RequestException $e) {
                    return error("Self-referential request failed: %s", $e->getMessage());
                }
            }

            $code = '$cfg = (include("./bootstrap/cache/config.php"))["database"]; $db=$cfg["connections"][$cfg["default"]]; ' .
                'print serialize(array("user" => $db["username"], "password" => $db["password"], "db" => $db["database"], ' .
                '"host" => $db["host"], "prefix" => $db["prefix"]));';
            $cmd = 'cd %(path)s && php -d mysqli.default_socket=' . escapeshellarg(ini_get('mysqli.default_socket')) . ' -r %(code)s';
            $ret = $this->pman_run($cmd, array('path' => $docroot, 'code' => $code));

            if (!$ret['success']) {
                return error("failed to obtain Laravel configuration for `%s'", $docroot);
            }
            $data = \Util_PHP::unserialize($ret['stdout']);

            return $data;
        }

        /**
         * Check if version is latest or get latest version
         *
         * @param null|string $version
         * @param string|null $branchcomp
         * @return bool
         */
        public function is_current(string $version = null, string $branchcomp = null)
        {
            return parent::is_current($version, $branchcomp);
        }

        public function update_all(string $hostname, string $path = '', string $version = null): bool
        {
            return $this->update($hostname, $path, $version) || error('failed to update all components');
        }

        /**
         * Update Laravel to latest version
         *
         * @param string $hostname domain or subdomain under which WP is installed
         * @param string $path     optional subdirectory
         * @param string $version  version to upgrade
         * @return bool
         */
        public function update(string $hostname, string $path = '', string $version = null): bool
        {
            $docroot = $this->getDocumentRoot($hostname, $path);
            if (!$docroot) {
                return error('update failed');
            }
            $approot = $this->getAppRoot($hostname, $path);
            $newversion = $this->get_version($hostname, $path) ?? $version;
            $cmd = 'update laravel/framework' . ($version ? ':' . $version : '');
            $ret = $this->_execComposer($approot, $cmd);
            $error = [$ret['stderr']];
            if ($newversion !== $version && $ret['success']) {
                $ret['success'] = false;
                $error = [
                    "Failed to update Laravel from `%s' to `%s', check composer.json for version restrictions",
                    $newversion, $version
                ];
            }
            parent::setInfo($docroot, [
                'version' => $newversion,
                'failed'  => !$ret['success']
            ]);

            return $ret['success'] ?: error(...$error);
        }

        /**
         * Update Laravel plugins
         *
         * @param string $hostname domain or subdomain
         * @param string $path     optional path within host
         * @param array  $plugins
         * @return bool
         */
        public function update_plugins(string $hostname, string $path = '', array $plugins = array()): bool
        {
            return parent::update_plugins($hostname, $path, $plugins);
        }

        /**
         * Update Laravel themes
         *
         * @param string $hostname subdomain or domain
         * @param string $path     optional path under hostname
         * @param array  $themes
         * @return bool
         */
        public function update_themes(string $hostname, string $path = '', array $themes = array()): bool
        {
            return parent::update_themes($hostname, $path, $themes);
        }

        /**
         * Web application supports fortification
         *
         * @param string|null $mode optional mode (min, max)
         * @return bool
         */
        public function has_fortification(string $mode = null): bool
        {
            return parent::has_fortification($mode);
        }

        /**
         * Relax permissions to allow write-access
         *
         * @param string $hostname
         * @param string $path
         * @return bool
         * @internal param string $mode
         */
        public function unfortify(string $hostname, string $path = ''): bool
        {
            return parent::unfortify($hostname, $path);
        }

        public function plugin_status(string $hostname, string $path = '', string $plugin = null)
        {
            return false;
        }

        public function install_plugin(
            string $hostname,
            string $path = '',
            string $plugin,
            string $version = 'stable'
        ): bool {
            return false;
        }

        public function uninstall_plugin(string $hostname, string $path = '', string $plugin, bool $force = false): bool
        {
            return false;
        }

        public function disable_all_plugins(string $hostname, string $path = ''): bool
        {
            return false;
        }

        public function theme_status(string $hostname, string $path = '', string $theme = null)
        {
            return parent::theme_status($hostname, $path, $theme); // TODO: Change the autogenerated stub
        }

        public function install_theme(string $hostname, string $path = '', string $theme, string $version = null): bool
        {
            return parent::install_theme($hostname, $path, $theme, $version);
        }

        public function change_admin(string $hostname, string $path = '', array $fields): bool
        {
            return false;
        }

        public function get_admin(string $hostname, string $path = ''): ?string
        {
            return null;
        }

        public function next_version(string $version, string $maximalbranch = '99999999.99999999.99999999'): ?string
        {
            return parent::next_version($version, $maximalbranch);
        }


    }