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->initializeMeta($docroot, $opts);
234:
235: $this->linkConfiguration($approot, 'production');
236:
237: if (!$wrapper->file_put_file_contents($docroot . '/.htaccess',
238: '# Enable caching' . "\n" .
239: 'UnsetEnv no-cache' . "\n" .
240: 'PassengerEnabled on' . "\n" .
241: 'PassengerAppEnv production' . "\n" .
242: 'PassengerStartupFile current/index.js' . "\n" .
243: 'PassengerAppType node' . "\n" .
244: 'PassengerAppRoot ' . $approot . "\n"
245: )) {
246: return error('failed to create .htaccess control - Ghost is not properly setup');
247: }
248:
249: $this->setInterpreter($docroot, $nodeVersion);
250:
251: $wrapper->node_do($nodeVersion, null, 'npm install -g --production knex-migrator');
252: $ret = $wrapper->node_do($nodeVersion, "${approot}/current", 'knex-migrator init', [], ['NODE_ENV' => 'production']);
253: if (!$ret['success']) {
254: return error('Failed to create initial database configuration - knex-migrator failed: %s',
255: $ret['stdout']);
256: }
257: if (!$this->migrate($approot)) {
258: return error('Failed to migrate database configuration - Ghost installation incomplete');
259: }
260: $this->change_admin($hostname, $path, [
261: 'email' => $opts['email'],
262: 'password' => $opts['password'],
263: 'name' => $username
264: ]);
265:
266: $this->notifyInstalled($hostname, $path, $opts);
267:
268: return info('%(app)s installed - confirmation email with login info sent to %(email)s',
269: ['app' => static::APP_NAME, 'email' => $opts['email']]);
270: }
271:
272: private function setInterpreter(string $docroot, string $nodeVersion): bool
273: {
274: $htaccess = $this->file_get_file_contents("{$docroot}/.htaccess");
275: $new = preg_replace(
276: '/\R(?:^PassengerNodejs .*$|$)/m',
277: "\n". 'PassengerNodejs ' . $this->getNodeCommand($nodeVersion, $this->file_stat($docroot)['owner']),
278: $htaccess,
279: 1
280: );
281: return $this->file_put_file_contents("{$docroot}/.htaccess", $new);
282: }
283:
284: /**
285: * Verify Node LTS is installed
286: *
287: * @param string|null $version optional version to compare against
288: * @param string|null $user
289: * @return null|string
290: */
291: protected function validateNode(string $version = self::DEFAULT_NODE, string $user = null): ?string
292: {
293: if ($user) {
294: $afi = \apnscpFunctionInterceptor::factory(Auth::context($user, $this->site));
295: }
296: $wrapper = $afi ?? $this;
297: $nodeVersion = \Opcenter\Versioning::satisfy($version, self::NODE_VERSIONS);
298: foreach ([\Opcenter\Versioning::asMajor($nodeVersion), $nodeVersion] as $testVersion) {
299: if (($chk = $wrapper->node_installed($testVersion)) && version_compare($chk, $nodeVersion, '>='))
300: {
301: $nodeVersion = $chk;
302: break;
303: }
304: }
305:
306: if (!$wrapper->node_installed($nodeVersion) && !$wrapper->node_install($nodeVersion)) {
307: error('failed to install Node %s', $nodeVersion);
308: return null;
309: }
310:
311: $wrapper->node_do($nodeVersion, null, 'nvm use --delete-prefix');
312: $ret = $wrapper->node_do($nodeVersion, null, 'npm install -g ' . self::GHOST_CLI_REPO);
313: if (!$ret['success']) {
314: error('failed to install ghost-cli: %s', $ret['stderr'] ?? 'UNKNOWN ERROR');
315: return null;
316: }
317: $home = $this->user_get_home($user);
318: $stat = $this->file_stat($home);
319: if (!$stat || !$this->file_chmod($home, decoct($stat['permissions']) | 0001)) {
320: error("failed to query user home directory `%s' for user `%s'", $home, $user);
321: return null;
322: }
323:
324: return $nodeVersion;
325: }
326:
327: private function _exec(?string $path, $cmd, array $args = array(), $env = array())
328: {
329: // client may override tz, propagate to bin
330: if (!is_array($args)) {
331: $args = func_get_args();
332: array_shift($args);
333: }
334:
335: $wrapper = $this->getApnscpFunctionInterceptorFromDocroot($path ?? '~');
336: $ret = $wrapper->node_do(
337: null,
338: $path,
339: $cmd,
340: $args,
341: $env + [
342: 'NODE_ENV' => 'production'
343: ]);
344: if (!strncmp(coalesce($ret['stderr'], $ret['stdout']), 'Error:', strlen('Error:'))) {
345: // move stdout to stderr on error for consistency
346: $ret['success'] = false;
347: if (!$ret['stderr']) {
348: $ret['stderr'] = $ret['stdout'];
349: }
350: }
351:
352: return $ret;
353: }
354:
355: /**
356: * Get installed version
357: *
358: * @param string $hostname or $docroot
359: * @param string $path
360: * @return string version number
361: */
362: public function get_version(string $hostname, string $path = ''): ?string
363: {
364: if (!$this->valid($hostname, $path)) {
365: return null;
366: }
367: if ($hostname[0] !== '/') {
368: $approot = $this->getAppRoot($hostname, $path);
369: } else {
370: $approot = Webapps\App\Loader::fromDocroot('ghost', $hostname, $this->getAuthContext())->getAppRoot();
371: }
372: $path = $this->domain_fs_path($approot . '/current/package.json');
373: clearstatcache(true, \dirname($path));
374: clearstatcache(true, $path);
375: if (!file_exists($path)) {
376: warn('missing package.json from Ghost root - cannot detect version');
377:
378: return null;
379: }
380:
381: return json_decode(file_get_contents($path))->version;
382: }
383:
384: /**
385: * Location is a valid Ghost install
386: *
387: * @param string $hostname or $docroot
388: * @param string $path
389: * @return bool
390: */
391: public function valid(string $hostname, string $path = ''): bool
392: {
393: if (!IS_CLI) {
394: return $this->query('ghost_valid', $hostname, $path);
395: }
396:
397: if ($hostname[0] === '/') {
398: if (!($path = realpath($this->domain_fs_path($hostname)))) {
399: return false;
400: }
401: $approot = \dirname($path);
402: } else {
403: $approot = $this->getAppRoot($hostname, $path);
404: if (!$approot) {
405: return false;
406: }
407: $approot = $this->domain_fs_path($approot);
408: }
409: if (is_link($approot . '/current') && readlink($approot . '/current')[0] === '/') {
410: $this->fixSymlink($this->file_unmake_path($approot));
411: }
412:
413: $tests = [
414: 'core/server/ghost-server.js',
415: 'core/server/GhostServer.js',
416: 'core/core/server/GhostServer.js'
417: ];
418:
419: foreach ($tests as $test) {
420: if (file_exists("{$approot}/current/{$test}")) {
421: return true;
422: }
423: }
424:
425: return false;
426: }
427:
428: /**
429: * Relink current/ from absolute to relative symlink
430: *
431: * @param string $approot
432: * @return bool
433: */
434: private function fixSymlink(string $approot): bool
435: {
436: $path = $this->domain_fs_path("${approot}/current");
437: clearstatcache(true, $path);
438: if (!is_link($path)) {
439: return error("${approot}/current missing - can't relink");
440: }
441: $link = readlink($path);
442: if ($link[0] !== '/') {
443: // relative link
444: $stat = $this->file_stat("${approot}/current");
445:
446: return !empty($stat['referent']) ? true : error("${approot}/current does not point to an active Ghost install");
447: }
448:
449: if (0 !== strpos($link, $approot)) {
450: return false;
451: }
452: // debugging code...
453: if (!$this->file_delete($approot . '/current') || !$this->file_symlink($link, $approot . '/current')) {
454: return false;
455: }
456:
457: return $this->file_chown_symlink($approot . '/current', $this->file_stat($approot)['owner']);
458: }
459:
460: /**
461: * Correct theme link when Ghost is installed in primary docroot
462: *
463: * @param string $approot
464: * @return bool
465: */
466: private function fixThemeLink(string $approot): bool
467: {
468: $path = $this->domain_fs_path("${approot}/content/themes");
469: if (!file_exists($path)) {
470: return warn('Cannot correct theme symlinks, cannot find theme path');
471: }
472: $dh = opendir($path);
473: while (false !== ($file = readdir($dh))) {
474: if ($file === '.' || $file === '..') {
475: continue;
476: }
477: if (!is_link("${path}/${file}")) {
478: continue;
479: }
480: $link = readlink("${path}/${file}");
481: if (0 !== strpos($link . '/', Web_Module::MAIN_DOC_ROOT . '/')) {
482: continue;
483: }
484: $localpath = $this->file_unmake_path("${path}/${file}");
485: $this->file_delete($localpath) && $this->file_symlink($approot . substr($link,
486: strlen(Web_Module::MAIN_DOC_ROOT)),
487: $localpath);
488: }
489: closedir($dh);
490:
491: return true;
492: }
493:
494: /**
495: * Get path to active Node
496: *
497: * @param string|null $version
498: * @param string|null $user
499: * @return null|string
500: */
501: protected function getNodeCommand(string $version = 'lts', string $user = null): ?string
502: {
503: if ($user) {
504: $afi = \apnscpFunctionInterceptor::factory(Auth::context($user, $this->site));
505: }
506: $ret = ($afi ?? $this)->node_do($version, null, 'which node');
507:
508: return $ret['success'] ? trim($ret['output']) : null;
509: }
510:
511: /**
512: * Migrate database configuration to current/
513: *
514: * @param string $approot
515: * @param string $appenv
516: * @return bool
517: */
518: private function linkConfiguration(string $approot, string $appenv = 'production'): bool
519: {
520: $this->file_delete($approot . "/current/config.${appenv}.json");
521:
522: return $this->file_symlink($approot . "/config.${appenv}.json",
523: $approot . "/current/config.${appenv}.json") ||
524: warn("failed to link configuration ${approot}/config.${appenv}.json to current/");
525: }
526:
527: /**
528: * Migrate Ghost database
529: *
530: * @param string $approot
531: * @param string $appenv optional app environment to source DB config
532: * @return bool
533: */
534: private function migrate(string $approot, string $appenv = 'production'): bool
535: {
536: $this->linkConfiguration($approot, $appenv);
537: $this->_exec("$approot/current", 'which knex-migrator > /dev/null || npm install --no-dev -g knex-migrator');
538: $ret = $this->_exec("${approot}/current", 'knex-migrator migrate');
539:
540: return $ret['success'] ?: error("failed to migrate database in `%s': %s", $approot,
541: coalesce($ret['stdout'], $ret['stderr']));
542: }
543:
544: /**
545: * Change Ghost admin credentials
546: *
547: * Common fields include: password, email, name; email doubles as login
548: *
549: * @param string $hostname
550: * @param string $path
551: * @param array $fields
552: * @return bool
553: */
554: public function change_admin(string $hostname, string $path, array $fields): bool
555: {
556: $docroot = $this->getAppRoot($hostname, $path);
557: if (!$docroot) {
558: return warn('failed to change administrator information');
559: }
560: $admin = $this->get_admin($hostname, $path);
561:
562: if (!$admin) {
563: return error('cannot determine admin of Ghost install');
564: }
565:
566: if (isset($fields['password'])) {
567: if (!\Opcenter\Auth\Password::strong($fields['password'])) {
568: return false;
569: }
570: $fields['password'] = password_hash($fields['password'], PASSWORD_BCRYPT, ['cost' => 10]);
571: }
572: if (isset($fields['name'])) {
573: $fields['slug'] = str_slug($fields['name']);
574: }
575:
576: $db = $this->connectDB($hostname, $path);
577: $q = "UPDATE users SET status = 'active'";
578: foreach (['password', 'email', 'name', 'slug'] as $field) {
579: if (!isset($fields[$field])) {
580: continue;
581: }
582: $q .= ", {$field} = '" . $db->escape_string($fields[$field]) . "'";
583: }
584: $q .= " WHERE email = '" . $admin . "'";
585: if (false === $db->query($q) || $db->affected_rows() < 1) {
586: return error("Failed to change admin user `%s'", $admin);
587: }
588: if (isset($fields['email'])) {
589: info('user login changed to %s', $fields['email']);
590: }
591: if (isset($fields['password'])) {
592: info("user `%s' password changed", $fields['email'] ?? $admin);
593: }
594:
595: return true;
596: }
597:
598: /**
599: * Get the primary admin for a WP instance
600: *
601: * @param string $hostname
602: * @param null|string $path
603: * @return string admin or false on failure
604: */
605: public function get_admin(string $hostname, string $path = ''): ?string
606: {
607: $mysql = $this->connectDB($hostname, $path);
608: $rs = $mysql->query('SELECT email FROM users WHERE id = 1');
609: if (!$rs || $rs->num_rows < 1) {
610: return null;
611: }
612:
613: return $rs->fetch_object()->email;
614: }
615:
616: private function connectDB($hostname, $path): \MySQL
617: {
618: $dbconfig = $this->db_config($hostname, $path);
619: $host = $dbconfig['host'] === 'localhost.localdomain' ? '127.0.0.1' : $dbconfig['host'];
620:
621: return \MySQL::stub()->connect($host, $dbconfig['user'], $dbconfig['password'], $dbconfig['db']);
622: }
623:
624: /**
625: * Get database configuration for a blog
626: *
627: * @param string $hostname domain or subdomain of wp blog
628: * @param string $path optional path
629: * @return bool|array
630: */
631: public function db_config(string $hostname, string $path = '')
632: {
633: $approot = $this->getAppRoot($hostname, $path);
634: if (!$approot) {
635: error('failed to determine Ghost config - ' . $approot);
636:
637: return [];
638: }
639: foreach (['development', 'production'] as $env) {
640: $path = "${approot}/config.${env}.json";
641: if ($this->file_exists($path)) {
642: // @todo unify config into a consistent object
643: $json = json_decode($this->file_get_file_contents($path), true)['database']['connection'];
644: if (!$json) {
645: continue;
646: }
647: $json['db'] = $json['database'];
648: $json['prefix'] = '';
649:
650: return $json;
651: }
652: }
653:
654: return [];
655: }
656:
657: /**
658: * Install and activate plugin
659: *
660: * @param string $hostname domain or subdomain of wp install
661: * @param string $path optional path component of wp install
662: * @param string $plugin plugin name
663: * @param string $version optional plugin version
664: * @return bool
665: */
666: public function install_plugin(
667: string $hostname,
668: string $path,
669: string $plugin,
670: string $version = 'stable'
671: ): bool {
672: return error('not supported');
673: }
674:
675: /**
676: * Uninstall WP from a location
677: *
678: * @param $hostname
679: * @param string $path
680: * @param string $delete remove all files under docroot
681: * @return bool
682: */
683: public function uninstall(string $hostname, string $path = '', string $delete = 'all'): bool
684: {
685: $this->kill($hostname, $path);
686:
687: return parent::uninstall($hostname, $path, $delete);
688: }
689:
690: /**
691: * Update core, plugins, and themes atomically
692: *
693: * @param string $hostname subdomain or domain
694: * @param string $path optional path under hostname
695: * @param string $version
696: * @return bool
697: */
698: public function update_all(string $hostname, string $path = '', string $version = null): bool
699: {
700: return $this->update($hostname, $path, $version) || error('failed to update all components');
701: }
702:
703: /**
704: * Update Ghost to latest version
705: *
706: * @param string $hostname domain or subdomain under which WP is installed
707: * @param string $path optional subdirectory
708: * @param string $version
709: * @return bool
710: */
711: public function update(string $hostname, string $path = '', string $version = null): bool
712: {
713: $approot = $this->getAppRoot($hostname, $path);
714: if (!$approot) {
715: return error('update failed');
716: }
717:
718: $docroot = $this->getDocumentRoot($hostname, $path);
719: if (!$version) {
720: $version = \Opcenter\Versioning::nextVersion($this->get_versions(),
721: $this->get_version($hostname, $path));
722: } else if (!\Opcenter\Versioning::valid($version)) {
723: return error('invalid version number, %s', $version);
724: }
725:
726: if (!$this->platformVersionCheck($version)) {
727: return error("Ghost %s cannot be installed on this platform", $version);
728: }
729:
730: $this->file_chmod($approot, 705);
731:
732: $oldversion = $this->get_version($hostname, $path);
733: if ($oldversion === $version) {
734: return info("Ghost is already at current version `%s'", $version);
735: }
736: $oldNodeVersion = $this->node_version_from_path($approot);
737:
738: if ($oldNodeVersion !== ($nodeVersion = $this->validateNode($version, $this->getDocrootUser($approot)))) {
739: info("Updating Node %(old)s => %(new)s per dependency requirements of Ghost %(ghostver)s", [
740: 'old' => $oldNodeVersion,
741: 'new' => $nodeVersion,
742: 'ghostver' => $version
743: ]);
744: // @TODO bounce Apache?
745: defer($_, fn() => $this->setInterpreter($this->getDocumentRoot($hostname, $path), $nodeVersion));
746: }
747:
748: if (\Opcenter\Versioning::asMajor($version) !== \Opcenter\Versioning::asMajor($oldversion)) {
749: // newer ghost-cli are sudo-happy
750: if (!$this->_exec($approot, 'ghost update %s --local --no-restart --no-color --v%d',
751: [
752: null,
753: \Opcenter\Versioning::asMajor($oldversion)
754: ])) {
755: return error('Failed to prep for major version upgrade');
756: }
757:
758: return error('Ghost upgrade must be manually completed. Run the following command to use the migration assistant: ' .
759: 'cd %s && NODE_ENV=production nvm exec ghost update --local -f', $approot);
760: }
761: // force version assertion on incomplete upgrade
762: $this->assertLocalVersion($approot, $oldversion, $version);
763: // more bad permission requirements, -D bypasses chmod requirement
764:
765: $cmd = 'ghost update %(debug)s --no-restart --local --no-prompt --no-color %(version)s';
766: // disable debug mode for now, causes stdout maxBuffer exceeded error
767: if (is_debug()) {
768: warn("Disabling debug mode as it causes a maxBuffer exceeded error");
769: }
770:
771: $args['debug'] = null;
772: $args['version'] = $version;
773: $ret = $this->_exec($approot, $cmd, $args);
774: $this->fixSymlink($approot);
775: $this->file_touch("${approot}/tmp/restart.txt");
776: if (!$ret['success']) {
777: $this->setInfo($this->getDocumentRoot($hostname, $path), [
778: 'version' => $this->get_version($hostname, $path),
779: 'failed' => true
780: ]);
781:
782: $this->assertLocalVersion($approot, $oldversion, $version);
783:
784: return error('failed to update Ghost: %s', coalesce($ret['stderr'], $ret['stdout']));
785: }
786:
787: $ret = $this->migrate($approot) && ($this->kill($hostname, $path) || true);
788: $this->setInterpreter($docroot, $nodeVersion);
789: if ($version !== ($newver = $this->get_version($hostname, $path))) {
790: report("Upgrade failed, reported version `%s' is not requested version `%s'", $newver, $version);
791: } else if ($ret) {
792: // unlink previous version
793: $this->file_delete("{$approot}/versions/{$oldversion}", true);
794: // cleanup orphaned packages
795: $this->_exec($approot, 'npm prune');
796: }
797:
798: $this->setInfo($docroot, [
799: 'version' => $version,
800: 'failed' => !$ret
801: ]);
802:
803: return $ret;
804: }
805:
806: /**
807: * Assert local Ghost CLI version matches expected
808: *
809: * @param string $approot
810: * @param string $version
811: * @return bool true if assertion passes, false if change forced
812: */
813: private function assertLocalVersion(string $approot, string $version, string $targetVersion = null): bool
814: {
815: $json = $this->file_get_file_contents($approot . '/.ghost-cli');
816: $meta = json_decode($json, true);
817: if (!is_array($meta)) {
818: return error("Failed decoding meta in `%s': %s", $approot, json_last_error_msg());
819: }
820:
821: if ($targetVersion) {
822: $stat = $this->file_stat($approot . '/versions/' . $targetVersion);
823: if ($stat && $stat['referent']) {
824: $this->file_delete($approot . '/versions/' . $targetVersion);
825: }
826: }
827:
828: if (($myver = array_get($meta, 'active-version')) === $version) {
829: return true;
830: }
831:
832: info("Version in %(approot)s reported as %(oldver)s - forcing version as %(newver)s",
833: ['approot' => $approot, 'oldver' => $myver, 'newver' => $version]);
834: $meta['active-version'] = $version;
835:
836: return $this->file_put_file_contents($approot . '/.ghost-cli', json_encode($meta), true) > 0;
837: }
838:
839: /**
840: * Get all available Ghost versions
841: *
842: * @return array
843: */
844: public function get_versions(): array
845: {
846: $versions = $this->_getVersions();
847: return array_column($versions, 'version');
848: }
849:
850: public function get_installable_versions(): array
851: {
852: return array_filter($this->get_versions(), $this->platformVersionCheck(...));
853: }
854:
855: /**
856: * Ghost version supported by platform
857: *
858: * @param string $version
859: * @return bool
860: */
861: private function platformVersionCheck(string $version): bool
862: {
863: // Ghost v5+ requires MySQL v8
864: return version_compare($version, '5.21', '<') || version_compare($version, '5.24.0', '>=');
865: }
866:
867: /**
868: * Get all current major versions
869: *
870: * @return array
871: */
872: private function _getVersions(): array
873: {
874: $key = 'ghost.versions';
875: $cache = Cache_Super_Global::spawn();
876: if (false !== ($ver = $cache->get($key))) {
877: return (array)$ver;
878: }
879: $versions = array_filter(
880: (new Webapps\VersionFetcher\PackageJson)->fetch('ghost', static function ($item) {
881: return !isset($item['deprecated']) && (
882: version_compare($item['version'], '5.0.0','<') || version_compare($item['version'], '5.24.1', '>=')
883: );
884: }
885: ));
886:
887: $cache->set($key, $versions, 43200);
888:
889: return $versions;
890: }
891:
892: /**
893: * Update plugins
894: *
895: * @param string $hostname domain or subdomain
896: * @param string $path optional path within host
897: * @param array $plugins
898: * @return bool
899: */
900: public function update_plugins(string $hostname, string $path = '', array $plugins = array()): bool
901: {
902: return error('not implemented');
903: }
904:
905: /**
906: * Update Laravel themes
907: *
908: * @param string $hostname subdomain or domain
909: * @param string $path optional path under hostname
910: * @param array $themes
911: * @return bool
912: */
913: public function update_themes(string $hostname, string $path = '', array $themes = array()): bool
914: {
915: return error('not implemented');
916: }
917:
918: /**
919: * @inheritDoc
920: */
921: public function has_fortification(string $hostname, string $path = '', string $mode = null): bool
922: {
923: return false;
924: }
925:
926: /**
927: * Restrict write-access by the app
928: *
929: * @param string $hostname
930: * @param string $path
931: * @param string $mode
932: * @param array $args
933: * @return bool
934: */
935: public function fortify(string $hostname, string $path = '', string $mode = 'max', $args = []): bool
936: {
937: return error('not implemented');
938: }
939:
940: /**
941: * Relax permissions to allow write-access
942: *
943: * @param string $hostname
944: * @param string $path
945: * @return bool
946: * @internal param string $mode
947: */
948: public function unfortify(string $hostname, string $path = ''): bool
949: {
950: return error('not implemented');
951: }
952: }