Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / lib / Drupal / Core / DrupalKernel.php
1 <?php
2
3 namespace Drupal\Core;
4
5 use Composer\Autoload\ClassLoader;
6 use Drupal\Component\Assertion\Handle;
7 use Drupal\Component\FileCache\FileCacheFactory;
8 use Drupal\Component\Utility\UrlHelper;
9 use Drupal\Core\Cache\DatabaseBackend;
10 use Drupal\Core\Config\BootstrapConfigStorageFactory;
11 use Drupal\Core\Config\NullStorage;
12 use Drupal\Core\Database\Database;
13 use Drupal\Core\DependencyInjection\ContainerBuilder;
14 use Drupal\Core\DependencyInjection\ServiceModifierInterface;
15 use Drupal\Core\DependencyInjection\ServiceProviderInterface;
16 use Drupal\Core\DependencyInjection\YamlFileLoader;
17 use Drupal\Core\Extension\ExtensionDiscovery;
18 use Drupal\Core\File\MimeType\MimeTypeGuesser;
19 use Drupal\Core\Http\TrustedHostsRequestFactory;
20 use Drupal\Core\Installer\InstallerRedirectTrait;
21 use Drupal\Core\Language\Language;
22 use Drupal\Core\Security\RequestSanitizer;
23 use Drupal\Core\Site\Settings;
24 use Drupal\Core\Test\TestDatabase;
25 use Symfony\Cmf\Component\Routing\RouteObjectInterface;
26 use Symfony\Component\ClassLoader\ApcClassLoader;
27 use Symfony\Component\ClassLoader\WinCacheClassLoader;
28 use Symfony\Component\ClassLoader\XcacheClassLoader;
29 use Symfony\Component\DependencyInjection\ContainerInterface;
30 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
31 use Symfony\Component\HttpFoundation\RedirectResponse;
32 use Symfony\Component\HttpFoundation\Request;
33 use Symfony\Component\HttpFoundation\Response;
34 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
35 use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
36 use Symfony\Component\HttpKernel\TerminableInterface;
37 use Symfony\Component\Routing\Route;
38
39 /**
40  * The DrupalKernel class is the core of Drupal itself.
41  *
42  * This class is responsible for building the Dependency Injection Container and
43  * also deals with the registration of service providers. It allows registered
44  * service providers to add their services to the container. Core provides the
45  * CoreServiceProvider, which, in addition to registering any core services that
46  * cannot be registered in the core.services.yaml file, adds any compiler passes
47  * needed by core, e.g. for processing tagged services. Each module can add its
48  * own service provider, i.e. a class implementing
49  * Drupal\Core\DependencyInjection\ServiceProvider, to register services to the
50  * container, or modify existing services.
51  */
52 class DrupalKernel implements DrupalKernelInterface, TerminableInterface {
53   use InstallerRedirectTrait;
54
55   /**
56    * Holds the class used for dumping the container to a PHP array.
57    *
58    * In combination with swapping the container class this is useful to e.g.
59    * dump to the human-readable PHP array format to debug the container
60    * definition in an easier way.
61    *
62    * @var string
63    */
64   protected $phpArrayDumperClass = '\Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper';
65
66   /**
67    * Holds the default bootstrap container definition.
68    *
69    * @var array
70    */
71   protected $defaultBootstrapContainerDefinition = [
72     'parameters' => [],
73     'services' => [
74       'database' => [
75         'class' => 'Drupal\Core\Database\Connection',
76         'factory' => 'Drupal\Core\Database\Database::getConnection',
77         'arguments' => ['default'],
78       ],
79       'cache.container' => [
80         'class' => 'Drupal\Core\Cache\DatabaseBackend',
81         'arguments' => ['@database', '@cache_tags_provider.container', 'container', DatabaseBackend::MAXIMUM_NONE],
82       ],
83       'cache_tags_provider.container' => [
84         'class' => 'Drupal\Core\Cache\DatabaseCacheTagsChecksum',
85         'arguments' => ['@database'],
86       ],
87     ],
88   ];
89
90   /**
91    * Holds the class used for instantiating the bootstrap container.
92    *
93    * @var string
94    */
95   protected $bootstrapContainerClass = '\Drupal\Component\DependencyInjection\PhpArrayContainer';
96
97   /**
98    * Holds the bootstrap container.
99    *
100    * @var \Symfony\Component\DependencyInjection\ContainerInterface
101    */
102   protected $bootstrapContainer;
103
104   /**
105    * Holds the container instance.
106    *
107    * @var \Symfony\Component\DependencyInjection\ContainerInterface
108    */
109   protected $container;
110
111   /**
112    * The environment, e.g. 'testing', 'install'.
113    *
114    * @var string
115    */
116   protected $environment;
117
118   /**
119    * Whether the kernel has been booted.
120    *
121    * @var bool
122    */
123   protected $booted = FALSE;
124
125   /**
126    * Whether essential services have been set up properly by preHandle().
127    *
128    * @var bool
129    */
130   protected $prepared = FALSE;
131
132   /**
133    * Holds the list of enabled modules.
134    *
135    * @var array
136    *   An associative array whose keys are module names and whose values are
137    *   ignored.
138    */
139   protected $moduleList;
140
141   /**
142    * List of available modules and installation profiles.
143    *
144    * @var \Drupal\Core\Extension\Extension[]
145    */
146   protected $moduleData = [];
147
148   /**
149    * The class loader object.
150    *
151    * @var \Composer\Autoload\ClassLoader
152    */
153   protected $classLoader;
154
155   /**
156    * Config storage object used for reading enabled modules configuration.
157    *
158    * @var \Drupal\Core\Config\StorageInterface
159    */
160   protected $configStorage;
161
162   /**
163    * Whether the container can be dumped.
164    *
165    * @var bool
166    */
167   protected $allowDumping;
168
169   /**
170    * Whether the container needs to be rebuilt the next time it is initialized.
171    *
172    * @var bool
173    */
174   protected $containerNeedsRebuild = FALSE;
175
176   /**
177    * Whether the container needs to be dumped once booting is complete.
178    *
179    * @var bool
180    */
181   protected $containerNeedsDumping;
182
183   /**
184    * List of discovered services.yml pathnames.
185    *
186    * This is a nested array whose top-level keys are 'app' and 'site', denoting
187    * the origin of a service provider. Site-specific providers have to be
188    * collected separately, because they need to be processed last, so as to be
189    * able to override services from application service providers.
190    *
191    * @var array
192    */
193   protected $serviceYamls;
194
195   /**
196    * List of discovered service provider class names or objects.
197    *
198    * This is a nested array whose top-level keys are 'app' and 'site', denoting
199    * the origin of a service provider. Site-specific providers have to be
200    * collected separately, because they need to be processed last, so as to be
201    * able to override services from application service providers.
202    *
203    * Allowing objects is for example used to allow
204    * \Drupal\KernelTests\KernelTestBase to register itself as service provider.
205    *
206    * @var array
207    */
208   protected $serviceProviderClasses;
209
210   /**
211    * List of instantiated service provider classes.
212    *
213    * @see \Drupal\Core\DrupalKernel::$serviceProviderClasses
214    *
215    * @var array
216    */
217   protected $serviceProviders;
218
219   /**
220    * Whether the PHP environment has been initialized.
221    *
222    * This legacy phase can only be booted once because it sets session INI
223    * settings. If a session has already been started, re-generating these
224    * settings would break the session.
225    *
226    * @var bool
227    */
228   protected static $isEnvironmentInitialized = FALSE;
229
230   /**
231    * The site directory.
232    *
233    * @var string
234    */
235   protected $sitePath;
236
237   /**
238    * The app root.
239    *
240    * @var string
241    */
242   protected $root;
243
244   /**
245    * Create a DrupalKernel object from a request.
246    *
247    * @param \Symfony\Component\HttpFoundation\Request $request
248    *   The request.
249    * @param $class_loader
250    *   The class loader. Normally Composer's ClassLoader, as included by the
251    *   front controller, but may also be decorated; e.g.,
252    *   \Symfony\Component\ClassLoader\ApcClassLoader.
253    * @param string $environment
254    *   String indicating the environment, e.g. 'prod' or 'dev'.
255    * @param bool $allow_dumping
256    *   (optional) FALSE to stop the container from being written to or read
257    *   from disk. Defaults to TRUE.
258    * @param string $app_root
259    *   (optional) The path to the application root as a string. If not supplied,
260    *   the application root will be computed.
261    *
262    * @return static
263    *
264    * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
265    *   In case the host name in the request is not trusted.
266    */
267   public static function createFromRequest(Request $request, $class_loader, $environment, $allow_dumping = TRUE, $app_root = NULL) {
268     $kernel = new static($environment, $class_loader, $allow_dumping, $app_root);
269     static::bootEnvironment($app_root);
270     $kernel->initializeSettings($request);
271     return $kernel;
272   }
273
274   /**
275    * Constructs a DrupalKernel object.
276    *
277    * @param string $environment
278    *   String indicating the environment, e.g. 'prod' or 'dev'.
279    * @param $class_loader
280    *   The class loader. Normally \Composer\Autoload\ClassLoader, as included by
281    *   the front controller, but may also be decorated; e.g.,
282    *   \Symfony\Component\ClassLoader\ApcClassLoader.
283    * @param bool $allow_dumping
284    *   (optional) FALSE to stop the container from being written to or read
285    *   from disk. Defaults to TRUE.
286    * @param string $app_root
287    *   (optional) The path to the application root as a string. If not supplied,
288    *   the application root will be computed.
289    */
290   public function __construct($environment, $class_loader, $allow_dumping = TRUE, $app_root = NULL) {
291     $this->environment = $environment;
292     $this->classLoader = $class_loader;
293     $this->allowDumping = $allow_dumping;
294     if ($app_root === NULL) {
295       $app_root = static::guessApplicationRoot();
296     }
297     $this->root = $app_root;
298   }
299
300   /**
301    * Determine the application root directory based on this file's location.
302    *
303    * @return string
304    *   The application root.
305    */
306   protected static function guessApplicationRoot() {
307     // Determine the application root by:
308     // - Removing the namespace directories from the path.
309     // - Getting the path to the directory two levels up from the path
310     //   determined in the previous step.
311     return dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
312   }
313
314   /**
315    * Returns the appropriate site directory for a request.
316    *
317    * Once the kernel has been created DrupalKernelInterface::getSitePath() is
318    * preferred since it gets the statically cached result of this method.
319    *
320    * Site directories contain all site specific code. This includes settings.php
321    * for bootstrap level configuration, file configuration stores, public file
322    * storage and site specific modules and themes.
323    *
324    * A file named sites.php must be present in the sites directory for
325    * multisite. If it doesn't exist, then 'sites/default' will be used.
326    *
327    * Finds a matching site directory file by stripping the website's hostname
328    * from left to right and pathname from right to left. By default, the
329    * directory must contain a 'settings.php' file for it to match. If the
330    * parameter $require_settings is set to FALSE, then a directory without a
331    * 'settings.php' file will match as well. The first configuration file found
332    * will be used and the remaining ones will be ignored. If no configuration
333    * file is found, returns a default value 'sites/default'. See
334    * default.settings.php for examples on how the URL is converted to a
335    * directory.
336    *
337    * The sites.php file in the sites directory can define aliases in an
338    * associative array named $sites. The array is written in the format
339    * '<port>.<domain>.<path>' => 'directory'. As an example, to create a
340    * directory alias for https://www.drupal.org:8080/mysite/test whose
341    * configuration file is in sites/example.com, the array should be defined as:
342    * @code
343    * $sites = array(
344    *   '8080.www.drupal.org.mysite.test' => 'example.com',
345    * );
346    * @endcode
347    *
348    * @param \Symfony\Component\HttpFoundation\Request $request
349    *   The current request.
350    * @param bool $require_settings
351    *   Only directories with an existing settings.php file will be recognized.
352    *   Defaults to TRUE. During initial installation, this is set to FALSE so
353    *   that Drupal can detect a matching directory, then create a new
354    *   settings.php file in it.
355    * @param string $app_root
356    *   (optional) The path to the application root as a string. If not supplied,
357    *   the application root will be computed.
358    *
359    * @return string
360    *   The path of the matching directory.
361    *
362    * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
363    *   In case the host name in the request is invalid.
364    *
365    * @see \Drupal\Core\DrupalKernelInterface::getSitePath()
366    * @see \Drupal\Core\DrupalKernelInterface::setSitePath()
367    * @see default.settings.php
368    * @see example.sites.php
369    */
370   public static function findSitePath(Request $request, $require_settings = TRUE, $app_root = NULL) {
371     if (static::validateHostname($request) === FALSE) {
372       throw new BadRequestHttpException();
373     }
374
375     if ($app_root === NULL) {
376       $app_root = static::guessApplicationRoot();
377     }
378
379     // Check for a simpletest override.
380     if ($test_prefix = drupal_valid_test_ua()) {
381       $test_db = new TestDatabase($test_prefix);
382       return $test_db->getTestSitePath();
383     }
384
385     // Determine whether multi-site functionality is enabled.
386     if (!file_exists($app_root . '/sites/sites.php')) {
387       return 'sites/default';
388     }
389
390     // Otherwise, use find the site path using the request.
391     $script_name = $request->server->get('SCRIPT_NAME');
392     if (!$script_name) {
393       $script_name = $request->server->get('SCRIPT_FILENAME');
394     }
395     $http_host = $request->getHttpHost();
396
397     $sites = [];
398     include $app_root . '/sites/sites.php';
399
400     $uri = explode('/', $script_name);
401     $server = explode('.', implode('.', array_reverse(explode(':', rtrim($http_host, '.')))));
402     for ($i = count($uri) - 1; $i > 0; $i--) {
403       for ($j = count($server); $j > 0; $j--) {
404         $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
405         if (isset($sites[$dir]) && file_exists($app_root . '/sites/' . $sites[$dir])) {
406           $dir = $sites[$dir];
407         }
408         if (file_exists($app_root . '/sites/' . $dir . '/settings.php') || (!$require_settings && file_exists($app_root . '/sites/' . $dir))) {
409           return "sites/$dir";
410         }
411       }
412     }
413     return 'sites/default';
414   }
415
416   /**
417    * {@inheritdoc}
418    */
419   public function setSitePath($path) {
420     if ($this->booted && $path !== $this->sitePath) {
421       throw new \LogicException('Site path cannot be changed after calling boot()');
422     }
423     $this->sitePath = $path;
424   }
425
426   /**
427    * {@inheritdoc}
428    */
429   public function getSitePath() {
430     return $this->sitePath;
431   }
432
433   /**
434    * {@inheritdoc}
435    */
436   public function getAppRoot() {
437     return $this->root;
438   }
439
440   /**
441    * {@inheritdoc}
442    */
443   public function boot() {
444     if ($this->booted) {
445       return $this;
446     }
447
448     // Ensure that findSitePath is set.
449     if (!$this->sitePath) {
450       throw new \Exception('Kernel does not have site path set before calling boot()');
451     }
452
453     // Initialize the FileCacheFactory component. We have to do it here instead
454     // of in \Drupal\Component\FileCache\FileCacheFactory because we can not use
455     // the Settings object in a component.
456     $configuration = Settings::get('file_cache');
457
458     // Provide a default configuration, if not set.
459     if (!isset($configuration['default'])) {
460       // @todo Use extension_loaded('apcu') for non-testbot
461       //  https://www.drupal.org/node/2447753.
462       if (function_exists('apcu_fetch')) {
463         $configuration['default']['cache_backend_class'] = '\Drupal\Component\FileCache\ApcuFileCacheBackend';
464       }
465     }
466     FileCacheFactory::setConfiguration($configuration);
467     FileCacheFactory::setPrefix(Settings::getApcuPrefix('file_cache', $this->root));
468
469     $this->bootstrapContainer = new $this->bootstrapContainerClass(Settings::get('bootstrap_container_definition', $this->defaultBootstrapContainerDefinition));
470
471     // Initialize the container.
472     $this->initializeContainer();
473
474     $this->booted = TRUE;
475
476     return $this;
477   }
478
479   /**
480    * {@inheritdoc}
481    */
482   public function shutdown() {
483     if (FALSE === $this->booted) {
484       return;
485     }
486     $this->container->get('stream_wrapper_manager')->unregister();
487     $this->booted = FALSE;
488     $this->container = NULL;
489     $this->moduleList = NULL;
490     $this->moduleData = [];
491   }
492
493   /**
494    * {@inheritdoc}
495    */
496   public function getContainer() {
497     return $this->container;
498   }
499
500   /**
501    * {@inheritdoc}
502    */
503   public function setContainer(ContainerInterface $container = NULL) {
504     if (isset($this->container)) {
505       throw new \Exception('The container should not override an existing container.');
506     }
507     if ($this->booted) {
508       throw new \Exception('The container cannot be set after a booted kernel.');
509     }
510
511     $this->container = $container;
512     return $this;
513   }
514
515   /**
516    * {@inheritdoc}
517    */
518   public function getCachedContainerDefinition() {
519     $cache = $this->bootstrapContainer->get('cache.container')->get($this->getContainerCacheKey());
520
521     if ($cache) {
522       return $cache->data;
523     }
524
525     return NULL;
526   }
527
528   /**
529    * {@inheritdoc}
530    */
531   public function loadLegacyIncludes() {
532     require_once $this->root . '/core/includes/common.inc';
533     require_once $this->root . '/core/includes/database.inc';
534     require_once $this->root . '/core/includes/module.inc';
535     require_once $this->root . '/core/includes/theme.inc';
536     require_once $this->root . '/core/includes/pager.inc';
537     require_once $this->root . '/core/includes/menu.inc';
538     require_once $this->root . '/core/includes/tablesort.inc';
539     require_once $this->root . '/core/includes/file.inc';
540     require_once $this->root . '/core/includes/unicode.inc';
541     require_once $this->root . '/core/includes/form.inc';
542     require_once $this->root . '/core/includes/errors.inc';
543     require_once $this->root . '/core/includes/schema.inc';
544     require_once $this->root . '/core/includes/entity.inc';
545   }
546
547   /**
548    * {@inheritdoc}
549    */
550   public function preHandle(Request $request) {
551     // Sanitize the request.
552     $request = RequestSanitizer::sanitize(
553       $request,
554       (array) Settings::get(RequestSanitizer::SANITIZE_WHITELIST, []),
555       (bool) Settings::get(RequestSanitizer::SANITIZE_LOG, FALSE)
556     );
557
558     $this->loadLegacyIncludes();
559
560     // Load all enabled modules.
561     $this->container->get('module_handler')->loadAll();
562
563     // Register stream wrappers.
564     $this->container->get('stream_wrapper_manager')->register();
565
566     // Initialize legacy request globals.
567     $this->initializeRequestGlobals($request);
568
569     // Put the request on the stack.
570     $this->container->get('request_stack')->push($request);
571
572     // Set the allowed protocols.
573     UrlHelper::setAllowedProtocols($this->container->getParameter('filter_protocols'));
574
575     // Override of Symfony's MIME type guesser singleton.
576     MimeTypeGuesser::registerWithSymfonyGuesser($this->container);
577
578     $this->prepared = TRUE;
579   }
580
581   /**
582    * {@inheritdoc}
583    */
584   public function discoverServiceProviders() {
585     $this->serviceYamls = [
586       'app' => [],
587       'site' => [],
588     ];
589     $this->serviceProviderClasses = [
590       'app' => [],
591       'site' => [],
592     ];
593     $this->serviceYamls['app']['core'] = 'core/core.services.yml';
594     $this->serviceProviderClasses['app']['core'] = 'Drupal\Core\CoreServiceProvider';
595
596     // Retrieve enabled modules and register their namespaces.
597     if (!isset($this->moduleList)) {
598       $extensions = $this->getConfigStorage()->read('core.extension');
599       $this->moduleList = isset($extensions['module']) ? $extensions['module'] : [];
600     }
601     $module_filenames = $this->getModuleFileNames();
602     $this->classLoaderAddMultiplePsr4($this->getModuleNamespacesPsr4($module_filenames));
603
604     // Load each module's serviceProvider class.
605     foreach ($module_filenames as $module => $filename) {
606       $camelized = ContainerBuilder::camelize($module);
607       $name = "{$camelized}ServiceProvider";
608       $class = "Drupal\\{$module}\\{$name}";
609       if (class_exists($class)) {
610         $this->serviceProviderClasses['app'][$module] = $class;
611       }
612       $filename = dirname($filename) . "/$module.services.yml";
613       if (file_exists($filename)) {
614         $this->serviceYamls['app'][$module] = $filename;
615       }
616     }
617
618     // Add site-specific service providers.
619     if (!empty($GLOBALS['conf']['container_service_providers'])) {
620       foreach ($GLOBALS['conf']['container_service_providers'] as $class) {
621         if ((is_string($class) && class_exists($class)) || (is_object($class) && ($class instanceof ServiceProviderInterface || $class instanceof ServiceModifierInterface))) {
622           $this->serviceProviderClasses['site'][] = $class;
623         }
624       }
625     }
626     $this->addServiceFiles(Settings::get('container_yamls', []));
627   }
628
629   /**
630    * {@inheritdoc}
631    */
632   public function getServiceProviders($origin) {
633     return $this->serviceProviders[$origin];
634   }
635
636   /**
637    * {@inheritdoc}
638    */
639   public function terminate(Request $request, Response $response) {
640     // Only run terminate() when essential services have been set up properly
641     // by preHandle() before.
642     if (FALSE === $this->prepared) {
643       return;
644     }
645
646     if ($this->getHttpKernel() instanceof TerminableInterface) {
647       $this->getHttpKernel()->terminate($request, $response);
648     }
649   }
650
651   /**
652    * {@inheritdoc}
653    */
654   public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
655     // Ensure sane PHP environment variables.
656     static::bootEnvironment();
657
658     try {
659       $this->initializeSettings($request);
660
661       // Redirect the user to the installation script if Drupal has not been
662       // installed yet (i.e., if no $databases array has been defined in the
663       // settings.php file) and we are not already installing.
664       if (!Database::getConnectionInfo() && !drupal_installation_attempted() && PHP_SAPI !== 'cli') {
665         $response = new RedirectResponse($request->getBasePath() . '/core/install.php', 302, ['Cache-Control' => 'no-cache']);
666       }
667       else {
668         $this->boot();
669         $response = $this->getHttpKernel()->handle($request, $type, $catch);
670       }
671     }
672     catch (\Exception $e) {
673       if ($catch === FALSE) {
674         throw $e;
675       }
676
677       $response = $this->handleException($e, $request, $type);
678     }
679
680     // Adapt response headers to the current request.
681     $response->prepare($request);
682
683     return $response;
684   }
685
686   /**
687    * Converts an exception into a response.
688    *
689    * @param \Exception $e
690    *   An exception
691    * @param \Symfony\Component\HttpFoundation\Request $request
692    *   A Request instance
693    * @param int $type
694    *   The type of the request (one of HttpKernelInterface::MASTER_REQUEST or
695    *   HttpKernelInterface::SUB_REQUEST)
696    *
697    * @return \Symfony\Component\HttpFoundation\Response
698    *   A Response instance
699    *
700    * @throws \Exception
701    *   If the passed in exception cannot be turned into a response.
702    */
703   protected function handleException(\Exception $e, $request, $type) {
704     if ($this->shouldRedirectToInstaller($e, $this->container ? $this->container->get('database') : NULL)) {
705       return new RedirectResponse($request->getBasePath() . '/core/install.php', 302, ['Cache-Control' => 'no-cache']);
706     }
707
708     if ($e instanceof HttpExceptionInterface) {
709       $response = new Response($e->getMessage(), $e->getStatusCode());
710       $response->headers->add($e->getHeaders());
711       return $response;
712     }
713
714     throw $e;
715   }
716
717   /**
718    * {@inheritdoc}
719    */
720   public function prepareLegacyRequest(Request $request) {
721     $this->boot();
722     $this->preHandle($request);
723     // Setup services which are normally initialized from within stack
724     // middleware or during the request kernel event.
725     if (PHP_SAPI !== 'cli') {
726       $request->setSession($this->container->get('session'));
727     }
728     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
729     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
730     $this->container->get('request_stack')->push($request);
731     $this->container->get('router.request_context')->fromRequest($request);
732     return $this;
733   }
734
735   /**
736    * Returns module data on the filesystem.
737    *
738    * @param $module
739    *   The name of the module.
740    *
741    * @return \Drupal\Core\Extension\Extension|bool
742    *   Returns an Extension object if the module is found, FALSE otherwise.
743    */
744   protected function moduleData($module) {
745     if (!$this->moduleData) {
746       // First, find profiles.
747       $listing = new ExtensionDiscovery($this->root);
748       $listing->setProfileDirectories([]);
749       $all_profiles = $listing->scan('profile');
750       $profiles = array_intersect_key($all_profiles, $this->moduleList);
751
752       // If a module is within a profile directory but specifies another
753       // profile for testing, it needs to be found in the parent profile.
754       $settings = $this->getConfigStorage()->read('simpletest.settings');
755       $parent_profile = !empty($settings['parent_profile']) ? $settings['parent_profile'] : NULL;
756       if ($parent_profile && !isset($profiles[$parent_profile])) {
757         // In case both profile directories contain the same extension, the
758         // actual profile always has precedence.
759         $profiles = [$parent_profile => $all_profiles[$parent_profile]] + $profiles;
760       }
761
762       $profile_directories = array_map(function ($profile) {
763         return $profile->getPath();
764       }, $profiles);
765       $listing->setProfileDirectories($profile_directories);
766
767       // Now find modules.
768       $this->moduleData = $profiles + $listing->scan('module');
769     }
770     return isset($this->moduleData[$module]) ? $this->moduleData[$module] : FALSE;
771   }
772
773   /**
774    * Implements Drupal\Core\DrupalKernelInterface::updateModules().
775    *
776    * @todo Remove obsolete $module_list parameter. Only $module_filenames is
777    *   needed.
778    */
779   public function updateModules(array $module_list, array $module_filenames = []) {
780     $pre_existing_module_namespaces = [];
781     if ($this->booted && is_array($this->moduleList)) {
782       $pre_existing_module_namespaces = $this->getModuleNamespacesPsr4($this->getModuleFileNames());
783     }
784     $this->moduleList = $module_list;
785     foreach ($module_filenames as $name => $extension) {
786       $this->moduleData[$name] = $extension;
787     }
788
789     // If we haven't yet booted, we don't need to do anything: the new module
790     // list will take effect when boot() is called. However we set a
791     // flag that the container needs a rebuild, so that a potentially cached
792     // container is not used. If we have already booted, then rebuild the
793     // container in order to refresh the serviceProvider list and container.
794     $this->containerNeedsRebuild = TRUE;
795     if ($this->booted) {
796       // We need to register any new namespaces to a new class loader because
797       // the current class loader might have stored a negative result for a
798       // class that is now available.
799       // @see \Composer\Autoload\ClassLoader::findFile()
800       $new_namespaces = array_diff_key(
801         $this->getModuleNamespacesPsr4($this->getModuleFileNames()),
802         $pre_existing_module_namespaces
803       );
804       if (!empty($new_namespaces)) {
805         $additional_class_loader = new ClassLoader();
806         $this->classLoaderAddMultiplePsr4($new_namespaces, $additional_class_loader);
807         $additional_class_loader->register();
808       }
809
810       $this->initializeContainer();
811     }
812   }
813
814   /**
815    * Returns the container cache key based on the environment.
816    *
817    * The 'environment' consists of:
818    * - The kernel environment string.
819    * - The Drupal version constant.
820    * - The deployment identifier from settings.php. This allows custom
821    *   deployments to force a container rebuild.
822    * - The operating system running PHP. This allows compiler passes to optimize
823    *   services for different operating systems.
824    * - The paths to any additional container YAMLs from settings.php.
825    *
826    * @return string
827    *   The cache key used for the service container.
828    */
829   protected function getContainerCacheKey() {
830     $parts = ['service_container', $this->environment, \Drupal::VERSION, Settings::get('deployment_identifier'), PHP_OS, serialize(Settings::get('container_yamls'))];
831     return implode(':', $parts);
832   }
833
834   /**
835    * Returns the kernel parameters.
836    *
837    * @return array An array of kernel parameters
838    */
839   protected function getKernelParameters() {
840     return [
841       'kernel.environment' => $this->environment,
842     ];
843   }
844
845   /**
846    * Initializes the service container.
847    *
848    * @return \Symfony\Component\DependencyInjection\ContainerInterface
849    */
850   protected function initializeContainer() {
851     $this->containerNeedsDumping = FALSE;
852     $session_started = FALSE;
853     if (isset($this->container)) {
854       // Save the id of the currently logged in user.
855       if ($this->container->initialized('current_user')) {
856         $current_user_id = $this->container->get('current_user')->id();
857       }
858
859       // If there is a session, close and save it.
860       if ($this->container->initialized('session')) {
861         $session = $this->container->get('session');
862         if ($session->isStarted()) {
863           $session_started = TRUE;
864           $session->save();
865         }
866         unset($session);
867       }
868     }
869
870     // If we haven't booted yet but there is a container, then we're asked to
871     // boot the container injected via setContainer().
872     // @see \Drupal\KernelTests\KernelTestBase::setUp()
873     if (isset($this->container) && !$this->booted) {
874       $container = $this->container;
875     }
876
877     // If the module list hasn't already been set in updateModules and we are
878     // not forcing a rebuild, then try and load the container from the cache.
879     if (empty($this->moduleList) && !$this->containerNeedsRebuild) {
880       $container_definition = $this->getCachedContainerDefinition();
881     }
882
883     // If there is no container and no cached container definition, build a new
884     // one from scratch.
885     if (!isset($container) && !isset($container_definition)) {
886       // Building the container creates 1000s of objects. Garbage collection of
887       // these objects is expensive. This appears to be causing random
888       // segmentation faults in PHP 5.6 due to
889       // https://bugs.php.net/bug.php?id=72286. Once the container is rebuilt,
890       // garbage collection is re-enabled.
891       $disable_gc = version_compare(PHP_VERSION, '7', '<') && gc_enabled();
892       if ($disable_gc) {
893         gc_collect_cycles();
894         gc_disable();
895       }
896       $container = $this->compileContainer();
897
898       // Only dump the container if dumping is allowed. This is useful for
899       // KernelTestBase, which never wants to use the real container, but always
900       // the container builder.
901       if ($this->allowDumping) {
902         $dumper = new $this->phpArrayDumperClass($container);
903         $container_definition = $dumper->getArray();
904       }
905       // If garbage collection was disabled prior to rebuilding container,
906       // re-enable it.
907       if ($disable_gc) {
908         gc_enable();
909       }
910     }
911
912     // The container was rebuilt successfully.
913     $this->containerNeedsRebuild = FALSE;
914
915     // Only create a new class if we have a container definition.
916     if (isset($container_definition)) {
917       $class = Settings::get('container_base_class', '\Drupal\Core\DependencyInjection\Container');
918       $container = new $class($container_definition);
919     }
920
921     $this->attachSynthetic($container);
922
923     $this->container = $container;
924     if ($session_started) {
925       $this->container->get('session')->start();
926     }
927
928     // The request stack is preserved across container rebuilds. Reinject the
929     // new session into the master request if one was present before.
930     if (($request_stack = $this->container->get('request_stack', ContainerInterface::NULL_ON_INVALID_REFERENCE))) {
931       if ($request = $request_stack->getMasterRequest()) {
932         $subrequest = TRUE;
933         if ($request->hasSession()) {
934           $request->setSession($this->container->get('session'));
935         }
936       }
937     }
938
939     if (!empty($current_user_id)) {
940       $this->container->get('current_user')->setInitialAccountId($current_user_id);
941     }
942
943     \Drupal::setContainer($this->container);
944
945     // Allow other parts of the codebase to react on container initialization in
946     // subrequest.
947     if (!empty($subrequest)) {
948       $this->container->get('event_dispatcher')->dispatch(self::CONTAINER_INITIALIZE_SUBREQUEST_FINISHED);
949     }
950
951     // If needs dumping flag was set, dump the container.
952     if ($this->containerNeedsDumping && !$this->cacheDrupalContainer($container_definition)) {
953       $this->container->get('logger.factory')->get('DrupalKernel')->error('Container cannot be saved to cache.');
954     }
955
956     return $this->container;
957   }
958
959   /**
960    * Setup a consistent PHP environment.
961    *
962    * This method sets PHP environment options we want to be sure are set
963    * correctly for security or just saneness.
964    *
965    * @param string $app_root
966    *   (optional) The path to the application root as a string. If not supplied,
967    *   the application root will be computed.
968    */
969   public static function bootEnvironment($app_root = NULL) {
970     if (static::$isEnvironmentInitialized) {
971       return;
972     }
973
974     // Determine the application root if it's not supplied.
975     if ($app_root === NULL) {
976       $app_root = static::guessApplicationRoot();
977     }
978
979     // Include our bootstrap file.
980     require_once $app_root . '/core/includes/bootstrap.inc';
981
982     // Enforce E_STRICT, but allow users to set levels not part of E_STRICT.
983     error_reporting(E_STRICT | E_ALL);
984
985     // Override PHP settings required for Drupal to work properly.
986     // sites/default/default.settings.php contains more runtime settings.
987     // The .htaccess file contains settings that cannot be changed at runtime.
988
989     if (PHP_SAPI !== 'cli') {
990       // Use session cookies, not transparent sessions that puts the session id
991       // in the query string.
992       ini_set('session.use_cookies', '1');
993       ini_set('session.use_only_cookies', '1');
994       ini_set('session.use_trans_sid', '0');
995       // Don't send HTTP headers using PHP's session handler.
996       // Send an empty string to disable the cache limiter.
997       ini_set('session.cache_limiter', '');
998       // Use httponly session cookies.
999       ini_set('session.cookie_httponly', '1');
1000     }
1001
1002     // Set sane locale settings, to ensure consistent string, dates, times and
1003     // numbers handling.
1004     setlocale(LC_ALL, 'C');
1005
1006     // Set appropriate configuration for multi-byte strings.
1007     mb_internal_encoding('utf-8');
1008     mb_language('uni');
1009
1010     // Indicate that code is operating in a test child site.
1011     if (!defined('DRUPAL_TEST_IN_CHILD_SITE')) {
1012       if ($test_prefix = drupal_valid_test_ua()) {
1013         $test_db = new TestDatabase($test_prefix);
1014         // Only code that interfaces directly with tests should rely on this
1015         // constant; e.g., the error/exception handler conditionally adds further
1016         // error information into HTTP response headers that are consumed by
1017         // Simpletest's internal browser.
1018         define('DRUPAL_TEST_IN_CHILD_SITE', TRUE);
1019
1020         // Web tests are to be conducted with runtime assertions active.
1021         assert_options(ASSERT_ACTIVE, TRUE);
1022         // Now synchronize PHP 5 and 7's handling of assertions as much as
1023         // possible.
1024         Handle::register();
1025
1026         // Log fatal errors to the test site directory.
1027         ini_set('log_errors', 1);
1028         ini_set('error_log', $app_root . '/' . $test_db->getTestSitePath() . '/error.log');
1029
1030         // Ensure that a rewritten settings.php is used if opcache is on.
1031         ini_set('opcache.validate_timestamps', 'on');
1032         ini_set('opcache.revalidate_freq', 0);
1033       }
1034       else {
1035         // Ensure that no other code defines this.
1036         define('DRUPAL_TEST_IN_CHILD_SITE', FALSE);
1037       }
1038     }
1039
1040     // Set the Drupal custom error handler.
1041     set_error_handler('_drupal_error_handler');
1042     set_exception_handler('_drupal_exception_handler');
1043
1044     static::$isEnvironmentInitialized = TRUE;
1045   }
1046
1047   /**
1048    * Locate site path and initialize settings singleton.
1049    *
1050    * @param \Symfony\Component\HttpFoundation\Request $request
1051    *   The current request.
1052    *
1053    * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
1054    *   In case the host name in the request is not trusted.
1055    */
1056   protected function initializeSettings(Request $request) {
1057     $site_path = static::findSitePath($request);
1058     $this->setSitePath($site_path);
1059     $class_loader_class = get_class($this->classLoader);
1060     Settings::initialize($this->root, $site_path, $this->classLoader);
1061
1062     // Initialize our list of trusted HTTP Host headers to protect against
1063     // header attacks.
1064     $host_patterns = Settings::get('trusted_host_patterns', []);
1065     if (PHP_SAPI !== 'cli' && !empty($host_patterns)) {
1066       if (static::setupTrustedHosts($request, $host_patterns) === FALSE) {
1067         throw new BadRequestHttpException('The provided host name is not valid for this server.');
1068       }
1069     }
1070
1071     // If the class loader is still the same, possibly
1072     // upgrade to an optimized class loader.
1073     if ($class_loader_class == get_class($this->classLoader)
1074         && Settings::get('class_loader_auto_detect', TRUE)) {
1075       $prefix = Settings::getApcuPrefix('class_loader', $this->root);
1076       $loader = NULL;
1077
1078       // We autodetect one of the following three optimized classloaders, if
1079       // their underlying extension exists.
1080       if (function_exists('apcu_fetch')) {
1081         $loader = new ApcClassLoader($prefix, $this->classLoader);
1082       }
1083       elseif (extension_loaded('wincache')) {
1084         $loader = new WinCacheClassLoader($prefix, $this->classLoader);
1085       }
1086       elseif (extension_loaded('xcache')) {
1087         $loader = new XcacheClassLoader($prefix, $this->classLoader);
1088       }
1089       if (!empty($loader)) {
1090         $this->classLoader->unregister();
1091         // The optimized classloader might be persistent and store cache misses.
1092         // For example, once a cache miss is stored in APCu clearing it on a
1093         // specific web-head will not clear any other web-heads. Therefore
1094         // fallback to the composer class loader that only statically caches
1095         // misses.
1096         $old_loader = $this->classLoader;
1097         $this->classLoader = $loader;
1098         // Our class loaders are prepended to ensure they come first like the
1099         // class loader they are replacing.
1100         $old_loader->register(TRUE);
1101         $loader->register(TRUE);
1102       }
1103     }
1104   }
1105
1106   /**
1107    * Bootstraps the legacy global request variables.
1108    *
1109    * @param \Symfony\Component\HttpFoundation\Request $request
1110    *   The current request.
1111    *
1112    * @todo D8: Eliminate this entirely in favor of Request object.
1113    */
1114   protected function initializeRequestGlobals(Request $request) {
1115     global $base_url;
1116     // Set and derived from $base_url by this function.
1117     global $base_path, $base_root;
1118     global $base_secure_url, $base_insecure_url;
1119
1120     // Create base URL.
1121     $base_root = $request->getSchemeAndHttpHost();
1122     $base_url = $base_root;
1123
1124     // For a request URI of '/index.php/foo', $_SERVER['SCRIPT_NAME'] is
1125     // '/index.php', whereas $_SERVER['PHP_SELF'] is '/index.php/foo'.
1126     if ($dir = rtrim(dirname($request->server->get('SCRIPT_NAME')), '\/')) {
1127       // Remove "core" directory if present, allowing install.php,
1128       // authorize.php, and others to auto-detect a base path.
1129       $core_position = strrpos($dir, '/core');
1130       if ($core_position !== FALSE && strlen($dir) - 5 == $core_position) {
1131         $base_path = substr($dir, 0, $core_position);
1132       }
1133       else {
1134         $base_path = $dir;
1135       }
1136       $base_url .= $base_path;
1137       $base_path .= '/';
1138     }
1139     else {
1140       $base_path = '/';
1141     }
1142     $base_secure_url = str_replace('http://', 'https://', $base_url);
1143     $base_insecure_url = str_replace('https://', 'http://', $base_url);
1144   }
1145
1146   /**
1147    * Returns service instances to persist from an old container to a new one.
1148    */
1149   protected function getServicesToPersist(ContainerInterface $container) {
1150     $persist = [];
1151     foreach ($container->getParameter('persist_ids') as $id) {
1152       // It's pointless to persist services not yet initialized.
1153       if ($container->initialized($id)) {
1154         $persist[$id] = $container->get($id);
1155       }
1156     }
1157     return $persist;
1158   }
1159
1160   /**
1161    * Moves persistent service instances into a new container.
1162    */
1163   protected function persistServices(ContainerInterface $container, array $persist) {
1164     foreach ($persist as $id => $object) {
1165       // Do not override services already set() on the new container, for
1166       // example 'service_container'.
1167       if (!$container->initialized($id)) {
1168         $container->set($id, $object);
1169       }
1170     }
1171   }
1172
1173   /**
1174    * {@inheritdoc}
1175    */
1176   public function rebuildContainer() {
1177     // Empty module properties and for them to be reloaded from scratch.
1178     $this->moduleList = NULL;
1179     $this->moduleData = [];
1180     $this->containerNeedsRebuild = TRUE;
1181     return $this->initializeContainer();
1182   }
1183
1184   /**
1185    * {@inheritdoc}
1186    */
1187   public function invalidateContainer() {
1188     // An invalidated container needs a rebuild.
1189     $this->containerNeedsRebuild = TRUE;
1190
1191     // If we have not yet booted, settings or bootstrap services might not yet
1192     // be available. In that case the container will not be loaded from cache
1193     // due to the above setting when the Kernel is booted.
1194     if (!$this->booted) {
1195       return;
1196     }
1197
1198     // Also remove the container definition from the cache backend.
1199     $this->bootstrapContainer->get('cache.container')->deleteAll();
1200   }
1201
1202   /**
1203    * Attach synthetic values on to kernel.
1204    *
1205    * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
1206    *   Container object
1207    *
1208    * @return \Symfony\Component\DependencyInjection\ContainerInterface
1209    */
1210   protected function attachSynthetic(ContainerInterface $container) {
1211     $persist = [];
1212     if (isset($this->container)) {
1213       $persist = $this->getServicesToPersist($this->container);
1214     }
1215     $this->persistServices($container, $persist);
1216
1217     // All namespaces must be registered before we attempt to use any service
1218     // from the container.
1219     $this->classLoaderAddMultiplePsr4($container->getParameter('container.namespaces'));
1220
1221     $container->set('kernel', $this);
1222
1223     // Set the class loader which was registered as a synthetic service.
1224     $container->set('class_loader', $this->classLoader);
1225     return $container;
1226   }
1227
1228   /**
1229    * Compiles a new service container.
1230    *
1231    * @return \Drupal\Core\DependencyInjection\ContainerBuilder The compiled service container
1232    */
1233   protected function compileContainer() {
1234     // We are forcing a container build so it is reasonable to assume that the
1235     // calling method knows something about the system has changed requiring the
1236     // container to be dumped to the filesystem.
1237     if ($this->allowDumping) {
1238       $this->containerNeedsDumping = TRUE;
1239     }
1240
1241     $this->initializeServiceProviders();
1242     $container = $this->getContainerBuilder();
1243     $container->set('kernel', $this);
1244     $container->setParameter('container.modules', $this->getModulesParameter());
1245     $container->setParameter('install_profile', $this->getInstallProfile());
1246
1247     // Get a list of namespaces and put it onto the container.
1248     $namespaces = $this->getModuleNamespacesPsr4($this->getModuleFileNames());
1249     // Add all components in \Drupal\Core and \Drupal\Component that have one of
1250     // the following directories:
1251     // - Element
1252     // - Entity
1253     // - Plugin
1254     foreach (['Core', 'Component'] as $parent_directory) {
1255       $path = 'core/lib/Drupal/' . $parent_directory;
1256       $parent_namespace = 'Drupal\\' . $parent_directory;
1257       foreach (new \DirectoryIterator($this->root . '/' . $path) as $component) {
1258         /** @var $component \DirectoryIterator */
1259         $pathname = $component->getPathname();
1260         if (!$component->isDot() && $component->isDir() && (
1261           is_dir($pathname . '/Plugin') ||
1262           is_dir($pathname . '/Entity') ||
1263           is_dir($pathname . '/Element')
1264         )) {
1265           $namespaces[$parent_namespace . '\\' . $component->getFilename()] = $path . '/' . $component->getFilename();
1266         }
1267       }
1268     }
1269     $container->setParameter('container.namespaces', $namespaces);
1270
1271     // Store the default language values on the container. This is so that the
1272     // default language can be configured using the configuration factory. This
1273     // avoids the circular dependencies that would created by
1274     // \Drupal\language\LanguageServiceProvider::alter() and allows the default
1275     // language to not be English in the installer.
1276     $default_language_values = Language::$defaultValues;
1277     if ($system = $this->getConfigStorage()->read('system.site')) {
1278       if ($default_language_values['id'] != $system['langcode']) {
1279         $default_language_values = ['id' => $system['langcode']];
1280       }
1281     }
1282     $container->setParameter('language.default_values', $default_language_values);
1283
1284     // Register synthetic services.
1285     $container->register('class_loader')->setSynthetic(TRUE);
1286     $container->register('kernel', 'Symfony\Component\HttpKernel\KernelInterface')->setSynthetic(TRUE);
1287     $container->register('service_container', 'Symfony\Component\DependencyInjection\ContainerInterface')->setSynthetic(TRUE);
1288
1289     // Register application services.
1290     $yaml_loader = new YamlFileLoader($container);
1291     foreach ($this->serviceYamls['app'] as $filename) {
1292       $yaml_loader->load($filename);
1293     }
1294     foreach ($this->serviceProviders['app'] as $provider) {
1295       if ($provider instanceof ServiceProviderInterface) {
1296         $provider->register($container);
1297       }
1298     }
1299     // Register site-specific service overrides.
1300     foreach ($this->serviceYamls['site'] as $filename) {
1301       $yaml_loader->load($filename);
1302     }
1303     foreach ($this->serviceProviders['site'] as $provider) {
1304       if ($provider instanceof ServiceProviderInterface) {
1305         $provider->register($container);
1306       }
1307     }
1308
1309     // Identify all services whose instances should be persisted when rebuilding
1310     // the container during the lifetime of the kernel (e.g., during a kernel
1311     // reboot). Include synthetic services, because by definition, they cannot
1312     // be automatically reinstantiated. Also include services tagged to persist.
1313     $persist_ids = [];
1314     foreach ($container->getDefinitions() as $id => $definition) {
1315       // It does not make sense to persist the container itself, exclude it.
1316       if ($id !== 'service_container' && ($definition->isSynthetic() || $definition->getTag('persist'))) {
1317         $persist_ids[] = $id;
1318       }
1319     }
1320     $container->setParameter('persist_ids', $persist_ids);
1321
1322     $container->compile();
1323     return $container;
1324   }
1325
1326   /**
1327    * Registers all service providers to the kernel.
1328    *
1329    * @throws \LogicException
1330    */
1331   protected function initializeServiceProviders() {
1332     $this->discoverServiceProviders();
1333     $this->serviceProviders = [
1334       'app' => [],
1335       'site' => [],
1336     ];
1337     foreach ($this->serviceProviderClasses as $origin => $classes) {
1338       foreach ($classes as $name => $class) {
1339         if (!is_object($class)) {
1340           $this->serviceProviders[$origin][$name] = new $class();
1341         }
1342         else {
1343           $this->serviceProviders[$origin][$name] = $class;
1344         }
1345       }
1346     }
1347   }
1348
1349   /**
1350    * Gets a new ContainerBuilder instance used to build the service container.
1351    *
1352    * @return \Drupal\Core\DependencyInjection\ContainerBuilder
1353    */
1354   protected function getContainerBuilder() {
1355     return new ContainerBuilder(new ParameterBag($this->getKernelParameters()));
1356   }
1357
1358   /**
1359    * Stores the container definition in a cache.
1360    *
1361    * @param array $container_definition
1362    *   The container definition to cache.
1363    *
1364    * @return bool
1365    *   TRUE if the container was successfully cached.
1366    */
1367   protected function cacheDrupalContainer(array $container_definition) {
1368     $saved = TRUE;
1369     try {
1370       $this->bootstrapContainer->get('cache.container')->set($this->getContainerCacheKey(), $container_definition);
1371     }
1372     catch (\Exception $e) {
1373       // There is no way to get from the Cache API if the cache set was
1374       // successful or not, hence an Exception is caught and the caller informed
1375       // about the error condition.
1376       $saved = FALSE;
1377     }
1378
1379     return $saved;
1380   }
1381
1382   /**
1383    * Gets a http kernel from the container
1384    *
1385    * @return \Symfony\Component\HttpKernel\HttpKernelInterface
1386    */
1387   protected function getHttpKernel() {
1388     return $this->container->get('http_kernel');
1389   }
1390
1391   /**
1392    * Returns the active configuration storage to use during building the container.
1393    *
1394    * @return \Drupal\Core\Config\StorageInterface
1395    */
1396   protected function getConfigStorage() {
1397     if (!isset($this->configStorage)) {
1398       // The active configuration storage may not exist yet; e.g., in the early
1399       // installer. Catch the exception thrown by config_get_config_directory().
1400       try {
1401         $this->configStorage = BootstrapConfigStorageFactory::get($this->classLoader);
1402       }
1403       catch (\Exception $e) {
1404         $this->configStorage = new NullStorage();
1405       }
1406     }
1407     return $this->configStorage;
1408   }
1409
1410   /**
1411    * Returns an array of Extension class parameters for all enabled modules.
1412    *
1413    * @return array
1414    */
1415   protected function getModulesParameter() {
1416     $extensions = [];
1417     foreach ($this->moduleList as $name => $weight) {
1418       if ($data = $this->moduleData($name)) {
1419         $extensions[$name] = [
1420           'type' => $data->getType(),
1421           'pathname' => $data->getPathname(),
1422           'filename' => $data->getExtensionFilename(),
1423         ];
1424       }
1425     }
1426     return $extensions;
1427   }
1428
1429   /**
1430    * Gets the file name for each enabled module.
1431    *
1432    * @return array
1433    *   Array where each key is a module name, and each value is a path to the
1434    *   respective *.info.yml file.
1435    */
1436   protected function getModuleFileNames() {
1437     $filenames = [];
1438     foreach ($this->moduleList as $module => $weight) {
1439       if ($data = $this->moduleData($module)) {
1440         $filenames[$module] = $data->getPathname();
1441       }
1442     }
1443     return $filenames;
1444   }
1445
1446   /**
1447    * Gets the PSR-4 base directories for module namespaces.
1448    *
1449    * @param string[] $module_file_names
1450    *   Array where each key is a module name, and each value is a path to the
1451    *   respective *.info.yml file.
1452    *
1453    * @return string[]
1454    *   Array where each key is a module namespace like 'Drupal\system', and each
1455    *   value is the PSR-4 base directory associated with the module namespace.
1456    */
1457   protected function getModuleNamespacesPsr4($module_file_names) {
1458     $namespaces = [];
1459     foreach ($module_file_names as $module => $filename) {
1460       $namespaces["Drupal\\$module"] = dirname($filename) . '/src';
1461     }
1462     return $namespaces;
1463   }
1464
1465   /**
1466    * Registers a list of namespaces with PSR-4 directories for class loading.
1467    *
1468    * @param array $namespaces
1469    *   Array where each key is a namespace like 'Drupal\system', and each value
1470    *   is either a PSR-4 base directory, or an array of PSR-4 base directories
1471    *   associated with this namespace.
1472    * @param object $class_loader
1473    *   The class loader. Normally \Composer\Autoload\ClassLoader, as included by
1474    *   the front controller, but may also be decorated; e.g.,
1475    *   \Symfony\Component\ClassLoader\ApcClassLoader.
1476    */
1477   protected function classLoaderAddMultiplePsr4(array $namespaces = [], $class_loader = NULL) {
1478     if ($class_loader === NULL) {
1479       $class_loader = $this->classLoader;
1480     }
1481     foreach ($namespaces as $prefix => $paths) {
1482       if (is_array($paths)) {
1483         foreach ($paths as $key => $value) {
1484           $paths[$key] = $this->root . '/' . $value;
1485         }
1486       }
1487       elseif (is_string($paths)) {
1488         $paths = $this->root . '/' . $paths;
1489       }
1490       $class_loader->addPsr4($prefix . '\\', $paths);
1491     }
1492   }
1493
1494   /**
1495    * Validates a hostname length.
1496    *
1497    * @param string $host
1498    *   A hostname.
1499    *
1500    * @return bool
1501    *   TRUE if the length is appropriate, or FALSE otherwise.
1502    */
1503   protected static function validateHostnameLength($host) {
1504     // Limit the length of the host name to 1000 bytes to prevent DoS attacks
1505     // with long host names.
1506     return strlen($host) <= 1000
1507     // Limit the number of subdomains and port separators to prevent DoS attacks
1508     // in findSitePath().
1509     && substr_count($host, '.') <= 100
1510     && substr_count($host, ':') <= 100;
1511   }
1512
1513   /**
1514    * Validates the hostname supplied from the HTTP request.
1515    *
1516    * @param \Symfony\Component\HttpFoundation\Request $request
1517    *   The request object
1518    *
1519    * @return bool
1520    *   TRUE if the hostname is valid, or FALSE otherwise.
1521    */
1522   public static function validateHostname(Request $request) {
1523     // $request->getHost() can throw an UnexpectedValueException if it
1524     // detects a bad hostname, but it does not validate the length.
1525     try {
1526       $http_host = $request->getHost();
1527     }
1528     catch (\UnexpectedValueException $e) {
1529       return FALSE;
1530     }
1531
1532     if (static::validateHostnameLength($http_host) === FALSE) {
1533       return FALSE;
1534     }
1535
1536     return TRUE;
1537   }
1538
1539   /**
1540    * Sets up the lists of trusted HTTP Host headers.
1541    *
1542    * Since the HTTP Host header can be set by the user making the request, it
1543    * is possible to create an attack vectors against a site by overriding this.
1544    * Symfony provides a mechanism for creating a list of trusted Host values.
1545    *
1546    * Host patterns (as regular expressions) can be configured through
1547    * settings.php for multisite installations, sites using ServerAlias without
1548    * canonical redirection, or configurations where the site responds to default
1549    * requests. For example,
1550    *
1551    * @code
1552    * $settings['trusted_host_patterns'] = array(
1553    *   '^example\.com$',
1554    *   '^*.example\.com$',
1555    * );
1556    * @endcode
1557    *
1558    * @param \Symfony\Component\HttpFoundation\Request $request
1559    *   The request object.
1560    * @param array $host_patterns
1561    *   The array of trusted host patterns.
1562    *
1563    * @return bool
1564    *   TRUE if the Host header is trusted, FALSE otherwise.
1565    *
1566    * @see https://www.drupal.org/node/1992030
1567    * @see \Drupal\Core\Http\TrustedHostsRequestFactory
1568    */
1569   protected static function setupTrustedHosts(Request $request, $host_patterns) {
1570     $request->setTrustedHosts($host_patterns);
1571
1572     // Get the host, which will validate the current request.
1573     try {
1574       $host = $request->getHost();
1575
1576       // Fake requests created through Request::create() without passing in the
1577       // server variables from the main request have a default host of
1578       // 'localhost'. If 'localhost' does not match any of the trusted host
1579       // patterns these fake requests would fail the host verification. Instead,
1580       // TrustedHostsRequestFactory makes sure to pass in the server variables
1581       // from the main request.
1582       $request_factory = new TrustedHostsRequestFactory($host);
1583       Request::setFactory([$request_factory, 'createRequest']);
1584
1585     }
1586     catch (\UnexpectedValueException $e) {
1587       return FALSE;
1588     }
1589
1590     return TRUE;
1591   }
1592
1593   /**
1594    * Add service files.
1595    *
1596    * @param string[] $service_yamls
1597    *   A list of service files.
1598    */
1599   protected function addServiceFiles(array $service_yamls) {
1600     $this->serviceYamls['site'] = array_filter($service_yamls, 'file_exists');
1601   }
1602
1603   /**
1604    * Gets the active install profile.
1605    *
1606    * @return string|null
1607    *   The name of the any active install profile or distribution.
1608    */
1609   protected function getInstallProfile() {
1610     $config = $this->getConfigStorage()->read('core.extension');
1611     if (isset($config['profile'])) {
1612       $install_profile = $config['profile'];
1613     }
1614     // @todo https://www.drupal.org/node/2831065 remove the BC layer.
1615     else {
1616       // If system_update_8300() has not yet run fallback to using settings.
1617       $settings = Settings::getAll();
1618       $install_profile = isset($settings['install_profile']) ? $settings['install_profile'] : NULL;
1619     }
1620
1621     // Normalize an empty string to a NULL value.
1622     return empty($install_profile) ? NULL : $install_profile;
1623   }
1624
1625 }