Total Complexity | 55 |
Total Lines | 615 |
Duplicated Lines | 0 % |
Changes | 0 |
Complex classes like Installer often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Installer, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
22 | class Installer extends InstallRequirements |
||
23 | { |
||
24 | /** |
||
25 | * value='' attribute placeholder for password fields |
||
26 | */ |
||
27 | const PASSWORD_PLACEHOLDER = '********'; |
||
28 | |||
29 | protected function installHeader() |
||
30 | { |
||
31 | $clientPath = PUBLIC_DIR |
||
32 | ? 'resources/vendor/silverstripe/framework/src/Dev/Install/client' |
||
33 | : 'resources/silverstripe/framework/src/Dev/Install/client'; |
||
34 | ?> |
||
35 | <html> |
||
36 | <head> |
||
37 | <meta charset="utf-8"/> |
||
38 | <title>Installing SilverStripe...</title> |
||
39 | <link rel="stylesheet" type="text/css" href="<?=$clientPath; ?>/styles/install.css"/> |
||
40 | <script src="//code.jquery.com/jquery-1.7.2.min.js"></script> |
||
41 | </head> |
||
42 | <body> |
||
43 | <div class="install-header"> |
||
44 | <div class="inner"> |
||
45 | <div class="brand"> |
||
46 | <span class="logo"></span> |
||
47 | |||
48 | <h1>SilverStripe</h1> |
||
49 | </div> |
||
50 | </div> |
||
51 | </div> |
||
52 | |||
53 | <div id="Navigation"> </div> |
||
54 | <div class="clear"><!-- --></div> |
||
55 | |||
56 | <div class="main"> |
||
57 | <div class="inner"> |
||
58 | <h2>Installing SilverStripe...</h2> |
||
59 | |||
60 | <p>I am now running through the installation steps (this should take about 30 seconds)</p> |
||
61 | |||
62 | <p>If you receive a fatal error, refresh this page to continue the installation</p> |
||
63 | <ul> |
||
64 | <?php |
||
65 | } |
||
66 | |||
67 | public function install($config) |
||
203 | } |
||
204 | |||
205 | protected function writeIndexPHP() |
||
206 | { |
||
207 | $content = <<<'PHP' |
||
208 | <?php |
||
209 | |||
210 | use SilverStripe\Control\HTTPApplication; |
||
211 | use SilverStripe\Control\HTTPRequestBuilder; |
||
212 | use SilverStripe\Core\CoreKernel; |
||
213 | use SilverStripe\Core\Startup\ErrorControlChainMiddleware; |
||
214 | |||
215 | // Find autoload.php |
||
216 | if (file_exists(__DIR__ . '/vendor/autoload.php')) { |
||
217 | require __DIR__ . '/vendor/autoload.php'; |
||
218 | } elseif (file_exists(__DIR__ . '/../vendor/autoload.php')) { |
||
219 | require __DIR__ . '/../vendor/autoload.php'; |
||
220 | } else { |
||
221 | echo "autoload.php not found"; |
||
222 | die; |
||
223 | } |
||
224 | |||
225 | // Build request and detect flush |
||
226 | $request = HTTPRequestBuilder::createFromEnvironment(); |
||
227 | |||
228 | // Default application |
||
229 | $kernel = new CoreKernel(BASE_PATH); |
||
230 | $app = new HTTPApplication($kernel); |
||
231 | $app->addMiddleware(new ErrorControlChainMiddleware($app)); |
||
232 | $response = $app->handle($request); |
||
233 | $response->output(); |
||
234 | PHP; |
||
235 | $path = $this->getPublicDir() . 'index.php'; |
||
236 | $this->writeToFile($path, $content, true); |
||
237 | } |
||
238 | |||
239 | /** |
||
240 | * Write all .env files |
||
241 | * |
||
242 | * @param $config |
||
243 | */ |
||
244 | protected function writeConfigEnv($config) |
||
245 | { |
||
246 | if (!$config['usingEnv']) { |
||
247 | return; |
||
248 | } |
||
249 | |||
250 | $path = $this->getBaseDir() . '.env'; |
||
251 | $vars = []; |
||
252 | |||
253 | // Retain existing vars |
||
254 | $env = new EnvironmentLoader(); |
||
255 | if (file_exists($path)) { |
||
256 | $vars = $env->loadFile($path) ?: []; |
||
257 | } |
||
258 | |||
259 | // Set base URL |
||
260 | if (!isset($vars['SS_BASE_URL']) && isset($_SERVER['HTTP_HOST'])) { |
||
261 | $vars['SS_BASE_URL'] = 'http://' . $_SERVER['HTTP_HOST'] . BASE_URL; |
||
262 | } |
||
263 | |||
264 | // Set DB env |
||
265 | if (empty($config['db']['database'])) { |
||
266 | $vars['SS_DATABASE_CHOOSE_NAME'] = true; |
||
267 | } else { |
||
268 | $vars['SS_DATABASE_NAME'] = $config['db']['database']; |
||
269 | } |
||
270 | $vars['SS_DATABASE_CLASS'] = $config['db']['type']; |
||
271 | if (isset($config['db']['server'])) { |
||
272 | $vars['SS_DATABASE_SERVER'] = $config['db']['server']; |
||
273 | } |
||
274 | if (isset($config['db']['username'])) { |
||
275 | $vars['SS_DATABASE_USERNAME'] = $config['db']['username']; |
||
276 | } |
||
277 | if (isset($config['db']['password'])) { |
||
278 | $vars['SS_DATABASE_PASSWORD'] = $config['db']['password']; |
||
279 | } |
||
280 | if (isset($config['db']['path'])) { |
||
281 | $vars['SS_DATABASE_PATH'] = $config['db']['path']; |
||
282 | // sqlite compat |
||
283 | $vars['SS_SQLITE_DATABASE_PATH'] = $config['db']['path']; |
||
284 | } |
||
285 | if (isset($config['db']['key'])) { |
||
286 | $vars['SS_DATABASE_KEY'] = $config['db']['key']; |
||
287 | // sqlite compat |
||
288 | $vars['SS_SQLITE_DATABASE_KEY'] = $config['db']['key']; |
||
289 | } |
||
290 | |||
291 | // Write all env vars |
||
292 | $lines = [ |
||
293 | '# Generated by SilverStripe Installer' |
||
294 | ]; |
||
295 | ksort($vars); |
||
296 | foreach ($vars as $key => $value) { |
||
297 | $lines[] = $key . '="' . addcslashes($value, '"') . '"'; |
||
298 | } |
||
299 | |||
300 | $this->writeToFile('.env', implode("\n", $lines)); |
||
301 | |||
302 | // Re-load env vars for installer access |
||
303 | $env->loadFile($path); |
||
304 | } |
||
305 | |||
306 | /** |
||
307 | * Write all *.php files |
||
308 | * |
||
309 | * @param array $config |
||
310 | */ |
||
311 | protected function writeConfigPHP($config) |
||
312 | { |
||
313 | if ($config['usingEnv']) { |
||
314 | $this->writeToFile("mysite/_config.php", "<?php\n "); |
||
315 | return; |
||
316 | } |
||
317 | |||
318 | // Create databaseConfig |
||
319 | $lines = []; |
||
320 | foreach ($config['db'] as $key => $value) { |
||
321 | $lines[] = sprintf( |
||
322 | " '%s' => '%s'", |
||
323 | addslashes($key), |
||
324 | addslashes($value) |
||
325 | ); |
||
326 | } |
||
327 | $databaseConfigContent = implode(",\n", $lines); |
||
328 | $this->writeToFile("mysite/_config.php", <<<PHP |
||
329 | <?php |
||
330 | |||
331 | use SilverStripe\\ORM\\DB; |
||
332 | |||
333 | DB::setConfig([ |
||
334 | {$databaseConfigContent} |
||
335 | ]); |
||
336 | |||
337 | PHP |
||
338 | ); |
||
339 | } |
||
340 | |||
341 | /** |
||
342 | * Write yml files |
||
343 | * |
||
344 | * @param array $config |
||
345 | */ |
||
346 | protected function writeConfigYaml($config) |
||
347 | { |
||
348 | // Escape user input for safe insertion into PHP file |
||
349 | $locale = $this->ymlString($config['locale']); |
||
350 | |||
351 | // Set either specified, or no theme |
||
352 | if ($config['theme'] && $config['theme'] !== 'tutorial') { |
||
353 | $theme = $this->ymlString($config['theme']); |
||
354 | $themeYML = <<<YML |
||
355 | - '\$public' |
||
356 | - '$theme' |
||
357 | - '\$default' |
||
358 | YML; |
||
359 | } else { |
||
360 | $themeYML = <<<YML |
||
361 | - '\$public' |
||
362 | - '\$default' |
||
363 | YML; |
||
364 | } |
||
365 | |||
366 | // Write theme.yml |
||
367 | $this->writeToFile("mysite/_config/theme.yml", <<<YML |
||
368 | --- |
||
369 | Name: mytheme |
||
370 | --- |
||
371 | SilverStripe\\View\\SSViewer: |
||
372 | themes: |
||
373 | $themeYML |
||
374 | SilverStripe\\i18n\\i18n: |
||
375 | default_locale: '$locale' |
||
376 | YML |
||
377 | ); |
||
378 | } |
||
379 | |||
380 | /** |
||
381 | * Escape yml string |
||
382 | * |
||
383 | * @param string $string |
||
384 | * @return mixed |
||
385 | */ |
||
386 | protected function ymlString($string) |
||
387 | { |
||
388 | // just escape single quotes using '' |
||
389 | return str_replace("'", "''", $string); |
||
390 | } |
||
391 | |||
392 | /** |
||
393 | * Write file to given location |
||
394 | * |
||
395 | * @param string $filename |
||
396 | * @param string $content |
||
397 | * @param bool $absolute If $filename is absolute path set to true |
||
398 | * @return bool |
||
399 | */ |
||
400 | public function writeToFile($filename, $content, $absolute = false) |
||
401 | { |
||
402 | $path = $absolute |
||
403 | ? $filename |
||
404 | : $this->getBaseDir() . $filename; |
||
405 | $this->statusMessage("Setting up $path"); |
||
406 | |||
407 | if ((@$fh = fopen($path, 'wb')) && fwrite($fh, $content) && fclose($fh)) { |
||
408 | // Set permissions to writable |
||
409 | @chmod($path, 0775); |
||
410 | return true; |
||
411 | } |
||
412 | $this->error("Couldn't write to file $path"); |
||
413 | return false; |
||
414 | } |
||
415 | |||
416 | /** |
||
417 | * Ensure root .htaccess is setup |
||
418 | */ |
||
419 | public function createHtaccess() |
||
420 | { |
||
421 | $start = "### SILVERSTRIPE START ###\n"; |
||
422 | $end = "\n### SILVERSTRIPE END ###"; |
||
423 | |||
424 | $base = dirname($_SERVER['SCRIPT_NAME']); |
||
425 | $base = Convert::slashes($base, '/'); |
||
426 | |||
427 | if ($base != '.') { |
||
428 | $baseClause = "RewriteBase '$base'\n"; |
||
429 | } else { |
||
430 | $baseClause = ""; |
||
431 | } |
||
432 | if (strpos(strtolower(php_sapi_name()), "cgi") !== false) { |
||
433 | $cgiClause = "RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\n"; |
||
434 | } else { |
||
435 | $cgiClause = ""; |
||
436 | } |
||
437 | $rewrite = <<<TEXT |
||
438 | # Deny access to templates (but allow from localhost) |
||
439 | <Files *.ss> |
||
440 | Order deny,allow |
||
441 | Deny from all |
||
442 | Allow from 127.0.0.1 |
||
443 | </Files> |
||
444 | |||
445 | # Deny access to IIS configuration |
||
446 | <Files web.config> |
||
447 | Order deny,allow |
||
448 | Deny from all |
||
449 | </Files> |
||
450 | |||
451 | # Deny access to YAML configuration files which might include sensitive information |
||
452 | <Files ~ "\.ya?ml$"> |
||
453 | Order allow,deny |
||
454 | Deny from all |
||
455 | </Files> |
||
456 | |||
457 | # Route errors to static pages automatically generated by SilverStripe |
||
458 | ErrorDocument 404 /assets/error-404.html |
||
459 | ErrorDocument 500 /assets/error-500.html |
||
460 | |||
461 | <IfModule mod_rewrite.c> |
||
462 | |||
463 | # Turn off index.php handling requests to the homepage fixes issue in apache >=2.4 |
||
464 | <IfModule mod_dir.c> |
||
465 | DirectoryIndex disabled |
||
466 | DirectorySlash On |
||
467 | </IfModule> |
||
468 | |||
469 | SetEnv HTTP_MOD_REWRITE On |
||
470 | RewriteEngine On |
||
471 | $baseClause |
||
472 | $cgiClause |
||
473 | |||
474 | # Deny access to potentially sensitive files and folders |
||
475 | RewriteRule ^vendor(/|$) - [F,L,NC] |
||
476 | RewriteRule ^\.env - [F,L,NC] |
||
477 | RewriteRule silverstripe-cache(/|$) - [F,L,NC] |
||
478 | RewriteRule composer\.(json|lock) - [F,L,NC] |
||
479 | RewriteRule (error|silverstripe|debug)\.log - [F,L,NC] |
||
480 | |||
481 | # Process through SilverStripe if no file with the requested name exists. |
||
482 | # Pass through the original path as a query parameter, and retain the existing parameters. |
||
483 | # Try finding framework in the vendor folder first |
||
484 | RewriteCond %{REQUEST_URI} ^(.*)$ |
||
485 | RewriteCond %{REQUEST_FILENAME} !-f |
||
486 | RewriteRule .* index.php |
||
487 | </IfModule> |
||
488 | TEXT; |
||
489 | |||
490 | $htaccessPath = $this->getPublicDir() . '.htaccess'; |
||
491 | if (file_exists($htaccessPath)) { |
||
492 | $htaccess = file_get_contents($htaccessPath); |
||
493 | |||
494 | if (strpos($htaccess, '### SILVERSTRIPE START ###') === false |
||
495 | && strpos($htaccess, '### SILVERSTRIPE END ###') === false |
||
496 | ) { |
||
497 | $htaccess .= "\n### SILVERSTRIPE START ###\n### SILVERSTRIPE END ###\n"; |
||
498 | } |
||
499 | |||
500 | if (strpos($htaccess, '### SILVERSTRIPE START ###') !== false |
||
501 | && strpos($htaccess, '### SILVERSTRIPE END ###') !== false |
||
502 | ) { |
||
503 | $start = substr($htaccess, 0, strpos($htaccess, '### SILVERSTRIPE START ###')) |
||
504 | . "### SILVERSTRIPE START ###\n"; |
||
505 | $end = "\n" . substr($htaccess, strpos($htaccess, '### SILVERSTRIPE END ###')); |
||
506 | } |
||
507 | } |
||
508 | |||
509 | $this->writeToFile($htaccessPath, $start . $rewrite . $end, true); |
||
510 | } |
||
511 | |||
512 | /** |
||
513 | * Writes basic configuration to the web.config for IIS |
||
514 | * so that rewriting capability can be use. |
||
515 | */ |
||
516 | public function createWebConfig() |
||
517 | { |
||
518 | $content = <<<TEXT |
||
519 | <?xml version="1.0" encoding="utf-8"?> |
||
520 | <configuration> |
||
521 | <system.webServer> |
||
522 | <security> |
||
523 | <requestFiltering> |
||
524 | <hiddenSegments applyToWebDAV="false"> |
||
525 | <add segment="silverstripe-cache" /> |
||
526 | <add segment="composer.json" /> |
||
527 | <add segment="composer.lock" /> |
||
528 | </hiddenSegments> |
||
529 | <fileExtensions allowUnlisted="true" > |
||
530 | <add fileExtension=".ss" allowed="false"/> |
||
531 | <add fileExtension=".yml" allowed="false"/> |
||
532 | </fileExtensions> |
||
533 | </requestFiltering> |
||
534 | </security> |
||
535 | <rewrite> |
||
536 | <rules> |
||
537 | <rule name="SilverStripe Clean URLs" stopProcessing="true"> |
||
538 | <match url="^(.*)$" /> |
||
539 | <conditions> |
||
540 | <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> |
||
541 | </conditions> |
||
542 | <action type="Rewrite" url="index.php" appendQueryString="true" /> |
||
543 | </rule> |
||
544 | </rules> |
||
545 | </rewrite> |
||
546 | </system.webServer> |
||
547 | </configuration> |
||
548 | TEXT; |
||
549 | |||
550 | $path = $this->getPublicDir() . 'web.config'; |
||
551 | $this->writeToFile($path, $content, true); |
||
552 | } |
||
553 | |||
554 | public function checkRewrite() |
||
555 | { |
||
556 | $token = new ParameterConfirmationToken('flush', new HTTPRequest('GET', '/')); |
||
557 | $params = http_build_query($token->params()); |
||
558 | |||
559 | $destinationURL = BASE_URL . '/' . ( |
||
560 | $this->checkModuleExists('cms') |
||
561 | ? "home/successfullyinstalled?$params" |
||
562 | : "?$params" |
||
563 | ); |
||
564 | |||
565 | echo <<<HTML |
||
566 | <li id="ModRewriteResult">Testing...</li> |
||
567 | <script> |
||
568 | if (typeof $ == 'undefined') { |
||
569 | document.getElemenyById('ModeRewriteResult').innerHTML = "I can't run jQuery ajax to set rewriting; I will redirect you to the homepage to see if everything is working."; |
||
570 | setTimeout(function() { |
||
571 | window.location = "$destinationURL"; |
||
572 | }, 10000); |
||
573 | } else { |
||
574 | $.ajax({ |
||
575 | method: 'get', |
||
576 | url: 'InstallerTest/testrewrite', |
||
577 | complete: function(response) { |
||
578 | var r = response.responseText.replace(/[^A-Z]?/g,""); |
||
579 | if (r === "OK") { |
||
580 | $('#ModRewriteResult').html("Friendly URLs set up successfully; I am now redirecting you to your SilverStripe site...") |
||
581 | setTimeout(function() { |
||
582 | window.location = "$destinationURL"; |
||
583 | }, 2000); |
||
584 | } else { |
||
585 | $('#ModRewriteResult').html("Friendly URLs are not working. This is most likely because a rewrite module isn't configured " |
||
586 | + "correctly on your site. You may need to get your web host or server administrator to do this for you: " |
||
587 | + "<ul>" |
||
588 | + "<li><strong>mod_rewrite</strong> or other rewrite module is enabled on your web server</li>" |
||
589 | + "<li><strong>AllowOverride All</strong> is set for the directory where SilverStripe is installed</li>" |
||
590 | + "</ul>"); |
||
591 | } |
||
592 | } |
||
593 | }); |
||
594 | } |
||
595 | </script> |
||
596 | <noscript> |
||
597 | <li><a href="$destinationURL">Click here</a> to check friendly URLs are working. If you get a 404 then something is wrong.</li> |
||
598 | </noscript> |
||
599 | HTML; |
||
600 | } |
||
601 | |||
602 | /** |
||
603 | * Show an installation status message. |
||
604 | * The output differs depending on whether this is CLI or web based |
||
605 | * |
||
606 | * @param string $msg |
||
607 | */ |
||
608 | public function statusMessage($msg) |
||
609 | { |
||
610 | echo "<li>$msg</li>\n"; |
||
611 | flush(); |
||
612 | } |
||
613 | |||
614 | /** |
||
615 | * @param $config |
||
616 | */ |
||
617 | protected function sendInstallStats($config) |
||
637 | } |
||
638 | } |
||
639 |