-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodule.php
524 lines (447 loc) · 16.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
<?php
/**
* +------------------------------------------------------------+
* | apnscp |
* +------------------------------------------------------------+
* | Copyright (c) Apis Networks |
* +------------------------------------------------------------+
* | Licensed under Artistic License 2.0 |
* +------------------------------------------------------------+
* | Author: Matt Saladna (msaladna@apisnetworks.com) |
* +------------------------------------------------------------+
*/
use Module\Support\Webapps as WebappsAlias;
use Module\Support\Webapps\App\Loader;
use Module\Support\Webapps\App\Type\Vanilla\ConstantFetch;
use Module\Support\Webapps\App\Type\Vanilla\Handler;
use Module\Support\Webapps\App\Type\Vanilla\Walker;
use Module\Support\Webapps\Composer;
use Module\Support\Webapps\DatabaseGenerator;
use Module\Support\Webapps\VersionFetcher\Github;
use Opcenter\Auth\Password;
use Opcenter\Auth\Shadow;
use Opcenter\Versioning;
/**
* Vanilla management
*
* @package core
*/
class Vanilla_Module extends Composer
{
// remain on 20xx versions
const DEFAULT_VERSION_LOCK = 'major';
const APP_NAME = Handler::NAME;
const VALIDITY_FILE = 'library/Vanilla/';
protected $aclList = [
'min' => [
'cache',
'conf',
'dist',
'uploads'
],
'max' => [
'cache',
'uploads'
]
];
/**
* Install Vanilla into a pre-existing location
*
* @param string $hostname domain or subdomain to install Vanilla
* @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]);
}
if (!version_compare($this->php_version(), '7', '>=')) {
return error('%s requires PHP7', Handler::NAME);
}
if (!$this->parseInstallOptions($opts, $hostname, $path)) {
return false;
}
$docroot = $approot = $this->getDocumentRoot($hostname, $path);
if (!$this->downloadVersion($approot, $opts['version'])) {
return error("Failed to download %(app)s", ['app' => Handler::NAME]);
}
$oldex = \Error_Reporter::exception_upgrade();
try {
$svc = \Opcenter\SiteConfiguration::shallow($this->getAuthContext());
$htaccess = (string)(new \Opcenter\Provisioning\ConfigurationWriter('@webapp(vanilla)::templates.htaccess',
$svc))->compile([
'afi' => $this->getApnscpFunctionInterceptor(),
'hostname' => $hostname,
'docroot' => $docroot
]);
$this->getApnscpFunctionInterceptorFromDocroot($approot)->file_put_file_contents("{$approot}/.htaccess", (string)$htaccess);
$db = DatabaseGenerator::mysql($this->getAuthContext(), $hostname);
if (!$db->create()) {
return false;
}
$this->fortify($hostname, $path, 'min');
$this->file_put_file_contents("{$approot}/version.json", json_encode([
'x-version-scheme' => '{Release version}-{? SNAPSHOT if it\'s a dev build}',
'version' => (string)$opts['version']
]));
$http = \HTTP\SelfReferential::instantiateContexted($this->getAuthContext(), [
$hostname,
$this->site_ip_address()
]);
info("setting admin user to `%s'", $opts['user']);
if (!isset($opts['password'])) {
$opts['password'] = Password::generate();
info("autogenerated password `%s'", $opts['password']);
}
try {
$http->post("{$path}/dashboard/setup.json", [
'Database-dot-Host' => $db->hostname,
'Database-dot-Name' => $db->database,
'Database-dot-User' => $db->username,
'Database-dot-Password' => $db->password,
'Garden-dot-Title' => $opts['title'] ?? 'Vanilla Forums',
'Email' => $opts['email'],
'Name' => $opts['user'],
'Password' => $opts['password'],
'PasswordMatch' => $opts['password']
]);
// give HTTP request time to finalize destructor
unset($http);
do {
usleep(250000);
$i = ($i ?? 0) + 1;
} while (!$this->file_exists("{$approot}/conf/config.php") && $i <= 40);
} catch (\GuzzleHttp\Exception\ClientException $e) {
$response = json_decode($e->getResponse()->getBody()->getContents(), true);
error("Self-request failed (status: %(status)d): %(err)s", [
'status' => $e->getResponse()->getStatusCode(),
'err' => $response['Exception']
]);
}
$this->fixRewriteBase($docroot);
$fqdn = $this->web_normalize_hostname($hostname);
$opts['uri'] = rtrim($fqdn . '/' . $path, '/');
$opts['proto'] = empty($opts['ssl']) ? 'http://' : 'https://';
} catch (\apnscpException $e) {
$this->file_delete($approot, true);
if (isset($db)) {
$db->rollback();
}
return error('Failed to install %(app)s: %(err)s', ['app' => Handler::NAME, 'err' => $e->getMessage()]);
} finally {
\Error_Reporter::exception_upgrade($oldex);
}
// permit pool read, inhibit Apache read
if ($this->php_jailed()) {
$this->file_chmod("{$approot}/version.json", 640);
}
$this->notifyInstalled($hostname, $path, $opts);
return info('%(app)s installed - confirmation email with login info sent to %(email)s',
['app' => static::APP_NAME, 'email' => $opts['email']]);
}
private function versionMeta(string $version): ?array
{
return array_first($this->_getVersions(), static function ($meta) use ($version) {
return strtok($meta['version'], ' ') === $version;
});
}
private function downloadVersion(string $approot, string $version): bool
{
if (null === ($meta = $this->versionMeta($version))) {
return error(":webapp_missing_download", "Cannot locate %(app)s version %(version)s", [
'app' => self::APP_NAME,
'version' => $version
]);
}
$dlUrl = array_first($meta['assets'], static function ($asset) {
return substr($asset['name'], -4) === '.zip';
});
$dlUrl = $dlUrl['browser_download_url'] ?? null;
if (null === $dlUrl) {
return error("@todo");
}
return $this->download($dlUrl, "{$approot}/") &&
$this->file_copy("{$approot}/package/", $approot, true) &&
$this->file_delete("{$approot}/package", true);
}
protected function checkVersion(array &$options): bool
{
if (!isset($options['version'])) {
$versions = $this->get_versions();
$options['version'] = array_pop($versions);
}
$phpversion = $this->php_pool_get_version();
$cap = null;
if (Opcenter\Versioning::compare($phpversion, '7.4.0', '<')) {
$cap = '2021.003';
}
if ($cap && version_compare($options['version'], $cap, '>=')) {
info("PHP version `%(version)s' detected, capping %(app)s to %(capver)s", [
'version' => $phpversion, 'app' => $this->getAppName(), 'capver' => $cap]
);
$options['version'] = $cap;
}
return true;
}
/**
* Get installed version
*
* @param string $hostname
* @param string $path
* @return string version number
*/
public function get_version(string $hostname, string $path = ''): ?string
{
if (!$this->valid($hostname, $path)) {
return null;
}
$approot = $this->getAppRoot($hostname, $path);
$parser = ConstantFetch::instantiateContexted($this->getAuthContextFromDocroot($approot), [
"{$approot}/environment.php"
]);
if ('$version' !== ($version = $parser->get('APPLICATION_VERSION'))) {
return $version;
}
if ($this->file_exists($path = "{$approot}/version.json")) {
if (null !== ($version = json_decode($this->file_get_file_contents($path))?->version)) {
return $version;
}
}
if (!$this->file_exists("{$approot}/cache/version.php")) {
return null;
}
$ast = Walker::instantiateContexted($this->getAuthContextFromDocroot($approot), ["{$approot}/cache/version.php"]);
$version = $ast->first(static function (PhpParser\Node $node) {
return $node instanceof \PhpParser\Node\Stmt\Return_;
});
return $version?->expr->value;
}
/**
* Get Vanilla framework versions
*
* @return array
*/
public function get_versions(): array
{
return array_column($this->_getVersions(), 'version');
}
protected function _getVersions(string $name = null): array
{
$key = 'vanilla.versions';
$cache = Cache_Super_Global::spawn();
if (false !== ($ver = $cache->get($key))) {
return (array)$ver;
}
$versions = (new Github)->setMode('releases')->fetch('apisnetworks/vanilla-rebuilds');
$cache->set($key, $versions, 43200);
return $versions;
}
/**
* Get database configuration for a blog
*
* @param string $hostname domain or subdomain of wp blog
* @param string $path optional path
* @return array|bool
*/
public function db_config(string $hostname, string $path = '')
{
$this->web_purge();
$approot = $this->getAppRoot($hostname, $path);
if (!$approot) {
return error('failed to determine Vanilla');
}
try {
$walker = Walker::instantiateContexted(
$this->getAuthContextFromDocroot($approot),
["{$approot}/conf/config.php"]
);
} catch (\ArgumentError $e) {
return false;
}
return array_combine(['host','prefix','user','password','db','type'], [
$walker->get('Database.Host'),
(string)($walker->get('Database.DatabasePrefix') ?? 'GDN_'),
$walker->get('Database.User'),
$walker->get('Database.Password'),
$walker->get('Database.Name'),
'mysql'
]);
}
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 Vanilla to latest version
*
* @param string $hostname domain or subdomain under which WP is installed
* @param string $path optional subdirectory
* @param string $version version to upgrade
* @return bool
*/
public function update(string $hostname, string $path = '', string $version = null): bool
{
$docroot = $this->getDocumentRoot($hostname, $path);
$approot = $this->getAppRoot($hostname, $path);
parent::setInfo($docroot, [
'failed' => true
]);
if (!$approot) {
return error('update failed');
}
$oldVersion = $this->get_version($hostname, $path);
if (!$version) {
$version = Versioning::nextVersion($this->get_versions(),
$oldVersion);
} else if (!Versioning::valid($version)) {
return error('invalid version number, %s', $version);
}
$app = Loader::fromHostname(null, $hostname, $path, $this->getAuthContext());
$oldFortificationMode = $app->getOption('fortify', $app::DEFAULT_FORTIFICATION);
if (version_compare($oldVersion, '2021.024', '<')) {
return error("Version %(version)s too old to support automatic upgrades", ['version' => $oldVersion]);
}
$this->reconfigure($hostname, $path, ['maintenance' => true]);
$cleanup = new Deferred;
$walker = Walker::instantiateContexted($this->getAuthContextFromDocroot($approot),
["{$approot}/conf/config.php"]);
$token = $walker->get('Garden.UpdateToken');
if (null === $token) {
$this->reconfigure($hostname, $path, ['maintenance' => false]);
return error("Update token not found in %(path)s", ['path' => "{$approot}/conf/config.php"]);
}
// reference: https://success.vanillaforums.com/kb/articles/158-upgrading-self-hosted-vanilla
$this->file_delete("{$approot}/dist", true);
if (!$this->downloadVersion($approot, $version)) {
$this->reconfigure($hostname, $path, ['maintenance' => false]);
return error("Failed to download %(version)s", ['version' => $version]);
}
if ($oldFortificationMode !== 'min') {
$this->fortify($hostname, $path, 'min');
defer($cleanup, fn() => $this->fortify($hostname, $path, $oldFortificationMode));
}
$this->file_delete("{$approot}/cache/*", true);
if (is_debug()) {
$wasDebug = (bool)$walker->get('Debug');
$walker->set('Debug', true)->save();
// messy with maintenance reconfiguration also depending upon file
defer($cleanup, fn() => $wasDebug || $this->reconfigure($hostname, $path, ['debug' => $wasDebug]));
}
if (!$walker->get('Feature.updateTokens.Enabled')) {
$walker->set('Feature.updateTokens.Enabled', true)->save();
}
$this->file_put_file_contents("{$approot}/version.json", json_encode([
'x-version-scheme' => '{Release version}-{? SNAPSHOT if it\'s a dev build}',
'version' => (string)$version
]));
// permit pool read, inhibit Apache read
if ($this->php_jailed()) {
$this->file_chmod("{$approot}/version.json", 640);
}
$http = \HTTP\SelfReferential::instantiateContexted($this->getAuthContext(), [
$hostname,
$this->site_ip_address()
]);
$library = $this->file_get_file_contents($dsPath = "{$approot}/library/database/class.databasestructure.php");
// unsupported in MariaDB
$this->file_put_file_contents(
$dsPath,
preg_replace('!\bALGORITHM = INPLACE LOCK = NONE\b!m', '', $library)
);
try {
$http->post("{$path}/utility/update.json", ['updateToken' => $token], [
'Authorization' => "Bearer {$token}"
]);
// rebuild /dist contents
preempt($cleanup, fn() => $http->get('/'));
} catch (\GuzzleHttp\Exception\ClientException $e) {
$response = json_decode($e->getResponse()->getBody()->getContents(), true);
return error("Self-request failed: %s", $response['Exception']);
} catch (\GuzzleHttp\Exception\ServerException $e) {
debug("Falling back to GET: %s", $e->getResponse()->getBody()->getContents());
$http->get("{$path}/utility/update.json", [
'Authorization' => "Bearer {$token}"
]);
} finally {
unset($http);
preempt($cleanup, fn() => $this->reconfigure($hostname, $path, ['maintenance' => false]));
}
$this->file_delete("{$approot}/cache/*", true);
if ($version && $oldVersion === $version) {
return error("Failed to update %(app)s from `%(old)s' to `%(new)s'",
['app' => $this->getAppName(), 'old' => $oldVersion, 'new' => $version]
);
}
parent::setInfo($docroot, [
'version' => $version,
'failed' => false
]);
return true;
}
public function get_admin(string $hostname, string $path = ''): ?string
{
$db = $this->db_config($hostname, $path);
$mysql = WebappsAlias::connectorFromCredentials($db);
$query = "SELECT Name FROM {$db['prefix']}User WHERE Admin = 1 ORDER BY UserID DESC LIMIT 1";
$rs = $mysql->query($query);
return $rs->rowCount() === 1 ? $rs->fetchObject()->Name : null;
}
/**
* @param string $hostname
* @param string $path
* @param array $fields available option: password, user, email
* @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 install');
}
if (isset($fields['password'])) {
if (!Shadow::crypted($fields['password'])) {
if (!Password::strong($fields['password'])) {
return error("Password is insufficient strength");
}
$fields['password'] = password_hash($fields['password'], CRYPT_BLOWFISH);
} else if (!Shadow::valid_crypted($fields['password'])) {
// error generated from fn
return false;
}
}
if (isset($fields['email']) && !preg_match(Regex::EMAIL, $fields['email'])) {
return error("Invalid email");
}
if (isset($fields['user']) && !preg_match(Regex::USERNAME, $fields['user'])) {
return error("Invalid user");
}
$valid = [
'user' => 'Name',
'email' => 'Email',
'password' => 'Password'
];
if ($unrecognized = array_diff_key($fields, $valid)) {
return error("Unrecognized fields: %s", implode(array_keys($unrecognized)));
}
$match = array_intersect_key($valid, $fields);
$fields = array_combine(array_values($match), array_intersect_key($fields, $match));
if (!$fields) {
return warn("No fields updated");
}
$db = $this->db_config($hostname, $path);
$admin = $this->get_admin($hostname, $path);
$mysql = WebappsAlias::connectorFromCredentials($db);
$query = "UPDATE {$db['prefix']}User SET " .
implode(', ', array_key_map(static fn($k, $v) => $k . ' = ' . $mysql->quote($v), $fields)) . " WHERE Name = " . $mysql->quote($admin);
$rs = $mysql->query($query);
return $rs->rowCount() > 0 ? true : error("Failed to update admin `%(admin)s', error: %(err)s",
['admin' => $admin, 'err' => $rs->errorInfo()]);
}
}