-
Notifications
You must be signed in to change notification settings - Fork 10
/
cmfive.php
executable file
·536 lines (459 loc) · 16.5 KB
/
cmfive.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
#!/usr/bin/php
<?php
if (!(isset($argc) && isset($argv))) {
echo "No action is possible.";
exit();
}
ini_set('display_errors', 1);
error_reporting(E_ALL);
/*
To add options:
--> * Adding to menu * -->
$menuMaker[] =
[
'option' => "Text will appear in menu",
'message' => "Text will display when launched",
'function' => "This function will be called as function() or function(param)",
'param' => null OR 'param' => "value" OR 'param' => [key array]
--> * NOTE * --> ONLY ONE PARAMETER IS PASSED
you need to provision your function vs param's deliberately!
]
--> * Adding to CLI * -->
$cmdMaker['aSingleWordNameForTheClassOfCommands'][] =
[
'request' => "commandToExecute",
'message' => "Text will display when launched and as CLI help",
'function' => "This function will be called as function() or function(argc, argv)",
'args' => true, OR 'args' => false,
'hint' => "Text will appear as CLI help if args=true",
"default" => [] OR ['aParameterName' => "aDefaultValue"] OR ['aParameterName' => null]
--> * NOTE * --> PARAMETERS ARE PASSED AS argc,argv IN CLI STYLE
defaults will read off in array order:
- hence will begin substituting when 'argv' runs out of entries
- a 'null' default value will halt as error error if 'argv' cannot fill
you need to provision your function vs param's deliberately!
]
]
*/
$menuMaker = [
[
'option' => "Install core libraries", 'message' => "Installing core libraries", 'function' => "installCoreLibraries", 'param' => "main"
],
[
'option' => "Install database migrations", 'message' => "Installing migrations", 'function' => "installMigrations", 'param' => null
],
[
'option' => "Seed admin user", 'message' => "Setting up admin user", 'function' => "seedAdminUser", 'param' => null
],
[
'option' => "Generate encryption keys", 'message' => "Generating encryption keys", 'function' => "generateEncryptionKeys", 'param' => null
],
];
$cmdMaker = [
'install' => [
[
'request' => "core", 'message' => "Installing core libraries", 'function' => "cmdinstallCoreLibraries", 'args' => true,
'hint' => "cmfive-core reference (default is 'main')", "default" => ['branch' => "main"]
],
[
'request' => "migration", 'message' => "Installing migrations", 'function' => "installMigrations", 'args' => false
],
[
'request' => "migrations", 'message' => "Installing migrations", 'function' => "installMigrations", 'args' => false
]
],
'seed' => [
[
'request' => "admin", 'message' => "Setting up admin user", 'function' => "cmdSeedAdminUser", 'args' => true,
'hint' => "F_name L_name email user password"
],
[
'request' => "encryption", 'message' => "Creating encryption keys", 'function' => "generateEncryptionKeys", 'args' => false
]
],
'cmfive' => [
[
'request' => "help", 'message' => "Command line options", 'function' => "synopsis", 'args' => false
]
]
];
include "cmfiveTests.php";
if ($argc >= 3) {
foreach ($cmdMaker as $command => $does) {
foreach ($does as $doing) {
if (($argv[1] == $command) && ($argv[2] == $doing['request'])) {
echo $command . " - " . $doing['message'] . "...\n\n";
if ($doing['args']) {
$shft = $argv;
array_shift($shft);
$defaults = $doing['default'] ?? [];
$substituted = process_default_arguments($shft, $defaults);
$doing['function'](count($substituted ?? []), $substituted);
} else {
$doing['function']();
}
exit(0);
}
}
}
echo "\nUnknown command\n";
exit(1);
}
function process_default_arguments($parameters, $defaults)
{
// this lacks smarts & works like a 'stack'
// because parameters do not come is as keyed values:
// they are 'argc' count and 'argv[]' array.
// so, nice key names on defaults are not used for matching
// but do allow exception message on missing req'd params
$request = array_slice($parameters, 0, 2);
$specs = array_slice($parameters, 2);
$seq = 0;
foreach ($defaults as $key => $value) {
if (empty($specs[$seq])) {
if (is_null($value)) {
echo "\nParameter: [" . $key . "] must be supplied!\n";
exit(1);
} else {
$specs[$seq] = $value;
}
}
$seq++;
}
return array_merge($request, $specs);
}
/////////////////////////////////////////////////////////////////////
$menuMaker[] =
[
'option' => "List command options", 'message' => "Command line options", 'function' => "synopsis", 'param' => null
];
$menuMaker[] =
[
'option' => "Exit (0)", 'message' => "Exiting", 'function' => "justQuit", 'param' => null
];
while (true) {
printMenu($menuMaker);
$command = readConsoleLine();
if ($command == "0") {
justQuit();
}
$sel = intval($command);
if (($sel > 0) && ($sel <= count($menuMaker))) {
$sel--;
echo $menuMaker[$sel]['message'] . "...\n\n";
if (!$menuMaker[$sel]['param']) {
$menuMaker[$sel]['function']();
} else {
$menuMaker[$sel]['function']($menuMaker[$sel]['param']);
}
} else {
echo "Command not found, please try again\n";
echo "\n";
}
}
/////////////////////////////////////////////////////////////////////
function justQuit()
{
exit(0);
}
function printMenu($menu)
{
echo "*************************************";
echo "\n Cmfive Installation Tools";
echo "\n*************************************\n";
if (!file_exists("config.php")) {
echo "You need to set up your config.php file first (see example)\n";
justQuit();
}
$i = 1;
foreach ($menu as $menuEntry) {
echo $i . ") " . $menuEntry['option'] . "\n";
$i++;
}
}
function synopsis()
{
global $cmdMaker;
foreach ($cmdMaker as $command => $does) {
foreach ($does as $doing) {
echo //__FILE__
$_SERVER['SCRIPT_NAME'] . " " . $command . " " . $doing['request'];
if ($doing['args'] && !isset($doing['implied'])) {
echo " ["
. (isset($doing['hint']) ? $doing['hint'] : "args...")
. "]";
}
echo " - (" . $doing['message'] . ")\n";
}
}
echo "\n";
}
function stepOneYieldsWeb()
{
// so we can find modules & some CM5 functions...
$webFind = "system/web.php";
if (is_readable($webFind) && !is_dir($webFind)) {
if (!class_exists('Web')) {
require($webFind);
}
refreshComposerAvailability();
return true;
}
echo "\nOrder of steps is important - can't find CORE INSTALL";
echo "\nMake sure to locate CORE and arrange SYSTEM symlink\n\n";
return false;
}
function refreshComposerAvailability()
{
// in case Composer has pulled new packages
// after the autoloader already went up from Web
// (when core is installed, web is used for module configs dependencies)
// (so autoloader needs flushing when the modules have finally come in)
$allIncluded = get_declared_classes();
foreach ($allIncluded as $key => $class) {
//because our ComposerAutoloader class has a suffixed long-hash:
if (strpos($class, "ComposerAutoloaderInit") !== false) {
$composerLoader = $class;
// OK we found it, so apply this stolen code from:
// composer\vendor\composer\autoload_real.php
$map = require 'composer/vendor/composer/autoload_psr4.php';
foreach ($map as $namespace => $path) {
// a minimal response, as Psr4 gets us
// at least the db classes needed for web
$composerLoader::getLoader()->setPsr4($namespace, $path);
}
echo "\nFlicked Composer switch: " . $class . "\n";
}
}
}
function cmdinstallCoreLibraries($pCount, $parameters = [])
{
installCoreLibraries(($pCount > 2) ? $parameters[2] : null, ($pCount > 3) ? $parameters[3] : null);
};
function installCoreLibraries($branch = null, $phpVersion = null)
{
// name : 2pisoftware/cmfive-core
// descrip. :
// keywords :
// versions : * main
// type : library
// source : [git] https://github.com/2pisoftware/cmfive-core develop
// dist : []
// names : 2pisoftware/cmfive-core
if (is_null($branch)) {
echo ("No branch from core repository was specified.\n");
} else {
echo ("Installing {$branch} from core repository.\n");
}
if (is_null($phpVersion)) {
echo ("No PHP version for Composer was specified.\n");
} else {
echo ("Asserting PHP version ({$phpVersion}) for Composer.\n");
}
$composer_json = sketchComposerForCore($branch, $phpVersion);
file_put_contents('./composer.json', json_encode($composer_json, JSON_PRETTY_PRINT));
echo exec('php composer.phar install');
$msg = "";
$out = 0;
try {
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
echo exec('mklink /J system composer\vendor\2pisoftware\cmfive-core\system', $msg, $out);
} else {
echo exec('ln -s composer/vendor/2pisoftware/cmfive-core/system system', $msg, $out);
}
} catch (Exception $e) {
echo $e->getMessage();
$out = 1;
}
if ($out !== 0) {
echo "\nFailed Linking for : \nsystem <---> composer/vendor/2pisoftware/cmfive-core/system";
echo "\nComposer dependencies will not install for a missing system path";
echo "\n(Check any permissions, fs mounts, host_vs_container links etc)";
echo "\nYou may need to rerun this step!\n\n";
}
installThirdPartyLibraries($composer_json);
}
function sketchComposerForCore($reference, $phpVersion)
{
// name : 2pisoftware/cmfive-core
// descrip. :
// keywords :
// versions : * main
// type : library
// source : [git] https://github.com/2pisoftware/cmfive-core develop
// dist : []
// names : 2pisoftware/cmfive-core
if (is_null($reference) || is_null($phpVersion)) {
if (PHP_MAJOR_VERSION === 7 && PHP_MINOR_VERSION === 0) {
$reference = "legacy/PHP7.0";
$phpVersion = "7.0";
}
if (PHP_MAJOR_VERSION === 7 && PHP_MINOR_VERSION === 4) {
$reference = "legacy/PHP7.4";
$phpVersion = "7.4";
}
if (is_null($reference) || is_null($phpVersion)) {
$reference = is_null($reference) ? "main" : $reference;
$phpVersion = is_null($phpVersion) ? (PHP_MAJOR_VERSION .".". PHP_MINOR_VERSION) : $phpVersion;
}
}
echo ("Composer has ref's as " . $reference . " & " . $phpVersion . ".\n");
$composer_string = <<<COMPOSER
{
"name": "2pisoftware/cmfive-boilerplate",
"version": "1.0",
"description": "A boilerplate project layout for Cmfive",
"require": {
"2pisoftware/cmfive-core": "dev-$reference",
"aws/aws-sdk-php": "^3.288"
},
"config": {
"vendor-dir": "composer/vendor",
"cache-dir": "composer/cache",
"bin-dir": "composer/bin",
"platform": {
"php": "$phpVersion"
}
},
"repositories": [
{
"type": "package",
"package": {
"name": "2pisoftware/cmfive-core",
"version": "dev-$reference",
"source": {
"url": "https://github.com/2pisoftware/cmfive-core",
"type": "git",
"reference": "$reference"
}
}
}
]
}
COMPOSER;
return json_decode($composer_string, true);
}
function installThirdPartyLibraries(array $composer_json)
{
if (!stepOneYieldsWeb()) {
return false;
}
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
echo exec('del .\cache\config.cache');
} else {
echo exec('rm -f cache/config.cache');
}
$w = new Web();
$dependencies_array = [];
foreach ($w->modules() as $module) {
$dependencies = Config::get("{$module}.dependencies");
if (!empty($dependencies)) {
$dependencies_array = array_merge($dependencies, $dependencies_array);
}
}
$composer_json['require'] = array_merge($composer_json['require'], $dependencies_array);
file_put_contents('./composer.json', json_encode($composer_json, JSON_PRETTY_PRINT));
echo exec('php composer.phar update');
}
function installMigrations()
{
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
echo exec('del .\cache\config.cache');
} else {
echo exec('rm -f cache/config.cache');
}
if (!stepOneYieldsWeb()) {
return false;
}
$w = new Web();
$w->initDB();
$_SESSION = [];
try {
MigrationService::getInstance($w)->installInitialMigration();
MigrationService::getInstance($w)->runMigrations("all");
echo "Migrations have run\n";
} catch (Exception $e) {
echo $e->getMessage();
}
}
function cmdSeedAdminUser($pCount, $parameters = [])
{
$parameters = array_slice($parameters, 2);
seedAdminUser($parameters);
};
function seedAdminUser($parameters = [])
{
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
echo exec('del .\cache\config.cache');
} else {
echo exec('rm -f cache/config.cache');
}
if (!stepOneYieldsWeb()) {
return false;
}
$w = new Web();
$w->initDB();
// Set up fake session to stop warnings
$_SESSION = [];
$findAdmin = AuthService::getInstance($w)->getObject("User", ["is_admin" => true]);
if (isset($findAdmin->id)) {
echo "\nOrder of steps is important - ADMIN USER EXISTS";
echo "\nSetup will not create multiple admin users\n\n";
return false;
}
$admin_contact = new Contact($w);
$admin_contact->firstname = !empty($parameters[0]) ? $parameters[0] : readConsoleLine("Enter first name: ");
$admin_contact->lastname = !empty($parameters[1]) ? $parameters[1] : readConsoleLine("Enter last name: ");
$admin_contact->email = !empty($parameters[2]) ? $parameters[2] : readConsoleLine("Enter email address: ");
$admin_contact->insert();
$admin_user = new User($w);
$admin_user->contact_id = $admin_contact->id;
$admin_user->login = !empty($parameters[3]) ? $parameters[3] : readConsoleLine("Enter admin login: ");
$admin_user->is_admin = 1;
$admin_user->is_active = 1;
$admin_user->insert();
$admin_user->setPassword(!empty($parameters[4]) ? $parameters[4] : readConsoleLine("Enter admin password: "));
$admin_user->update();
$user_role = new UserRole($w);
$user_role->user_id = $admin_user->id;
$user_role->role = "user";
$user_role->insert();
echo "Admin user setup successful\n";
return true;
}
function generateEncryptionKeys()
{
if (!stepOneYieldsWeb()) {
return false;
}
if (!empty(Config::get("system.encryption"))) {
echo "\nOrder of steps is important - KEY ALREADY EXISTS";
echo "\nSetup will not create multiple encryption keys\n\n";
return false;
}
$key_token = '';
//$key_iv = '';
if (PHP_VERSION_ID >= 70000) {
$key_token = random_bytes(32);
//$key_iv = random_bytes(8);
} else {
$key_token = openssl_random_pseudo_bytes(32);
//$key_iv = openssl_random_pseudo_bytes(8);
}
$key_token = bin2hex($key_token);
echo "Encryption key generated\n";
file_put_contents('config.php', "\nConfig::set('system.encryption', [\n\t'key' => '{$key_token}'\n]);", FILE_APPEND);
echo "Key written to project config\n\n";
return true;
}
function readConsoleLine($prompt = "Command: ")
{
$command = '';
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
echo $prompt;
$command = stream_get_line(STDIN, 1024, PHP_EOL);
} else {
$command = readline($prompt);
}
return $command;
}