-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.php
963 lines (847 loc) · 29.6 KB
/
module.php
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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
<?php
declare(strict_types=1);
/**
* +------------------------------------------------------------+
* | apnscp |
* +------------------------------------------------------------+
* | Copyright (c) Apis Networks |
* +------------------------------------------------------------+
* | Licensed under Artistic License 2.0 |
* +------------------------------------------------------------+
* | Author: Matt Saladna ([email protected]) |
* +------------------------------------------------------------+
*/
use Module\Support\Webapps;
use Module\Support\Webapps\Traits\PublicRelocatable;
/**
* Ghost management
*
* A blogging platform built on Node
*
* @package core
*/
class Ghost_Module extends Webapps
{
// via https://ghost.org/faq/node-versions/
const DEFAULT_NODE = '12';
const GHOST_CLI_REPO = 'git+https://github.com/msaladna/ghost-cli-lite.git';
use PublicRelocatable {
getAppRoot as getAppRootReal;
}
const APP_NAME = 'Ghost';
const GHOST_CLI = 'ghost';
const DEFAULT_VERSION_LOCK = 'major';
// via ghost/core/package.json
const NODE_VERSIONS = [
'0' => self::DEFAULT_NODE,
'4.0' => '12.10.0',
'4.5' => '12.22.1',
'4.6' => '14.16.1',
'4.21' => '14.18.0',
'5.0' => '16.19',
'5.30' => '18.12.1',
];
public function plugin_status(string $hostname, string $path = '', string $plugin = null)
{
return error('not supported');
}
public function uninstall_plugin(string $hostname, string $path, string $plugin, bool $force = false): bool
{
return error('not supported');
}
public function disable_all_plugins(string $hostname, string $path = ''): bool
{
return error('not supported');
}
public function restart(string $hostname, string $path = ''): bool
{
if (!$approot = $this->getAppRoot($hostname, $path)) {
return false;
}
return \Module\Support\Webapps\Passenger::instantiateContexted($this->getAuthContext(),
[$approot, 'nodejs'])->restart();
}
/**
* Get app root for Ghost
*
* @param string $hostname
* @param string $path
* @return null|string
*/
protected function getAppRoot(string $hostname, string $path = ''): ?string
{
return $this->getAppRootReal($hostname, $path);
}
/**
* Install Ghost 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('%(what)s must be enabled to install %(app)s',
['what' => 'MySQL', 'app' => static::APP_NAME]);
}
$available = null;
if (!$this->hasMemoryAllowance(768, $available)) {
return error("%(app)s requires at least %(min)d MB memory, `%(found)d' MB provided for account",
['app' => 'Ghost', 'min' => 768, 'found' => $available]);
}
if (!$this->hasStorageAllowance(500, $available)) {
return error("%(app)s requires at least %(min)d MB storage. Only %(found).2f' MB provided for account",
['app' => 'Ghost', 'min' => 500, 'found' => $available]);
}
if (!$this->ssh_enabled()) {
return error('Ghost requires ssh service to be enabled');
}
// assume all Ghost installs will be located in a parent directory
// once installed, relink the domain/subdomain to $docroot + /public
// also block installing under a path, because this would require either relocating
// Ghost outside any document root, e.g. /var/www/<hostname>-<path>-ghost and making
// a symlink, which fails once the parent document root moves (must use relative symlinks)
// and clutters up wherever they get located... no sound solution
if ($path) {
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');
}
if (!$this->parseInstallOptions($opts, $hostname, $path)) {
return false;
}
$docroot = $this->getDocumentRoot($hostname, $path);
if (!$this->platformVersionCheck((string)$opts['version'])) {
return error("Ghost %s cannot be installed on this platform", $opts['version']);
}
$nodeVersion = $this->validateNode((string)$opts['version'], $opts['user'] ?? null);
$wrapper = empty($opts['user']) ? $this : \apnscpFunctionInterceptor::factory(Auth::context($opts['user'],
$this->site));
$wrapper->node_make_default($nodeVersion, $docroot);
$args['version'] = $opts['version'];
$db = Webapps\DatabaseGenerator::mysql($this->getAuthContext(), $hostname);
$db->hostname = '127.0.0.1';
$db->connectionLimit = max($db->connectionLimit, 15);
if (!$db->create()) {
return false;
}
$args['dbhost'] = $db->hostname;
$args['dbkind'] = $db->kind;
$args['dbname'] = $db->database;
$args['dbuser'] = $db->username;
$args['dbpassword'] = $db->password;
$fqdn = $this->web_normalize_hostname($hostname);
$args['uri'] = rtrim($fqdn . '/' . $path, '/');
$args['proto'] = empty($opts['ssl']) ? 'http://' : 'https://';
$args['debug'] = is_debug() ? '-V' : null;
if (is_debug()) {
warn("Disabling debug mode as it causes a maxBuffer exceeded error");
$args['debug'] = null;
}
// use localhost.localdomain, which is an alias to 127.0.0.1;
// ghost looks for "mysqld" if dbhost is localhost or 127.0.0.1;
// this isn't present in a synthetic root
$ret = $this->_exec($docroot,
'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 ' .
'--dbname=%(dbname)s --no-setup-linux-user --no-setup-nginx --url=%(proto)s%(uri)s --mail=sendmail %(version)s',
$args);
if (!$ret['success']) {
info('removing temporary files');
$this->file_delete($docroot, true);
$db->rollback();
return error('failed to download Ghost v%s: %s - possibly out of storage space?', $args['version'],
$ret['stdout']);
}
$wrapper->node_make_default($nodeVersion, $docroot);
if (!isset($opts['password'])) {
$opts['password'] = \Opcenter\Auth\Password::generate(10);
info("autogenerated password `%s'", $opts['password']);
}
$username = $this->user_getpwnam($opts['user'] ?? $this->username)['gecos'] ?: $this->username;
info("setting displayed name to `%s'", $username);
$opts['url'] = rtrim($hostname . '/' . $path, '/');
if (!$this->fixSymlink($docroot)) {
return error("Failed to correct current/ symlink in `%s'", $docroot);
}
$this->fixThemeLink($docroot);
if (null === ($docroot = $this->remapPublic($hostname, $path))) {
// it's more reasonable to fail at this stage, but let's try to complete
return error("Failed to remap Ghost to public/, manually remap from `%s' - Ghost setup is incomplete!",
$docroot);
}
$approot = $this->getAppRoot($hostname, $path);
// @todo migrate cache management to reconfigure method
$config = [
'useMinFiles' => 'true',
'caching.frontend.maxAge' => 120,
'logging.rotation.enabled' => 'true',
'mail.transport' => 'sendmail',
// frontend caches + leave 5 for update/admin
'database.pool.max' => 5,
'paths.contentPath' => "{$approot}/content"
];
foreach ($config as $c => $v) {
$ret = $this->_exec($approot, 'ghost config set %(c)s %(v)s', ['c' => $c, 'v' => $v]);
if (!$ret['success']) {
info('removing temporary files');
$this->file_delete($docroot, true);
$db->rollback();
return error("Failed to set configuration `%s': %s", $c, coalesce($ret['stderr'], $ret['stdout']));
}
}
foreach (['tmp', 'public', 'logs'] as $dir) {
($this->file_create_directory("{$approot}/{$dir}") &&
$this->file_chown("{$approot}/{$dir}", $opts['user'] ?? $this->username)
) || warn("failed to create application directory `%s/%s'", $docroot, $dir);
}
$this->linkConfiguration($approot, 'production');
if (!$wrapper->file_put_file_contents($docroot . '/.htaccess',
'# Enable caching' . "\n" .
'UnsetEnv no-cache' . "\n" .
'PassengerEnabled on' . "\n" .
'PassengerAppEnv production' . "\n" .
'PassengerStartupFile current/index.js' . "\n" .
'PassengerAppType node' . "\n" .
'PassengerAppRoot ' . $approot . "\n"
)) {
return error('failed to create .htaccess control - Ghost is not properly setup');
}
$this->setInterpreter($docroot, $nodeVersion);
$wrapper->node_do($nodeVersion, null, 'npm install -g --production knex-migrator');
$ret = $wrapper->node_do($nodeVersion, "{$approot}/current", 'knex-migrator init', [], ['NODE_ENV' => 'production']);
if (!$ret['success']) {
return error('Failed to create initial database configuration - knex-migrator failed: %s',
$ret['stdout']);
}
if (!$this->migrate($approot)) {
return error('Failed to migrate database configuration - Ghost installation incomplete');
}
$this->change_admin($hostname, $path, [
'email' => $opts['email'],
'password' => $opts['password'],
'name' => $username
]);
$this->notifyInstalled($hostname, $path, $opts);
try {
// throws 503 as it boots up, boot up populates new settings into db...
(new \HTTP\SelfReferential($hostname, $this->site_ip_address()))->get($path);
} catch (\GuzzleHttp\Exception\RequestException) { }
return info('%(app)s installed - confirmation email with login info sent to %(email)s',
['app' => static::APP_NAME, 'email' => $opts['email']]);
}
private function setInterpreter(string $docroot, string $nodeVersion): bool
{
$htaccess = $this->file_get_file_contents("{$docroot}/.htaccess");
$new = preg_replace(
'/\R(?:^PassengerNodejs .*$|$)/m',
"\n". 'PassengerNodejs ' . $this->getNodeCommand($nodeVersion, $this->file_stat($docroot)['owner']),
$htaccess,
1
);
return $this->file_put_file_contents("{$docroot}/.htaccess", $new);
}
/**
* Verify Node LTS is installed
*
* @param string|null $version optional version to compare against
* @param string|null $user
* @return null|string
*/
protected function validateNode(string $version = self::DEFAULT_NODE, string $user = null): ?string
{
if ($user) {
$afi = \apnscpFunctionInterceptor::factory(Auth::context($user, $this->site));
}
$wrapper = $afi ?? $this;
$nodeVersion = \Opcenter\Versioning::satisfy($version, self::NODE_VERSIONS);
foreach ([\Opcenter\Versioning::asMajor($nodeVersion), $nodeVersion] as $testVersion) {
if (($chk = $wrapper->node_installed($testVersion)) && version_compare($chk, $nodeVersion, '>='))
{
$nodeVersion = $chk;
break;
}
}
if (!$wrapper->node_installed($nodeVersion) && !$wrapper->node_install($nodeVersion)) {
error('failed to install Node %s', $nodeVersion);
return null;
}
$wrapper->node_do($nodeVersion, null, 'nvm use --delete-prefix');
$ret = $wrapper->node_do($nodeVersion, null, 'npm install -g ' . self::GHOST_CLI_REPO);
if (!$ret['success']) {
error('failed to install ghost-cli: %s', $ret['stderr'] ?? 'UNKNOWN ERROR');
return null;
}
$home = $this->user_get_home($user);
$stat = $this->file_stat($home);
if (!$stat || !$this->file_chmod($home, decoct($stat['permissions']) | 0001)) {
error("failed to query user home directory `%s' for user `%s'", $home, $user);
return null;
}
return $nodeVersion;
}
private function _exec(?string $path, $cmd, array $args = array(), $env = array())
{
// client may override tz, propagate to bin
if (!is_array($args)) {
$args = func_get_args();
array_shift($args);
}
$wrapper = $this->getApnscpFunctionInterceptorFromDocroot($path ?? '~');
$ret = $wrapper->node_do(
null,
$path,
$cmd,
$args,
$env + [
'NODE_ENV' => 'production'
]);
if (!strncmp(coalesce($ret['stderr'], $ret['stdout']), 'Error:', strlen('Error:'))) {
// move stdout to stderr on error for consistency
$ret['success'] = false;
if (!$ret['stderr']) {
$ret['stderr'] = $ret['stdout'];
}
}
return $ret;
}
/**
* Get installed version
*
* @param string $hostname or $docroot
* @param string $path
* @return string version number
*/
public function get_version(string $hostname, string $path = ''): ?string
{
if (!$this->valid($hostname, $path)) {
return null;
}
if ($hostname[0] !== '/') {
$approot = $this->getAppRoot($hostname, $path);
} else {
$approot = Webapps\App\Loader::fromDocroot('ghost', $hostname, $this->getAuthContext())->getAppRoot();
}
$path = $this->domain_fs_path($approot . '/current/package.json');
clearstatcache(true, \dirname($path));
clearstatcache(true, $path);
if (!file_exists($path)) {
warn('missing package.json from Ghost root - cannot detect version');
return null;
}
return json_decode(file_get_contents($path))->version;
}
/**
* Location is a valid Ghost install
*
* @param string $hostname or $docroot
* @param string $path
* @return bool
*/
public function valid(string $hostname, string $path = ''): bool
{
if (!IS_CLI) {
return $this->query('ghost_valid', $hostname, $path);
}
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);
}
if (is_link($approot . '/current') && readlink($approot . '/current')[0] === '/') {
$this->fixSymlink($this->file_unmake_path($approot));
}
$tests = [
'core/server/ghost-server.js',
'core/server/GhostServer.js',
'core/core/server/GhostServer.js'
];
foreach ($tests as $test) {
if (file_exists("{$approot}/current/{$test}")) {
return true;
}
}
return false;
}
/**
* Relink current/ from absolute to relative symlink
*
* @param string $approot
* @return bool
*/
private function fixSymlink(string $approot): bool
{
$path = $this->domain_fs_path("{$approot}/current");
clearstatcache(true, $path);
if (!is_link($path)) {
return error("{$approot}/current missing - can't relink");
}
$link = readlink($path);
if ($link[0] !== '/') {
// relative link
$stat = $this->file_stat("{$approot}/current");
return !empty($stat['referent']) ? true : error("{$approot}/current does not point to an active Ghost install");
}
if (0 !== strpos($link, $approot)) {
return false;
}
// debugging code...
if (!$this->file_delete($approot . '/current') || !$this->file_symlink($link, $approot . '/current')) {
return false;
}
return $this->file_chown_symlink($approot . '/current', $this->file_stat($approot)['owner']);
}
/**
* Correct theme link when Ghost is installed in primary docroot
*
* @param string $approot
* @return bool
*/
private function fixThemeLink(string $approot): bool
{
$path = $this->domain_fs_path("{$approot}/content/themes");
if (!file_exists($path)) {
return warn('Cannot correct theme symlinks, cannot find theme path');
}
$dh = opendir($path);
while (false !== ($file = readdir($dh))) {
if ($file === '.' || $file === '..') {
continue;
}
if (!is_link("{$path}/{$file}")) {
continue;
}
$link = readlink("{$path}/{$file}");
if (0 !== strpos($link . '/', Web_Module::MAIN_DOC_ROOT . '/')) {
continue;
}
$localpath = $this->file_unmake_path("{$path}/{$file}");
$this->file_delete($localpath) && $this->file_symlink($approot . substr($link,
strlen(Web_Module::MAIN_DOC_ROOT)),
$localpath);
}
closedir($dh);
return true;
}
/**
* Get path to active Node
*
* @param string|null $version
* @param string|null $user
* @return null|string
*/
protected function getNodeCommand(string $version = 'lts', string $user = null): ?string
{
if ($user) {
$afi = \apnscpFunctionInterceptor::factory(Auth::context($user, $this->site));
}
$ret = ($afi ?? $this)->node_do($version, null, 'which node');
return $ret['success'] ? trim($ret['output']) : null;
}
/**
* Migrate database configuration to current/
*
* @param string $approot
* @param string $appenv
* @return bool
*/
private function linkConfiguration(string $approot, string $appenv = 'production'): bool
{
$this->file_delete($approot . "/current/config.{$appenv}.json");
return $this->file_symlink($approot . "/config.{$appenv}.json",
$approot . "/current/config.{$appenv}.json") ||
warn("failed to link configuration {$approot}/config.{$appenv}.json to current/");
}
/**
* Migrate Ghost database
*
* @param string $approot
* @param string $appenv optional app environment to source DB config
* @return bool
*/
private function migrate(string $approot, string $appenv = 'production'): bool
{
$this->linkConfiguration($approot, $appenv);
$this->_exec("$approot/current", 'knex-migrator -v || npm install --no-optional knex-migrator');
$ret = $this->_exec("$approot/current", 'knex-migrator migrate');
return $ret['success'] ?: error("failed to migrate database in `%s': %s", $approot,
coalesce($ret['stdout'], $ret['stderr']));
}
/**
* Change Ghost admin credentials
*
* Common fields include: password, email, name; email doubles as login
*
* @param string $hostname
* @param string $path
* @param array $fields
* @return bool
*/
public function change_admin(string $hostname, string $path, array $fields): bool
{
$docroot = $this->getAppRoot($hostname, $path);
if (!$docroot) {
return warn('failed to change administrator information');
}
$admin = $this->get_admin($hostname, $path);
if (!$admin) {
return error('cannot determine admin of Ghost install');
}
if (isset($fields['password'])) {
if (!\Opcenter\Auth\Password::strong($fields['password'])) {
return false;
}
$fields['password'] = password_hash($fields['password'], PASSWORD_BCRYPT, ['cost' => 10]);
}
if (isset($fields['name'])) {
$fields['slug'] = str_slug($fields['name']);
}
$db = $this->connectDB($hostname, $path);
$q = "UPDATE users SET status = 'active'";
foreach (['password', 'email', 'name', 'slug'] as $field) {
if (!isset($fields[$field])) {
continue;
}
$q .= ", {$field} = '" . $db->escape_string($fields[$field]) . "'";
}
$q .= " WHERE email = '" . $admin . "'";
if (false === $db->query($q) || $db->affected_rows() < 1) {
return error("Failed to change admin user `%s'", $admin);
}
if (isset($fields['email'])) {
info('user login changed to %s', $fields['email']);
}
if (isset($fields['password'])) {
info("user `%s' password changed", $fields['email'] ?? $admin);
}
return true;
}
/**
* Get the primary admin for a WP instance
*
* @param string $hostname
* @param null|string $path
* @return string admin or false on failure
*/
public function get_admin(string $hostname, string $path = ''): ?string
{
$mysql = $this->connectDB($hostname, $path);
$rs = $mysql->query('SELECT email FROM users WHERE id = 1');
if (!$rs || $rs->num_rows < 1) {
return null;
}
return $rs->fetch_object()->email;
}
private function connectDB($hostname, $path): \MySQL
{
$dbconfig = $this->db_config($hostname, $path);
$host = $dbconfig['host'] === 'localhost.localdomain' ? '127.0.0.1' : $dbconfig['host'];
return \MySQL::stub()->connect($host, $dbconfig['user'], $dbconfig['password'], $dbconfig['db']);
}
/**
* Get database configuration for a blog
*
* @param string $hostname domain or subdomain of wp blog
* @param string $path optional path
* @return bool|array
*/
public function db_config(string $hostname, string $path = '')
{
$approot = $this->getAppRoot($hostname, $path);
if (!$approot) {
error('failed to determine Ghost config - ' . $approot);
return [];
}
foreach (['development', 'production'] as $env) {
$path = "{$approot}/config.{$env}.json";
if ($this->file_exists($path)) {
// @todo unify config into a consistent object
$json = json_decode($this->file_get_file_contents($path), true)['database']['connection'];
if (!$json) {
continue;
}
$json['db'] = $json['database'];
$json['prefix'] = '';
return $json;
}
}
return [];
}
/**
* Install and activate plugin
*
* @param string $hostname domain or subdomain of wp install
* @param string $path optional path component of wp install
* @param string $plugin plugin name
* @param string $version optional plugin version
* @return bool
*/
public function install_plugin(
string $hostname,
string $path,
string $plugin,
string $version = 'stable'
): bool {
return error('not supported');
}
/**
* Uninstall WP 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
{
$this->kill($hostname, $path);
return parent::uninstall($hostname, $path, $delete);
}
/**
* Update core, plugins, and themes atomically
*
* @param string $hostname subdomain or domain
* @param string $path optional path under hostname
* @param string $version
* @return bool
*/
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 Ghost to latest version
*
* @param string $hostname domain or subdomain under which WP is installed
* @param string $path optional subdirectory
* @param string $version
* @return bool
*/
public function update(string $hostname, string $path = '', string $version = null): bool
{
$approot = $this->getAppRoot($hostname, $path);
if (!$approot) {
return error('update failed');
}
$docroot = $this->getDocumentRoot($hostname, $path);
if (!$version) {
$version = \Opcenter\Versioning::nextVersion($this->get_versions(),
$this->get_version($hostname, $path));
} else if (!\Opcenter\Versioning::valid($version)) {
return error('invalid version number, %s', $version);
}
if (!$this->platformVersionCheck($version)) {
return error("Ghost %s cannot be installed on this platform", $version);
}
$this->file_chmod($approot, 705);
$oldversion = $this->get_version($hostname, $path);
if ($oldversion === $version) {
return info("Ghost is already at current version `%s'", $version);
}
$oldNodeVersion = $this->node_version_from_path($approot);
if ($oldNodeVersion !== ($nodeVersion = $this->validateNode($version, $this->getDocrootUser($approot)))) {
info("Updating Node %(old)s => %(new)s per dependency requirements of Ghost %(ghostver)s", [
'old' => $oldNodeVersion,
'new' => $nodeVersion,
'ghostver' => $version
]);
$wrapper = $this->getApnscpFunctionInterceptorFromDocroot($docroot);
$wrapper->node_make_default($nodeVersion, $approot);
// @TODO bounce Apache?
defer($_, fn() => $this->setInterpreter($this->getDocumentRoot($hostname, $path), $nodeVersion));
}
if (\Opcenter\Versioning::asMajor($version) !== \Opcenter\Versioning::asMajor($oldversion))
{
// newer ghost-cli are sudo-happy
$ret = $this->_exec($approot, 'ghost update %s --local --no-restart --no-color v%d', [
null,
(int)\Opcenter\Versioning::asMajor($oldversion)
]);
if (!$ret['success']) {
return error('Ghost upgrade must be manually completed. Run the following command to use the migration assistant: ' .
'cd %s && NODE_ENV=production nvm exec ghost update --local -f', $approot);
}
} else {
// force version assertion on incomplete upgrade
$this->assertLocalVersion($approot, $oldversion, $version);
}
// more bad permission requirements, -D bypasses chmod requirement
$cmd = 'ghost update %(debug)s --no-restart --local --no-prompt --no-color %(version)s';
// disable debug mode for now, causes stdout maxBuffer exceeded error
if (is_debug()) {
warn("Disabling debug mode as it causes a maxBuffer exceeded error");
}
$args['debug'] = null;
$args['version'] = $version;
$ret = $this->_exec($approot, $cmd, $args);
$this->fixSymlink($approot);
$this->file_touch("{$approot}/tmp/restart.txt");
if (!$ret['success']) {
$this->setInfo($this->getDocumentRoot($hostname, $path), [
'version' => $this->get_version($hostname, $path),
'failed' => true
]);
$this->assertLocalVersion($approot, $oldversion, $version);
$output = coalesce($ret['stderr'], $ret['stdout']);
if (str_contains($output, 'has been deprecated with ')) {
return warn("Release %(version)s is deprecated pending upstream acknowledgement. " .
"Update has not been applied and will be skipped.", ['version' => $version]);
}
return error('failed to update Ghost: %s', $output);
}
$ret = $this->migrate($approot) && ($this->kill($hostname, $path) || true);
$this->setInterpreter($docroot, $nodeVersion);
if (!\Opcenter\Versioning::compare($version, $newver = $this->get_version($hostname, $path))) {
report("Upgrade failed, reported version `%s' is not requested version `%s'", $newver, $version);
} else if ($ret) {
// unlink previous version
$this->file_delete("{$approot}/versions/{$oldversion}", true);
// cleanup orphaned packages
$this->_exec($approot, 'npm prune');
}
$this->setInfo($docroot, [
'version' => $newver,
'failed' => !$ret
]);
return $ret;
}
/**
* Assert local Ghost CLI version matches expected
*
* @param string $approot
* @param string $version
* @return bool true if assertion passes, false if change forced
*/
private function assertLocalVersion(string $approot, string $version, string $targetVersion = null): bool
{
$json = $this->file_get_file_contents($approot . '/.ghost-cli');
$meta = json_decode($json, true);
if (!is_array($meta)) {
return error("Failed decoding meta in `%s': %s", $approot, json_last_error_msg());
}
if ($targetVersion) {
$stat = $this->file_stat($approot . '/versions/' . $targetVersion);
if ($stat && $stat['referent']) {
$this->file_delete($approot . '/versions/' . $targetVersion);
}
}
if (($myver = array_get($meta, 'active-version')) === $version) {
return true;
}
info("Version in %(approot)s reported as %(oldver)s - forcing version as %(newver)s",
['approot' => $approot, 'oldver' => $myver, 'newver' => $version]);
$meta['active-version'] = $version;
return $this->file_put_file_contents($approot . '/.ghost-cli', json_encode($meta), true) > 0;
}
/**
* Get all available Ghost versions
*
* @return array
*/
public function get_versions(): array
{
$versions = $this->_getVersions();
return array_column($versions, 'version');
}
public function get_installable_versions(): array
{
return array_filter($this->get_versions(), $this->platformVersionCheck(...));
}
/**
* Ghost version supported by platform
*
* @param string $version
* @return bool
*/
private function platformVersionCheck(string $version): bool
{
// Ghost v5+ requires MySQL v8
return version_compare($version, '5.21', '<') || version_compare($version, '5.24.0', '>=');
}
/**
* Get all current major versions
*
* @return array
*/
private function _getVersions(): array
{
$key = 'ghost.versions';
$cache = Cache_Super_Global::spawn();
if (false !== ($ver = $cache->get($key))) {
return (array)$ver;
}
$versions = array_filter(
(new Webapps\VersionFetcher\PackageJson)->fetch('ghost', static function ($item) {
if (isset($item['deprecated'])) {
return false;
}
return version_compare($item['version'], '5.0.0','<') || version_compare($item['version'], '5.24.1', '>=')
? $item : false;
}
));
$cache->set($key, $versions, 43200);
return $versions;
}
/**
* Update 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 error('not implemented');
}
/**
* 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 error('not implemented');
}
/**
* @inheritDoc
*/
public function has_fortification(string $hostname, string $path = '', string $mode = null): bool
{
return false;
}
/**
* Restrict write-access by the app
*
* @param string $hostname
* @param string $path
* @param string $mode
* @param array $args
* @return bool
*/
public function fortify(string $hostname, string $path = '', string $mode = 'max', $args = []): bool
{
return error('not implemented');
}
/**
* 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 error('not implemented');
}
}