1: <?php
2: declare(strict_types=1);
3: /**
4: * +------------------------------------------------------------+
5: * | apnscp |
6: * +------------------------------------------------------------+
7: * | Copyright (c) Apis Networks |
8: * +------------------------------------------------------------+
9: * | Licensed under Artistic License 2.0 |
10: * +------------------------------------------------------------+
11: * | Author: Matt Saladna (msaladna@apisnetworks.com) |
12: * +------------------------------------------------------------+
13: */
14:
15: use Module\Support\Webapps;
16: use Module\Support\Webapps\Traits\PublicRelocatable;
17:
18: /**
19: * Ghost management
20: *
21: * A blogging platform built on Node
22: *
23: * @package core
24: */
25: class Ghost_Module extends Webapps
26: {
27: // via https://ghost.org/faq/node-versions/
28: const DEFAULT_NODE = '12';
29: const GHOST_CLI_REPO = 'git+https://github.com/msaladna/ghost-cli-lite.git';
30: use PublicRelocatable {
31: getAppRoot as getAppRootReal;
32: }
33: const APP_NAME = 'Ghost';
34: const GHOST_CLI = 'ghost';
35: const DEFAULT_VERSION_LOCK = 'major';
36:
37: // via ghost/core/package.json
38: const NODE_VERSIONS = [
39: '0' => self::DEFAULT_NODE,
40: '4.0' => '12.10.0',
41: '4.5' => '12.22.1',
42: '4.6' => '14.16.1',
43: '4.21' => '14.18.0',
44: '5.0' => '16.19',
45: '5.30' => '18.12',
46: ];
47:
48: public function plugin_status(string $hostname, string $path = '', string $plugin = null)
49: {
50: return error('not supported');
51: }
52:
53: public function uninstall_plugin(string $hostname, string $path, string $plugin, bool $force = false): bool
54: {
55: return error('not supported');
56: }
57:
58: public function disable_all_plugins(string $hostname, string $path = ''): bool
59: {
60: return error('not supported');
61: }
62:
63:
64: public function restart(string $hostname, string $path = ''): bool
65: {
66: if (!$approot = $this->getAppRoot($hostname, $path)) {
67: return false;
68: }
69:
70: return \Module\Support\Webapps\Passenger::instantiateContexted($this->getAuthContext(),
71: [$approot, 'nodejs'])->restart();
72: }
73:
74: /**
75: * Get app root for Ghost
76: *
77: * @param string $hostname
78: * @param string $path
79: * @return null|string
80: */
81: protected function getAppRoot(string $hostname, string $path = ''): ?string
82: {
83: return $this->getAppRootReal($hostname, $path);
84: }
85:
86: /**
87: * Install Ghost into a pre-existing location
88: *
89: * @param string $hostname domain or subdomain to install Laravel
90: * @param string $path optional path under hostname
91: * @param array $opts additional install options
92: * @return bool
93: */
94: public function install(string $hostname, string $path = '', array $opts = array()): bool
95: {
96: if (!$this->mysql_enabled()) {
97: return error('%(what)s must be enabled to install %(app)s',
98: ['what' => 'MySQL', 'app' => static::APP_NAME]);
99: }
100: $available = null;
101: if (!$this->hasMemoryAllowance(768, $available)) {
102: return error("%(app)s requires at least %(min)d MB memory, `%(found)d' MB provided for account",
103: ['app' => 'Ghost', 'min' => 768, 'found' => $available]);
104: }
105: if (!$this->hasStorageAllowance(500, $available)) {
106: return error("%(app)s requires at least %(min)d MB storage. Only %(found).2f' MB provided for account",
107: ['app' => 'Ghost', 'min' => 500, 'found' => $available]);
108: }
109:
110: if (!$this->ssh_enabled()) {
111: return error('Ghost requires ssh service to be enabled');
112: }
113:
114: // assume all Ghost installs will be located in a parent directory
115: // once installed, relink the domain/subdomain to $docroot + /public
116: // also block installing under a path, because this would require either relocating
117: // Ghost outside any document root, e.g. /var/www/<hostname>-<path>-ghost and making
118: // a symlink, which fails once the parent document root moves (must use relative symlinks)
119: // and clutters up wherever they get located... no sound solution
120: if ($path) {
121: return error('Ghost may only be installed directly on a subdomain or domain without a child path, e.g. https://domain.com but not https://domain.com/ghost');
122: }
123:
124: if (!$this->parseInstallOptions($opts, $hostname, $path)) {
125: return false;
126: }
127:
128: $docroot = $this->getDocumentRoot($hostname, $path);
129:
130: if (!$this->platformVersionCheck((string)$opts['version'])) {
131: return error("Ghost %s cannot be installed on this platform", $opts['version']);
132: }
133:
134: $nodeVersion = $this->validateNode((string)$opts['version'], $opts['user'] ?? null);
135:
136: $wrapper = empty($opts['user']) ? $this : \apnscpFunctionInterceptor::factory(Auth::context($opts['user'],
137: $this->site));
138: $wrapper->node_make_default($nodeVersion, $docroot);
139:
140: $args['version'] = $opts['version'];
141:
142: $db = Webapps\DatabaseGenerator::mysql($this->getAuthContext(), $hostname);
143: $db->hostname = '127.0.0.1';
144: $db->connectionLimit = max($db->connectionLimit, 15);
145:
146: if (!$db->create()) {
147: return false;
148: }
149:
150: $args['dbhost'] = $db->hostname;
151: $args['dbkind'] = $db->kind;
152: $args['dbname'] = $db->database;
153: $args['dbuser'] = $db->username;
154: $args['dbpassword'] = $db->password;
155:
156: $fqdn = $this->web_normalize_hostname($hostname);
157: $args['uri'] = rtrim($fqdn . '/' . $path, '/');
158: $args['proto'] = empty($opts['ssl']) ? 'http://' : 'https://';
159: $args['debug'] = is_debug() ? '-V' : null;
160: if (is_debug()) {
161: warn("Disabling debug mode as it causes a maxBuffer exceeded error");
162: $args['debug'] = null;
163: }
164: // use localhost.localdomain, which is an alias to 127.0.0.1;
165: // ghost looks for "mysqld" if dbhost is localhost or 127.0.0.1;
166: // this isn't present in a synthetic root
167: $ret = $this->_exec($docroot,
168: 'ghost install %(debug)s --process=local --no-prompt --no-stack --no-start --no-color --db=%(dbkind)s --dbhost=%(dbhost)s --dbuser=%(dbuser)s --dbpass=%(dbpassword)s ' .
169: '--dbname=%(dbname)s --no-setup-linux-user --no-setup-nginx --url=%(proto)s%(uri)s --mail=sendmail %(version)s',
170: $args);
171:
172: if (!$ret['success']) {
173: info('removing temporary files');
174: $this->file_delete($docroot, true);
175: $db->rollback();
176:
177: return error('failed to download Ghost v%s: %s - possibly out of storage space?', $args['version'],
178: $ret['stdout']);
179: }
180:
181: $wrapper->node_make_default($nodeVersion, $docroot);
182:
183: if (!isset($opts['password'])) {
184: $opts['password'] = \Opcenter\Auth\Password::generate(10);
185: info("autogenerated password `%s'", $opts['password']);
186: }
187:
188: $username = $this->user_getpwnam($opts['user'] ?? $this->username)['gecos'] ?: $this->username;
189: info("setting displayed name to `%s'", $username);
190: $opts['url'] = rtrim($hostname . '/' . $path, '/');
191:
192: if (!$this->fixSymlink($docroot)) {
193: return error("Failed to correct current/ symlink in `%s'", $docroot);
194: }
195:
196: $this->fixThemeLink($docroot);
197:
198: if (null === ($docroot = $this->remapPublic($hostname, $path))) {
199: // it's more reasonable to fail at this stage, but let's try to complete
200: return error("Failed to remap Ghost to public/, manually remap from `%s' - Ghost setup is incomplete!",
201: $docroot);
202: }
203:
204: $approot = $this->getAppRoot($hostname, $path);
205: // @todo migrate cache management to reconfigure method
206: $config = [
207: 'useMinFiles' => 'true',
208: 'caching.frontend.maxAge' => 120,
209: 'logging.rotation.enabled' => 'true',
210: 'mail.transport' => 'sendmail',
211: // frontend caches + leave 5 for update/admin
212: 'database.pool.max' => 5,
213: 'paths.contentPath' => "${approot}/content"
214: ];
215:
216: foreach ($config as $c => $v) {
217: $ret = $this->_exec($approot, 'ghost config set %(c)s %(v)s', ['c' => $c, 'v' => $v]);
218: if (!$ret['success']) {
219: info('removing temporary files');
220: $this->file_delete($docroot, true);
221: $db->rollback();
222: return error("Failed to set configuration `%s': %s", $c, coalesce($ret['stderr'], $ret['stdout']));
223: }
224: }
225:
226: foreach (['tmp', 'public', 'logs'] as $dir) {
227: ($this->file_create_directory("${approot}/${dir}") &&
228: $this->file_chown("${approot}/${dir}", $opts['user'] ?? $this->username)
229: ) || warn("failed to create application directory `%s/%s'", $docroot, $dir);
230: }
231:
232:
233: $this->linkConfiguration($approot, 'production');
234:
235: if (!$wrapper->file_put_file_contents($docroot . '/.htaccess',
236: '# Enable caching' . "\n" .
237: 'UnsetEnv no-cache' . "\n" .
238: 'PassengerEnabled on' . "\n" .
239: 'PassengerAppEnv production' . "\n" .
240: 'PassengerStartupFile current/index.js' . "\n" .
241: 'PassengerAppType node' . "\n" .
242: 'PassengerAppRoot ' . $approot . "\n"
243: )) {
244: return error('failed to create .htaccess control - Ghost is not properly setup');
245: }
246:
247: $this->setInterpreter($docroot, $nodeVersion);
248:
249: $wrapper->node_do($nodeVersion, null, 'npm install -g --production knex-migrator');
250: $ret = $wrapper->node_do($nodeVersion, "${approot}/current", 'knex-migrator init', [], ['NODE_ENV' => 'production']);
251: if (!$ret['success']) {
252: return error('Failed to create initial database configuration - knex-migrator failed: %s',
253: $ret['stdout']);
254: }
255: if (!$this->migrate($approot)) {
256: return error('Failed to migrate database configuration - Ghost installation incomplete');
257: }
258: $this->change_admin($hostname, $path, [
259: 'email' => $opts['email'],
260: 'password' => $opts['password'],
261: 'name' => $username
262: ]);
263:
264: $this->notifyInstalled($hostname, $path, $opts);
265:
266: return info('%(app)s installed - confirmation email with login info sent to %(email)s',
267: ['app' => static::APP_NAME, 'email' => $opts['email']]);
268: }
269:
270: private function setInterpreter(string $docroot, string $nodeVersion): bool
271: {
272: $htaccess = $this->file_get_file_contents("{$docroot}/.htaccess");
273: $new = preg_replace(
274: '/\R(?:^PassengerNodejs .*$|$)/m',
275: "\n". 'PassengerNodejs ' . $this->getNodeCommand($nodeVersion, $this->file_stat($docroot)['owner']),
276: $htaccess,
277: 1
278: );
279: return $this->file_put_file_contents("{$docroot}/.htaccess", $new);
280: }
281:
282: /**
283: * Verify Node LTS is installed
284: *
285: * @param string|null $version optional version to compare against
286: * @param string|null $user
287: * @return null|string
288: */
289: protected function validateNode(string $version = self::DEFAULT_NODE, string $user = null): ?string
290: {
291: if ($user) {
292: $afi = \apnscpFunctionInterceptor::factory(Auth::context($user, $this->site));
293: }
294: $wrapper = $afi ?? $this;
295: $nodeVersion = \Opcenter\Versioning::satisfy($version, self::NODE_VERSIONS);
296: foreach ([\Opcenter\Versioning::asMajor($nodeVersion), $nodeVersion] as $testVersion) {
297: if (($chk = $wrapper->node_installed($testVersion)) && version_compare($chk, $nodeVersion, '>='))
298: {
299: $nodeVersion = $chk;
300: break;
301: }
302: }
303:
304: if (!$wrapper->node_installed($nodeVersion) && !$wrapper->node_install($nodeVersion)) {
305: error('failed to install Node %s', $nodeVersion);
306: return null;
307: }
308:
309: $wrapper->node_do($nodeVersion, null, 'nvm use --delete-prefix');
310: $ret = $wrapper->node_do($nodeVersion, null, 'npm install -g ' . self::GHOST_CLI_REPO);
311: if (!$ret['success']) {
312: error('failed to install ghost-cli: %s', $ret['stderr'] ?? 'UNKNOWN ERROR');
313: return null;
314: }
315: $home = $this->user_get_home($user);
316: $stat = $this->file_stat($home);
317: if (!$stat || !$this->file_chmod($home, decoct($stat['permissions']) | 0001)) {
318: error("failed to query user home directory `%s' for user `%s'", $home, $user);
319: return null;
320: }
321:
322: return $nodeVersion;
323: }
324:
325: private function _exec(?string $path, $cmd, array $args = array(), $env = array())
326: {
327: // client may override tz, propagate to bin
328: if (!is_array($args)) {
329: $args = func_get_args();
330: array_shift($args);
331: }
332:
333: $wrapper = $this->getApnscpFunctionInterceptorFromDocroot($path ?? '~');
334: $ret = $wrapper->node_do(
335: null,
336: $path,
337: $cmd,
338: $args,
339: $env + [
340: 'NODE_ENV' => 'production'
341: ]);
342: if (!strncmp(coalesce($ret['stderr'], $ret['stdout']), 'Error:', strlen('Error:'))) {
343: // move stdout to stderr on error for consistency
344: $ret['success'] = false;
345: if (!$ret['stderr']) {
346: $ret['stderr'] = $ret['stdout'];
347: }
348: }
349:
350: return $ret;
351: }
352:
353: /**
354: * Get installed version
355: *
356: * @param string $hostname or $docroot
357: * @param string $path
358: * @return string version number
359: */
360: public function get_version(string $hostname, string $path = ''): ?string
361: {
362: if (!$this->valid($hostname, $path)) {
363: return null;
364: }
365: if ($hostname[0] !== '/') {
366: $approot = $this->getAppRoot($hostname, $path);
367: } else {
368: $approot = Webapps\App\Loader::fromDocroot('ghost', $hostname, $this->getAuthContext())->getAppRoot();
369: }
370: $path = $this->domain_fs_path($approot . '/current/package.json');
371: clearstatcache(true, \dirname($path));
372: clearstatcache(true, $path);
373: if (!file_exists($path)) {
374: warn('missing package.json from Ghost root - cannot detect version');
375:
376: return null;
377: }
378:
379: return json_decode(file_get_contents($path))->version;
380: }
381:
382: /**
383: * Location is a valid Ghost install
384: *
385: * @param string $hostname or $docroot
386: * @param string $path
387: * @return bool
388: */
389: public function valid(string $hostname, string $path = ''): bool
390: {
391: if (!IS_CLI) {
392: return $this->query('ghost_valid', $hostname, $path);
393: }
394:
395: if ($hostname[0] === '/') {
396: if (!($path = realpath($this->domain_fs_path($hostname)))) {
397: return false;
398: }
399: $approot = \dirname($path);
400: } else {
401: $approot = $this->getAppRoot($hostname, $path);
402: if (!$approot) {
403: return false;
404: }
405: $approot = $this->domain_fs_path($approot);
406: }
407: if (is_link($approot . '/current') && readlink($approot . '/current')[0] === '/') {
408: $this->fixSymlink($this->file_unmake_path($approot));
409: }
410:
411: $tests = [
412: 'core/server/ghost-server.js',
413: 'core/server/GhostServer.js',
414: 'core/core/server/GhostServer.js'
415: ];
416:
417: foreach ($tests as $test) {
418: if (file_exists("{$approot}/current/{$test}")) {
419: return true;
420: }
421: }
422:
423: return false;
424: }
425:
426: /**
427: * Relink current/ from absolute to relative symlink
428: *
429: * @param string $approot
430: * @return bool
431: */
432: private function fixSymlink(string $approot): bool
433: {
434: $path = $this->domain_fs_path("${approot}/current");
435: clearstatcache(true, $path);
436: if (!is_link($path)) {
437: return error("${approot}/current missing - can't relink");
438: }
439: $link = readlink($path);
440: if ($link[0] !== '/') {
441: // relative link
442: $stat = $this->file_stat("${approot}/current");
443:
444: return !empty($stat['referent']) ? true : error("${approot}/current does not point to an active Ghost install");
445: }
446:
447: if (0 !== strpos($link, $approot)) {
448: return false;
449: }
450: // debugging code...
451: if (!$this->file_delete($approot . '/current') || !$this->file_symlink($link, $approot . '/current')) {
452: return false;
453: }
454:
455: return $this->file_chown_symlink($approot . '/current', $this->file_stat($approot)['owner']);
456: }
457:
458: /**
459: * Correct theme link when Ghost is installed in primary docroot
460: *
461: * @param string $approot
462: * @return bool
463: */
464: private function fixThemeLink(string $approot): bool
465: {
466: $path = $this->domain_fs_path("${approot}/content/themes");
467: if (!file_exists($path)) {
468: return warn('Cannot correct theme symlinks, cannot find theme path');
469: }
470: $dh = opendir($path);
471: while (false !== ($file = readdir($dh))) {
472: if ($file === '.' || $file === '..') {
473: continue;
474: }
475: if (!is_link("${path}/${file}")) {
476: continue;
477: }
478: $link = readlink("${path}/${file}");
479: if (0 !== strpos($link . '/', Web_Module::MAIN_DOC_ROOT . '/')) {
480: continue;
481: }
482: $localpath = $this->file_unmake_path("${path}/${file}");
483: $this->file_delete($localpath) && $this->file_symlink($approot . substr($link,
484: strlen(Web_Module::MAIN_DOC_ROOT)),
485: $localpath);
486: }
487: closedir($dh);
488:
489: return true;
490: }
491:
492: /**
493: * Get path to active Node
494: *
495: * @param string|null $version
496: * @param string|null $user
497: * @return null|string
498: */
499: protected function getNodeCommand(string $version = 'lts', string $user = null): ?string
500: {
501: if ($user) {
502: $afi = \apnscpFunctionInterceptor::factory(Auth::context($user, $this->site));
503: }
504: $ret = ($afi ?? $this)->node_do($version, null, 'which node');
505:
506: return $ret['success'] ? trim($ret['output']) : null;
507: }
508:
509: /**
510: * Migrate database configuration to current/
511: *
512: * @param string $approot
513: * @param string $appenv
514: * @return bool
515: */
516: private function linkConfiguration(string $approot, string $appenv = 'production'): bool
517: {
518: $this->file_delete($approot . "/current/config.${appenv}.json");
519:
520: return $this->file_symlink($approot . "/config.${appenv}.json",
521: $approot . "/current/config.${appenv}.json") ||
522: warn("failed to link configuration ${approot}/config.${appenv}.json to current/");
523: }
524:
525: /**
526: * Migrate Ghost database
527: *
528: * @param string $approot
529: * @param string $appenv optional app environment to source DB config
530: * @return bool
531: */
532: private function migrate(string $approot, string $appenv = 'production'): bool
533: {
534: $this->linkConfiguration($approot, $appenv);
535: $this->_exec("$approot/current", 'which knex-migrator > /dev/null || npm install --no-dev -g knex-migrator');
536: $ret = $this->_exec("${approot}/current", 'knex-migrator migrate');
537:
538: return $ret['success'] ?: error("failed to migrate database in `%s': %s", $approot,
539: coalesce($ret['stdout'], $ret['stderr']));
540: }
541:
542: /**
543: * Change Ghost admin credentials
544: *
545: * Common fields include: password, email, name; email doubles as login
546: *
547: * @param string $hostname
548: * @param string $path
549: * @param array $fields
550: * @return bool
551: */
552: public function change_admin(string $hostname, string $path, array $fields): bool
553: {
554: $docroot = $this->getAppRoot($hostname, $path);
555: if (!$docroot) {
556: return warn('failed to change administrator information');
557: }
558: $admin = $this->get_admin($hostname, $path);
559:
560: if (!$admin) {
561: return error('cannot determine admin of Ghost install');
562: }
563:
564: if (isset($fields['password'])) {
565: if (!\Opcenter\Auth\Password::strong($fields['password'])) {
566: return false;
567: }
568: $fields['password'] = password_hash($fields['password'], PASSWORD_BCRYPT, ['cost' => 10]);
569: }
570: if (isset($fields['name'])) {
571: $fields['slug'] = str_slug($fields['name']);
572: }
573:
574: $db = $this->connectDB($hostname, $path);
575: $q = "UPDATE users SET status = 'active'";
576: foreach (['password', 'email', 'name', 'slug'] as $field) {
577: if (!isset($fields[$field])) {
578: continue;
579: }
580: $q .= ", {$field} = '" . $db->escape_string($fields[$field]) . "'";
581: }
582: $q .= " WHERE email = '" . $admin . "'";
583: if (false === $db->query($q) || $db->affected_rows() < 1) {
584: return error("Failed to change admin user `%s'", $admin);
585: }
586: if (isset($fields['email'])) {
587: info('user login changed to %s', $fields['email']);
588: }
589: if (isset($fields['password'])) {
590: info("user `%s' password changed", $fields['email'] ?? $admin);
591: }
592:
593: return true;
594: }
595:
596: /**
597: * Get the primary admin for a WP instance
598: *
599: * @param string $hostname
600: * @param null|string $path
601: * @return string admin or false on failure
602: */
603: public function get_admin(string $hostname, string $path = ''): ?string
604: {
605: $mysql = $this->connectDB($hostname, $path);
606: $rs = $mysql->query('SELECT email FROM users WHERE id = 1');
607: if (!$rs || $rs->num_rows < 1) {
608: return null;
609: }
610:
611: return $rs->fetch_object()->email;
612: }
613:
614: private function connectDB($hostname, $path): \MySQL
615: {
616: $dbconfig = $this->db_config($hostname, $path);
617: $host = $dbconfig['host'] === 'localhost.localdomain' ? '127.0.0.1' : $dbconfig['host'];
618:
619: return \MySQL::stub()->connect($host, $dbconfig['user'], $dbconfig['password'], $dbconfig['db']);
620: }
621:
622: /**
623: * Get database configuration for a blog
624: *
625: * @param string $hostname domain or subdomain of wp blog
626: * @param string $path optional path
627: * @return bool|array
628: */
629: public function db_config(string $hostname, string $path = '')
630: {
631: $approot = $this->getAppRoot($hostname, $path);
632: if (!$approot) {
633: error('failed to determine Ghost config - ' . $approot);
634:
635: return [];
636: }
637: foreach (['development', 'production'] as $env) {
638: $path = "${approot}/config.${env}.json";
639: if ($this->file_exists($path)) {
640: // @todo unify config into a consistent object
641: $json = json_decode($this->file_get_file_contents($path), true)['database']['connection'];
642: if (!$json) {
643: continue;
644: }
645: $json['db'] = $json['database'];
646: $json['prefix'] = '';
647:
648: return $json;
649: }
650: }
651:
652: return [];
653: }
654:
655: /**
656: * Install and activate plugin
657: *
658: * @param string $hostname domain or subdomain of wp install
659: * @param string $path optional path component of wp install
660: * @param string $plugin plugin name
661: * @param string $version optional plugin version
662: * @return bool
663: */
664: public function install_plugin(
665: string $hostname,
666: string $path,
667: string $plugin,
668: string $version = 'stable'
669: ): bool {
670: return error('not supported');
671: }
672:
673: /**
674: * Uninstall WP from a location
675: *
676: * @param $hostname
677: * @param string $path
678: * @param string $delete remove all files under docroot
679: * @return bool
680: */
681: public function uninstall(string $hostname, string $path = '', string $delete = 'all'): bool
682: {
683: $this->kill($hostname, $path);
684:
685: return parent::uninstall($hostname, $path, $delete);
686: }
687:
688: /**
689: * Update core, plugins, and themes atomically
690: *
691: * @param string $hostname subdomain or domain
692: * @param string $path optional path under hostname
693: * @param string $version
694: * @return bool
695: */
696: public function update_all(string $hostname, string $path = '', string $version = null): bool
697: {
698: return $this->update($hostname, $path, $version) || error('failed to update all components');
699: }
700:
701: /**
702: * Update Ghost to latest version
703: *
704: * @param string $hostname domain or subdomain under which WP is installed
705: * @param string $path optional subdirectory
706: * @param string $version
707: * @return bool
708: */
709: public function update(string $hostname, string $path = '', string $version = null): bool
710: {
711: $approot = $this->getAppRoot($hostname, $path);
712: if (!$approot) {
713: return error('update failed');
714: }
715:
716: $docroot = $this->getDocumentRoot($hostname, $path);
717: if (!$version) {
718: $version = \Opcenter\Versioning::nextVersion($this->get_versions(),
719: $this->get_version($hostname, $path));
720: } else if (!\Opcenter\Versioning::valid($version)) {
721: return error('invalid version number, %s', $version);
722: }
723:
724: if (!$this->platformVersionCheck($version)) {
725: return error("Ghost %s cannot be installed on this platform", $version);
726: }
727:
728: $this->file_chmod($approot, 705);
729:
730: $oldversion = $this->get_version($hostname, $path);
731: if ($oldversion === $version) {
732: return info("Ghost is already at current version `%s'", $version);
733: }
734: $oldNodeVersion = $this->node_version_from_path($approot);
735:
736: if ($oldNodeVersion !== ($nodeVersion = $this->validateNode($version, $this->getDocrootUser($approot)))) {
737: info("Updating Node %(old)s => %(new)s per dependency requirements of Ghost %(ghostver)s", [
738: 'old' => $oldNodeVersion,
739: 'new' => $nodeVersion,
740: 'ghostver' => $version
741: ]);
742: // @TODO bounce Apache?
743: defer($_, fn() => $this->setInterpreter($this->getDocumentRoot($hostname, $path), $nodeVersion));
744: }
745:
746: if (\Opcenter\Versioning::asMajor($version) !== \Opcenter\Versioning::asMajor($oldversion)) {
747: // newer ghost-cli are sudo-happy
748: if (!$this->_exec($approot, 'ghost update %s --local --no-restart --no-color --v%d',
749: [
750: null,
751: \Opcenter\Versioning::asMajor($oldversion)
752: ])) {
753: return error('Failed to prep for major version upgrade');
754: }
755:
756: return error('Ghost upgrade must be manually completed. Run the following command to use the migration assistant: ' .
757: 'cd %s && NODE_ENV=production nvm exec ghost update --local -f', $approot);
758: }
759: // force version assertion on incomplete upgrade
760: $this->assertLocalVersion($approot, $oldversion, $version);
761: // more bad permission requirements, -D bypasses chmod requirement
762:
763: $cmd = 'ghost update %(debug)s --no-restart --local --no-prompt --no-color %(version)s';
764: // disable debug mode for now, causes stdout maxBuffer exceeded error
765: if (is_debug()) {
766: warn("Disabling debug mode as it causes a maxBuffer exceeded error");
767: }
768:
769: $args['debug'] = null;
770: $args['version'] = $version;
771: $ret = $this->_exec($approot, $cmd, $args);
772: $this->fixSymlink($approot);
773: $this->file_touch("${approot}/tmp/restart.txt");
774: if (!$ret['success']) {
775: $this->setInfo($this->getDocumentRoot($hostname, $path), [
776: 'version' => $this->get_version($hostname, $path),
777: 'failed' => true
778: ]);
779:
780: $this->assertLocalVersion($approot, $oldversion, $version);
781:
782: return error('failed to update Ghost: %s', coalesce($ret['stderr'], $ret['stdout']));
783: }
784:
785: $ret = $this->migrate($approot) && ($this->kill($hostname, $path) || true);
786: $this->setInterpreter($docroot, $nodeVersion);
787: if ($version !== ($newver = $this->get_version($hostname, $path))) {
788: report("Upgrade failed, reported version `%s' is not requested version `%s'", $newver, $version);
789: } else if ($ret) {
790: // unlink previous version
791: $this->file_delete("{$approot}/versions/{$oldversion}", true);
792: // cleanup orphaned packages
793: $this->_exec($approot, 'npm prune');
794: }
795:
796: $this->setInfo($docroot, [
797: 'version' => $newver,
798: 'failed' => !$ret
799: ]);
800:
801: return $ret;
802: }
803:
804: /**
805: * Assert local Ghost CLI version matches expected
806: *
807: * @param string $approot
808: * @param string $version
809: * @return bool true if assertion passes, false if change forced
810: */
811: private function assertLocalVersion(string $approot, string $version, string $targetVersion = null): bool
812: {
813: $json = $this->file_get_file_contents($approot . '/.ghost-cli');
814: $meta = json_decode($json, true);
815: if (!is_array($meta)) {
816: return error("Failed decoding meta in `%s': %s", $approot, json_last_error_msg());
817: }
818:
819: if ($targetVersion) {
820: $stat = $this->file_stat($approot . '/versions/' . $targetVersion);
821: if ($stat && $stat['referent']) {
822: $this->file_delete($approot . '/versions/' . $targetVersion);
823: }
824: }
825:
826: if (($myver = array_get($meta, 'active-version')) === $version) {
827: return true;
828: }
829:
830: info("Version in %(approot)s reported as %(oldver)s - forcing version as %(newver)s",
831: ['approot' => $approot, 'oldver' => $myver, 'newver' => $version]);
832: $meta['active-version'] = $version;
833:
834: return $this->file_put_file_contents($approot . '/.ghost-cli', json_encode($meta), true) > 0;
835: }
836:
837: /**
838: * Get all available Ghost versions
839: *
840: * @return array
841: */
842: public function get_versions(): array
843: {
844: $versions = $this->_getVersions();
845: return array_column($versions, 'version');
846: }
847:
848: public function get_installable_versions(): array
849: {
850: return array_filter($this->get_versions(), $this->platformVersionCheck(...));
851: }
852:
853: /**
854: * Ghost version supported by platform
855: *
856: * @param string $version
857: * @return bool
858: */
859: private function platformVersionCheck(string $version): bool
860: {
861: // Ghost v5+ requires MySQL v8
862: return version_compare($version, '5.21', '<') || version_compare($version, '5.24.0', '>=');
863: }
864:
865: /**
866: * Get all current major versions
867: *
868: * @return array
869: */
870: private function _getVersions(): array
871: {
872: $key = 'ghost.versions';
873: $cache = Cache_Super_Global::spawn();
874: if (false !== ($ver = $cache->get($key))) {
875: return (array)$ver;
876: }
877: $versions = array_filter(
878: (new Webapps\VersionFetcher\PackageJson)->fetch('ghost', static function ($item) {
879: if (isset($item['deprecated'])) {
880: return null;
881: }
882:
883: return version_compare($item['version'], '5.0.0','<') || version_compare($item['version'], '5.24.1', '>=')
884: ? $item : null;
885: }
886: ));
887:
888: $cache->set($key, $versions, 43200);
889:
890: return $versions;
891: }
892:
893: /**
894: * Update plugins
895: *
896: * @param string $hostname domain or subdomain
897: * @param string $path optional path within host
898: * @param array $plugins
899: * @return bool
900: */
901: public function update_plugins(string $hostname, string $path = '', array $plugins = array()): bool
902: {
903: return error('not implemented');
904: }
905:
906: /**
907: * Update Laravel themes
908: *
909: * @param string $hostname subdomain or domain
910: * @param string $path optional path under hostname
911: * @param array $themes
912: * @return bool
913: */
914: public function update_themes(string $hostname, string $path = '', array $themes = array()): bool
915: {
916: return error('not implemented');
917: }
918:
919: /**
920: * @inheritDoc
921: */
922: public function has_fortification(string $hostname, string $path = '', string $mode = null): bool
923: {
924: return false;
925: }
926:
927: /**
928: * Restrict write-access by the app
929: *
930: * @param string $hostname
931: * @param string $path
932: * @param string $mode
933: * @param array $args
934: * @return bool
935: */
936: public function fortify(string $hostname, string $path = '', string $mode = 'max', $args = []): bool
937: {
938: return error('not implemented');
939: }
940:
941: /**
942: * Relax permissions to allow write-access
943: *
944: * @param string $hostname
945: * @param string $path
946: * @return bool
947: * @internal param string $mode
948: */
949: public function unfortify(string $hostname, string $path = ''): bool
950: {
951: return error('not implemented');
952: }
953: }
954: