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