-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodule.php
420 lines (370 loc) · 11.8 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
<?php
use LithiumHosting\WebApps\OpenCart\Handler;
use Module\Support\Webapps;
use Module\Support\Webapps\App\Type\Wordpress\DefineReplace;
use Module\Support\Webapps\DatabaseGenerator;
use Module\Support\Webapps\PhpWrapper;
use Module\Support\Webapps\Traits\PublicRelocatable;
use Module\Support\Webapps\VersionFetcher\Github;
use Opcenter\Auth\Password;
use Opcenter\Versioning;
/**
* Web application management
*
* @package core
*/
class OpenCart_Module extends Webapps
{
use PublicRelocatable {
getAppRoot as getAppRootReal;
}
const APP_NAME = Handler::NAME;
const DEFAULT_VERSION_LOCK = 'minor';
protected $aclList = [
'min' => [
'public/config.php',
'public/admin/config.php',
'public/image/',
'public/image/cache/',
'public/image/catalog/',
'storage/cache/',
'storage/logs/',
'storage/download/',
'storage/upload/',
'storage/modification/',
],
'max' => [
'public/image/',
'public/image/cache/',
'public/image/catalog/',
'storage/cache/',
'storage/logs/',
'storage/download/',
'storage/upload/',
'storage/modification/',
],
];
protected const CLEANUP_FILES = [
'.github',
'.editorconfig',
'CHANGELOG.md',
'INSTALL.md',
'LICENSE.md',
'README.md',
'UPGRADE.md'
];
/**
* Install application
*
* @param string $hostname domain or subdomain to install application
* @param string $path optional path under hostname
* @param array $opts additional install options
*
* @return bool
*/
public function install(string $hostname, string $path = '', array $opts = []): bool {
if (! version_compare($this->php_version(), '8', '>=')) {
return error('OpenCart requires PHP8 or higher.');
}
if (! $this->parseInstallOptions($opts, $hostname, $path)) {
return false;
}
if (! ($docroot = $this->getDocumentRoot($hostname, $path))) {
return error("failed to normalize path for `%s'", $hostname);
}
$args['version'] = $opts['version'];
if (null === ($docroot = $this->remapPublic($hostname, $path))) {
$this->file_delete($this->getDocumentRoot($hostname, $path), true);
return error("Failed to remap OpenCart to public/, manually remap from `%s' - OpenCart setup is incomplete!",
$docroot);
}
$oldex = Error_Reporter::exception_upgrade(Error_Reporter::E_ERROR);
$approot = $this->getAppRoot($hostname, $path);
try {
$this->downloadPackage($approot, $args['version']);
$this->file_move("$docroot/.htaccess.txt", "$docroot/.htaccess");
$db = DatabaseGenerator::mysql($this->getAuthContext(), $hostname);
$db->connectionLimit = max($db->connectionLimit, 15);
if (! $db->create()) {
return false;
}
if (! isset($opts['adminuser'])) {
$opts['adminuser'] = 'storeadmin';
info("autogenerated admin username `%s'", $opts['adminuser']);
}
$opts['adminpassword'] = Password::generate();
info("autogenerated password `%s'", $opts['adminpassword']);
$opts['email'] ?? $this->common_get_email();
$installArgs = [
'adminuser' => $opts['adminuser'],
'email' => $opts['email'],
'passwd' => $opts['adminpassword'],
'server' => $opts['ssl'] ? "https://$hostname/" : "http://$hostname/",
'dbserver' => $db->hostname,
'dbuser' => $db->username,
'dbpass' => $db->password,
'dbname' => $db->database,
];
$installCommand = 'cli_install.php install '.
'--username %(adminuser)s '.
'--email %(email)s '.
'--password %(passwd)s '.
'--http_server %(server)s '.
'--db_driver mysqli '.
'--db_hostname %(dbserver)s '.
'--db_username %(dbuser)s '.
'--db_password %(dbpass)s '.
'--db_database %(dbname)s '.
'--db_prefix ""';
$ret = PhpWrapper::instantiateContexted($this->getAuthContextFromDocroot($approot))->exec("$docroot/install", $installCommand, $installArgs);
if (! $ret['success']) {
return error("failed to install %(app)s: %(err)s", [
'app' => static::APP_NAME,
'approot' => $approot,
'err' => $ret['stderr']
]);
}
info('Deleting install folder');
$this->file_delete("$docroot/install", true);
info('Relocating storage directory and updating configs.');
$this->relocateStorage($docroot, $approot);
} catch (apnscpException $e) {
$this->remapPublic($hostname, $path, '');
$this->file_delete($approot, true);
if (isset($db)) {
$db->rollback();
}
return error('Failed to install %s: %s', static::APP_NAME, $e->getMessage());
} finally {
Error_Reporter::exception_upgrade($oldex);
}
$this->initializeMeta($docroot, $opts);
$this->fortify($hostname, $path, Handler::DEFAULT_FORTIFICATION);
$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']]);
}
/**
* Get all available versions sorted in ascending semantic version
*
* @return array
*/
public function get_versions(): array {
$versions = $this->_getVersions();
return array_column(array_filter($versions, static function($meta) {
return false === strpos($meta['version'], '-');
}), 'version');
}
/**
* Get installed version
*
* @param string $hostname
* @param string $path
*
* @return string|null|bool version number, null if not app or false on failure
*/
public function get_version(string $hostname, string $path = ''): ?string {
$docroot = $this->getDocumentRoot($hostname, $path);
if (! $this->valid($hostname, $path)) {
return null;
}
$contents = $this->file_get_file_contents("$docroot/index.php");
if (preg_match_all("/^.*VERSION.*\$/m", $contents, $lines)) {
if (0 !== preg_match('/\d{1,2}\.\d{1,2}\.\d{1,2}.\d{1,2}/', $lines[0][0], $matches)) {
return $matches[0];
}
return false;
}
return false;
}
/**
* Get all current major versions
*
* @return array
*/
private function _getVersions(): array {
$key = 'opencart.versions';
$cache = Cache_Super_Global::spawn();
if (false !== ($ver = $cache->get($key))) {
return (array) $ver;
}
$versions = (new Github)->setVersionField('tag_name')->fetch('opencart/opencart');
$cache->set($key, $versions, 43200);
return $versions;
}
/**
* Location is a valid webapp install
*
* @param string $hostname or $docroot
* @param string $path
*
* @return bool
*/
public function valid(string $hostname, string $path = ''): bool {
if ($hostname[0] === '/') {
$docroot = $hostname;
} else {
$docroot = $this->getDocumentRoot($hostname, $path);
if (! $docroot) {
return false;
}
}
return $this->file_exists("$docroot/extension/opencart/install.json");
}
/**
* 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);
// }
/**
* Update application to latest version
*
* @param string $hostname domain or subdomain under which application 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');
// }
//
// $oldversion = $this->get_version($hostname, $path);
// $ret = serial(function() use ($approot, $version, $hostname, $path) {
// if (! $version) {
// $version = Versioning::nextVersion($this->get_versions(),
// $this->get_version($hostname, $path));
// } else {
// if (! Versioning::valid($version)) {
// return error('invalid version number, %s', $version);
// }
// }
//
// /*
// * Download new package
// * Rename Admin if applicable by finding the existing admin folder if it was renamed
// * move storage outside the docroot
// * backup or safeguard configs before moving files
// * There's no way at this time to CLI update, the user will have to login as Admin
// */
//
// return $this->fortify($hostname, $path, data_get($this->getOptions($approot), 'fortify') ?: 'max');
// });
//
// $this->setInfo($approot, [
// 'version' => $ret ? $version : $oldversion,
// 'failed' => ! $ret
// ]);
//
// return (bool) $ret;
// }
/**
* Get database configuration for application
*
* @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 = '') {
$docroot = $this->getDocumentRoot($hostname, $path);
if (! $docroot) {
return error('failed to determine App');
}
$code = 'ob_start(); register_shutdown_function(static function() { file_put_contents("php://fd/3", serialize(array("user" => DB_USERNAME, "password" => DB_PASSWORD, "db" => DB_DATABASE, "host" => DB_HOSTNAME, "prefix" => DB_PREFIX))); ob_get_level() && ob_clean(); die(); }); include("./config.php"); die();';
$cmd = 'cd %(path)s && php -d mysqli.default_socket=%(socket)s -r %(code)s 3>&1-';
$ret = $this->pman_run($cmd,
[
'path' => $docroot,
'code' => $code,
'socket' => ini_get('mysqli.default_socket')
]
);
if (! $ret['success']) {
return error("failed to obtain %(app)s configuration for `%(approot)s': %(err)s", [
'app' => static::APP_NAME,
'approot' => $docroot,
'err' => $ret['stderr']
]);
}
return \Util_PHP::unserialize(trim($ret['stdout']));
}
/**
* Release meta
*
* @param string $version
*
* @return array|null
*/
private function versionMeta(string $version): ?array {
return array_first($this->_getVersions(), static function($meta) use ($version) {
return $meta['tag_name'] === $version;
});
}
/**
* Download remote OpenCart version and Extract into directory
*
* @param string $approot
* @param string $version
*
* @return bool
*/
private function downloadPackage(string $approot, string $version): bool {
if (null === ($meta = $this->versionMeta($version))) {
return error("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'];
$this->download($dlUrl, "$approot/");
foreach (static::CLEANUP_FILES as $file) {
$this->file_exists("$approot/$file") && $this->file_delete("$approot/$file", true);
}
return $this->file_move("$approot/upload/", "$approot/public") &&
$this->file_move("$approot/public/config-dist.php", "$approot/public/config.php") &&
$this->file_move("$approot/public/admin/config-dist.php", "$approot/public/admin/config.php") &&
$this->file_delete("$approot/upload", true);
}
/**
* Relocate the storage folder and update the configuration file
*
* @param string $approot
* @param array $pairs
*
* @return bool
*/
protected function relocateStorage(string $docroot, $approot): bool {
$this->file_move("$docroot/system/storage", "$approot/storage");
$files = ["$approot/public/config.php", "$approot/public/admin/config.php"];
$pairs = ['DIR_OPENCART' => "$approot/public/", 'DIR_STORAGE' => "$approot/storage/"];
try {
foreach ($files as $file) {
$instance = DefineReplace::instantiateContexted($this->getAuthContext(), [$file]);
foreach ($pairs as $k => $v) {
$instance->set($k, $v);
}
$instance->save();
}
return true;
} catch (\PhpParser\Error $e) {
return warn("Failed parsing %(file)s - cannot update %(directive)s",
['file' => $file]);
} catch (\ArgumentError $e) {
return warn("Failed parsing %(file)s - does not exist");
}
return false;
}
}