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