-
Notifications
You must be signed in to change notification settings - Fork 132
/
Setup.php
432 lines (337 loc) · 12.5 KB
/
Setup.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
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Shield\Commands;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Commands\Database\Migrate;
use CodeIgniter\Shield\Commands\Setup\ContentReplacer;
use CodeIgniter\Test\Filters\CITestStreamFilter;
use Config\Autoload as AutoloadConfig;
use Config\Email as EmailConfig;
use Config\Services;
class Setup extends BaseCommand
{
/**
* The Command's name
*
* @var string
*/
protected $name = 'shield:setup';
/**
* the Command's short description
*
* @var string
*/
protected $description = 'Initial setup for CodeIgniter Shield.';
/**
* the Command's usage
*
* @var string
*/
protected $usage = 'shield:setup';
/**
* the Command's Arguments
*
* @var array<string, string>
*/
protected $arguments = [];
/**
* the Command's Options
*
* @var array<string, string>
*/
protected $options = [
'-f' => 'Force overwrite ALL existing files in destination.',
];
/**
* The path to `CodeIgniter\Shield\` src directory.
*
* @var string
*/
protected $sourcePath;
protected $distPath = APPPATH;
private ContentReplacer $replacer;
/**
* Displays the help for the spark cli script itself.
*/
public function run(array $params): void
{
$this->replacer = new ContentReplacer();
$this->sourcePath = __DIR__ . '/../';
$this->publishConfig();
}
private function publishConfig(): void
{
$this->publishConfigAuth();
$this->publishConfigAuthGroups();
$this->publishConfigAuthToken();
$this->setAutoloadHelpers();
$this->setupRoutes();
$this->setSecurityCSRF();
$this->setupEmail();
$this->runMigrations();
}
/**
* @param string $file Relative file path like 'Config/Auth.php'.
* @param array $replaces [search => replace]
*/
protected function copyAndReplace(string $file, array $replaces): void
{
$path = "{$this->sourcePath}/{$file}";
$content = file_get_contents($path);
$content = $this->replacer->replace($content, $replaces);
$this->writeFile($file, $content);
}
private function publishConfigAuth(): void
{
$file = 'Config/Auth.php';
$replaces = [
'namespace CodeIgniter\Shield\Config' => 'namespace Config',
'use CodeIgniter\\Config\\BaseConfig;' => 'use CodeIgniter\\Shield\\Config\\Auth as ShieldAuth;',
'extends BaseConfig' => 'extends ShieldAuth',
];
$this->copyAndReplace($file, $replaces);
}
private function publishConfigAuthGroups(): void
{
$file = 'Config/AuthGroups.php';
$replaces = [
'namespace CodeIgniter\Shield\Config' => 'namespace Config',
'use CodeIgniter\\Config\\BaseConfig;' => 'use CodeIgniter\\Shield\\Config\\AuthGroups as ShieldAuthGroups;',
'extends BaseConfig' => 'extends ShieldAuthGroups',
];
$this->copyAndReplace($file, $replaces);
}
private function publishConfigAuthToken(): void
{
$file = 'Config/AuthToken.php';
$replaces = [
'namespace CodeIgniter\Shield\Config;' => "namespace Config;\n\nuse CodeIgniter\\Shield\\Config\\AuthToken as ShieldAuthToken;",
'extends BaseAuthToken' => 'extends ShieldAuthToken',
];
$this->copyAndReplace($file, $replaces);
}
/**
* Write a file, catching any exceptions and showing a
* nicely formatted error.
*
* @param string $file Relative file path like 'Config/Auth.php'.
*/
protected function writeFile(string $file, string $content): void
{
$path = $this->distPath . $file;
$cleanPath = clean_path($path);
$directory = dirname($path);
if (! is_dir($directory)) {
mkdir($directory, 0777, true);
}
if (file_exists($path)) {
$overwrite = (bool) CLI::getOption('f');
if (
! $overwrite
&& $this->prompt(" File '{$cleanPath}' already exists in destination. Overwrite?", ['n', 'y']) === 'n'
) {
$this->error(" Skipped {$cleanPath}. If you wish to overwrite, please use the '-f' option or reply 'y' to the prompt.");
return;
}
}
if (write_file($path, $content)) {
$this->write(CLI::color(' Created: ', 'green') . $cleanPath);
} else {
$this->error(" Error creating {$cleanPath}.");
}
}
/**
* @param string $code Code to add.
* @param string $file Relative file path like 'Controllers/BaseController.php'.
*/
protected function add(string $file, string $code, string $pattern, string $replace): void
{
$path = $this->distPath . $file;
$cleanPath = clean_path($path);
$content = file_get_contents($path);
$output = $this->replacer->add($content, $code, $pattern, $replace);
if ($output === true) {
$this->error(" Skipped {$cleanPath}. It has already been updated.");
return;
}
if ($output === false) {
$this->error(" Error checking {$cleanPath}.");
return;
}
if (write_file($path, $output)) {
$this->write(CLI::color(' Updated: ', 'green') . $cleanPath);
} else {
$this->error(" Error updating {$cleanPath}.");
}
}
/**
* Replace for setupHelper()
*
* @param string $file Relative file path like 'Controllers/BaseController.php'.
* @param array $replaces [search => replace]
*/
private function replace(string $file, array $replaces): bool
{
$path = $this->distPath . $file;
$cleanPath = clean_path($path);
$content = file_get_contents($path);
$output = $this->replacer->replace($content, $replaces);
if ($output === $content) {
return false;
}
if (write_file($path, $output)) {
$this->write(CLI::color(' Updated: ', 'green') . $cleanPath);
return true;
}
$this->error(" Error updating {$cleanPath}.");
return false;
}
private function setAutoloadHelpers(): void
{
$file = 'Config/Autoload.php';
$path = $this->distPath . $file;
$cleanPath = clean_path($path);
$config = new AutoloadConfig();
$helpers = $config->helpers;
$newHelpers = array_unique(array_merge($helpers, ['auth', 'setting']));
$pattern = '/^ public \$helpers = \[.*\];/mu';
$replace = ' public $helpers = [\'' . implode("', '", $newHelpers) . '\'];';
$content = file_get_contents($path);
$output = preg_replace($pattern, $replace, $content);
// check if the content is updated
if ($output === $content) {
$this->write(CLI::color(' Autoload Setup: ', 'green') . 'Everything is fine.');
return;
}
if (write_file($path, $output)) {
$this->write(CLI::color(' Updated: ', 'green') . $cleanPath);
$this->removeHelperLoadingInBaseController();
} else {
$this->error(" Error updating file '{$cleanPath}'.");
}
}
private function removeHelperLoadingInBaseController(): void
{
$file = 'Controllers/BaseController.php';
$check = ' $this->helpers = array_merge($this->helpers, [\'setting\']);';
// Replace old helper setup
$replaces = [
'$this->helpers = array_merge($this->helpers, [\'auth\', \'setting\']);' => $check,
];
$this->replace($file, $replaces);
// Remove helper setup
$replaces = [
"\n" . $check . "\n" => '',
];
$this->replace($file, $replaces);
}
private function setupRoutes(): void
{
$file = 'Config/Routes.php';
$check = 'service(\'auth\')->routes($routes);';
$pattern = '/(.*)(\n' . preg_quote('$routes->', '/') . '[^\n]+?;\n)/su';
$replace = '$1$2' . "\n" . $check . "\n";
$this->add($file, $check, $pattern, $replace);
}
/**
* @see https://github.com/codeigniter4/shield/security/advisories/GHSA-5hm8-vh6r-2cjq
*/
private function setSecurityCSRF(): void
{
$file = 'Config/Security.php';
$replaces = [
'$csrfProtection = \'cookie\';' => '$csrfProtection = \'session\';',
];
$path = $this->distPath . $file;
$cleanPath = clean_path($path);
if (! is_file($path)) {
$this->error(" Not found file '{$cleanPath}'.");
return;
}
$content = file_get_contents($path);
$output = $this->replacer->replace($content, $replaces);
// check $csrfProtection = 'session'
if ($output === $content) {
$this->write(CLI::color(' Security Setup: ', 'green') . 'Everything is fine.');
return;
}
if (write_file($path, $output)) {
$this->write(CLI::color(' Updated: ', 'green') . "We have updated file '{$cleanPath}' for security reasons.");
} else {
$this->error(" Error updating file '{$cleanPath}'.");
}
}
private function setupEmail(): void
{
$file = 'Config/Email.php';
$path = $this->distPath . $file;
$cleanPath = clean_path($path);
if (! is_file($path)) {
$this->error(" Not found file '{$cleanPath}'.");
return;
}
$config = config(EmailConfig::class);
$fromEmail = (string) $config->fromEmail; // Old Config may return null.
$fromName = (string) $config->fromName;
if ($fromEmail !== '' && $fromName !== '') {
$this->write(CLI::color(' Email Setup: ', 'green') . 'Everything is fine.');
return;
}
$content = file_get_contents($path);
$output = $content;
if ($fromEmail === '') {
$set = $this->prompt(' The required Config\Email::$fromEmail is not set. Do you set now?', ['y', 'n']);
if ($set === 'y') {
// Input from email
$fromEmail = $this->prompt(' What is your email?', null, 'required|valid_email');
$pattern = '/^ public .*\$fromEmail\s+= \'\';/mu';
$replace = ' public string $fromEmail = \'' . $fromEmail . '\';';
$output = preg_replace($pattern, $replace, $content);
}
}
if ($fromName === '') {
$set = $this->prompt(' The required Config\Email::$fromName is not set. Do you set now?', ['y', 'n']);
if ($set === 'y') {
$fromName = $this->prompt(' What is your name?', null, 'required');
$pattern = '/^ public .*\$fromName\s+= \'\';/mu';
$replace = ' public string $fromName = \'' . $fromName . '\';';
$output = preg_replace($pattern, $replace, $output);
}
}
if (write_file($path, $output)) {
$this->write(CLI::color(' Updated: ', 'green') . $cleanPath);
} else {
$this->error(" Error updating file '{$cleanPath}'.");
}
}
private function runMigrations(): void
{
if (
$this->prompt(' Run `spark migrate --all` now?', ['y', 'n']) === 'n'
) {
return;
}
$command = new Migrate(Services::logger(), Services::commands());
// This is a hack for testing.
// @TODO Remove CITestStreamFilter and refactor when CI 4.5.0 or later is supported.
CITestStreamFilter::registration();
CITestStreamFilter::addOutputFilter();
CITestStreamFilter::addErrorFilter();
$command->run(['all' => null]);
CITestStreamFilter::removeOutputFilter();
CITestStreamFilter::removeErrorFilter();
// Capture the output, and write for testing.
// @TODO Remove CITestStreamFilter and refactor when CI 4.5.0 or later is supported.
$output = CITestStreamFilter::$buffer;
$this->write($output);
CITestStreamFilter::$buffer = '';
}
}