5 use Composer\Autoload\ClassLoader;
6 use Drupal\Component\Assertion\Handle;
7 use Drupal\Component\FileCache\FileCacheFactory;
8 use Drupal\Component\Utility\UrlHelper;
9 use Drupal\Core\Cache\DatabaseBackend;
10 use Drupal\Core\Config\BootstrapConfigStorageFactory;
11 use Drupal\Core\Config\NullStorage;
12 use Drupal\Core\Database\Database;
13 use Drupal\Core\DependencyInjection\ContainerBuilder;
14 use Drupal\Core\DependencyInjection\ServiceModifierInterface;
15 use Drupal\Core\DependencyInjection\ServiceProviderInterface;
16 use Drupal\Core\DependencyInjection\YamlFileLoader;
17 use Drupal\Core\Extension\ExtensionDiscovery;
18 use Drupal\Core\File\MimeType\MimeTypeGuesser;
19 use Drupal\Core\Http\TrustedHostsRequestFactory;
20 use Drupal\Core\Installer\InstallerRedirectTrait;
21 use Drupal\Core\Language\Language;
22 use Drupal\Core\Security\RequestSanitizer;
23 use Drupal\Core\Site\Settings;
24 use Drupal\Core\Test\TestDatabase;
25 use Symfony\Cmf\Component\Routing\RouteObjectInterface;
26 use Symfony\Component\ClassLoader\ApcClassLoader;
27 use Symfony\Component\ClassLoader\WinCacheClassLoader;
28 use Symfony\Component\ClassLoader\XcacheClassLoader;
29 use Symfony\Component\DependencyInjection\ContainerInterface;
30 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
31 use Symfony\Component\HttpFoundation\RedirectResponse;
32 use Symfony\Component\HttpFoundation\Request;
33 use Symfony\Component\HttpFoundation\Response;
34 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
35 use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
36 use Symfony\Component\HttpKernel\TerminableInterface;
37 use Symfony\Component\Routing\Route;
40 * The DrupalKernel class is the core of Drupal itself.
42 * This class is responsible for building the Dependency Injection Container and
43 * also deals with the registration of service providers. It allows registered
44 * service providers to add their services to the container. Core provides the
45 * CoreServiceProvider, which, in addition to registering any core services that
46 * cannot be registered in the core.services.yaml file, adds any compiler passes
47 * needed by core, e.g. for processing tagged services. Each module can add its
48 * own service provider, i.e. a class implementing
49 * Drupal\Core\DependencyInjection\ServiceProvider, to register services to the
50 * container, or modify existing services.
52 class DrupalKernel implements DrupalKernelInterface, TerminableInterface {
53 use InstallerRedirectTrait;
56 * Holds the class used for dumping the container to a PHP array.
58 * In combination with swapping the container class this is useful to e.g.
59 * dump to the human-readable PHP array format to debug the container
60 * definition in an easier way.
64 protected $phpArrayDumperClass = '\Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper';
67 * Holds the default bootstrap container definition.
71 protected $defaultBootstrapContainerDefinition = [
75 'class' => 'Drupal\Core\Database\Connection',
76 'factory' => 'Drupal\Core\Database\Database::getConnection',
77 'arguments' => ['default'],
79 'cache.container' => [
80 'class' => 'Drupal\Core\Cache\DatabaseBackend',
81 'arguments' => ['@database', '@cache_tags_provider.container', 'container', DatabaseBackend::MAXIMUM_NONE],
83 'cache_tags_provider.container' => [
84 'class' => 'Drupal\Core\Cache\DatabaseCacheTagsChecksum',
85 'arguments' => ['@database'],
91 * Holds the class used for instantiating the bootstrap container.
95 protected $bootstrapContainerClass = '\Drupal\Component\DependencyInjection\PhpArrayContainer';
98 * Holds the bootstrap container.
100 * @var \Symfony\Component\DependencyInjection\ContainerInterface
102 protected $bootstrapContainer;
105 * Holds the container instance.
107 * @var \Symfony\Component\DependencyInjection\ContainerInterface
109 protected $container;
112 * The environment, e.g. 'testing', 'install'.
116 protected $environment;
119 * Whether the kernel has been booted.
123 protected $booted = FALSE;
126 * Whether essential services have been set up properly by preHandle().
130 protected $prepared = FALSE;
133 * Holds the list of enabled modules.
136 * An associative array whose keys are module names and whose values are
139 protected $moduleList;
142 * List of available modules and installation profiles.
144 * @var \Drupal\Core\Extension\Extension[]
146 protected $moduleData = [];
149 * The class loader object.
151 * @var \Composer\Autoload\ClassLoader
153 protected $classLoader;
156 * Config storage object used for reading enabled modules configuration.
158 * @var \Drupal\Core\Config\StorageInterface
160 protected $configStorage;
163 * Whether the container can be dumped.
167 protected $allowDumping;
170 * Whether the container needs to be rebuilt the next time it is initialized.
174 protected $containerNeedsRebuild = FALSE;
177 * Whether the container needs to be dumped once booting is complete.
181 protected $containerNeedsDumping;
184 * List of discovered services.yml pathnames.
186 * This is a nested array whose top-level keys are 'app' and 'site', denoting
187 * the origin of a service provider. Site-specific providers have to be
188 * collected separately, because they need to be processed last, so as to be
189 * able to override services from application service providers.
193 protected $serviceYamls;
196 * List of discovered service provider class names or objects.
198 * This is a nested array whose top-level keys are 'app' and 'site', denoting
199 * the origin of a service provider. Site-specific providers have to be
200 * collected separately, because they need to be processed last, so as to be
201 * able to override services from application service providers.
203 * Allowing objects is for example used to allow
204 * \Drupal\KernelTests\KernelTestBase to register itself as service provider.
208 protected $serviceProviderClasses;
211 * List of instantiated service provider classes.
213 * @see \Drupal\Core\DrupalKernel::$serviceProviderClasses
217 protected $serviceProviders;
220 * Whether the PHP environment has been initialized.
222 * This legacy phase can only be booted once because it sets session INI
223 * settings. If a session has already been started, re-generating these
224 * settings would break the session.
228 protected static $isEnvironmentInitialized = FALSE;
231 * The site directory.
245 * Create a DrupalKernel object from a request.
247 * @param \Symfony\Component\HttpFoundation\Request $request
249 * @param $class_loader
250 * The class loader. Normally Composer's ClassLoader, as included by the
251 * front controller, but may also be decorated; e.g.,
252 * \Symfony\Component\ClassLoader\ApcClassLoader.
253 * @param string $environment
254 * String indicating the environment, e.g. 'prod' or 'dev'.
255 * @param bool $allow_dumping
256 * (optional) FALSE to stop the container from being written to or read
257 * from disk. Defaults to TRUE.
258 * @param string $app_root
259 * (optional) The path to the application root as a string. If not supplied,
260 * the application root will be computed.
264 * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
265 * In case the host name in the request is not trusted.
267 public static function createFromRequest(Request $request, $class_loader, $environment, $allow_dumping = TRUE, $app_root = NULL) {
268 $kernel = new static($environment, $class_loader, $allow_dumping, $app_root);
269 static::bootEnvironment($app_root);
270 $kernel->initializeSettings($request);
275 * Constructs a DrupalKernel object.
277 * @param string $environment
278 * String indicating the environment, e.g. 'prod' or 'dev'.
279 * @param $class_loader
280 * The class loader. Normally \Composer\Autoload\ClassLoader, as included by
281 * the front controller, but may also be decorated; e.g.,
282 * \Symfony\Component\ClassLoader\ApcClassLoader.
283 * @param bool $allow_dumping
284 * (optional) FALSE to stop the container from being written to or read
285 * from disk. Defaults to TRUE.
286 * @param string $app_root
287 * (optional) The path to the application root as a string. If not supplied,
288 * the application root will be computed.
290 public function __construct($environment, $class_loader, $allow_dumping = TRUE, $app_root = NULL) {
291 $this->environment = $environment;
292 $this->classLoader = $class_loader;
293 $this->allowDumping = $allow_dumping;
294 if ($app_root === NULL) {
295 $app_root = static::guessApplicationRoot();
297 $this->root = $app_root;
301 * Determine the application root directory based on this file's location.
304 * The application root.
306 protected static function guessApplicationRoot() {
307 // Determine the application root by:
308 // - Removing the namespace directories from the path.
309 // - Getting the path to the directory two levels up from the path
310 // determined in the previous step.
311 return dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
315 * Returns the appropriate site directory for a request.
317 * Once the kernel has been created DrupalKernelInterface::getSitePath() is
318 * preferred since it gets the statically cached result of this method.
320 * Site directories contain all site specific code. This includes settings.php
321 * for bootstrap level configuration, file configuration stores, public file
322 * storage and site specific modules and themes.
324 * A file named sites.php must be present in the sites directory for
325 * multisite. If it doesn't exist, then 'sites/default' will be used.
327 * Finds a matching site directory file by stripping the website's hostname
328 * from left to right and pathname from right to left. By default, the
329 * directory must contain a 'settings.php' file for it to match. If the
330 * parameter $require_settings is set to FALSE, then a directory without a
331 * 'settings.php' file will match as well. The first configuration file found
332 * will be used and the remaining ones will be ignored. If no configuration
333 * file is found, returns a default value 'sites/default'. See
334 * default.settings.php for examples on how the URL is converted to a
337 * The sites.php file in the sites directory can define aliases in an
338 * associative array named $sites. The array is written in the format
339 * '<port>.<domain>.<path>' => 'directory'. As an example, to create a
340 * directory alias for https://www.drupal.org:8080/mysite/test whose
341 * configuration file is in sites/example.com, the array should be defined as:
344 * '8080.www.drupal.org.mysite.test' => 'example.com',
348 * @param \Symfony\Component\HttpFoundation\Request $request
349 * The current request.
350 * @param bool $require_settings
351 * Only directories with an existing settings.php file will be recognized.
352 * Defaults to TRUE. During initial installation, this is set to FALSE so
353 * that Drupal can detect a matching directory, then create a new
354 * settings.php file in it.
355 * @param string $app_root
356 * (optional) The path to the application root as a string. If not supplied,
357 * the application root will be computed.
360 * The path of the matching directory.
362 * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
363 * In case the host name in the request is invalid.
365 * @see \Drupal\Core\DrupalKernelInterface::getSitePath()
366 * @see \Drupal\Core\DrupalKernelInterface::setSitePath()
367 * @see default.settings.php
368 * @see example.sites.php
370 public static function findSitePath(Request $request, $require_settings = TRUE, $app_root = NULL) {
371 if (static::validateHostname($request) === FALSE) {
372 throw new BadRequestHttpException();
375 if ($app_root === NULL) {
376 $app_root = static::guessApplicationRoot();
379 // Check for a simpletest override.
380 if ($test_prefix = drupal_valid_test_ua()) {
381 $test_db = new TestDatabase($test_prefix);
382 return $test_db->getTestSitePath();
385 // Determine whether multi-site functionality is enabled.
386 if (!file_exists($app_root . '/sites/sites.php')) {
387 return 'sites/default';
390 // Otherwise, use find the site path using the request.
391 $script_name = $request->server->get('SCRIPT_NAME');
393 $script_name = $request->server->get('SCRIPT_FILENAME');
395 $http_host = $request->getHttpHost();
398 include $app_root . '/sites/sites.php';
400 $uri = explode('/', $script_name);
401 $server = explode('.', implode('.', array_reverse(explode(':', rtrim($http_host, '.')))));
402 for ($i = count($uri) - 1; $i > 0; $i--) {
403 for ($j = count($server); $j > 0; $j--) {
404 $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
405 if (isset($sites[$dir]) && file_exists($app_root . '/sites/' . $sites[$dir])) {
408 if (file_exists($app_root . '/sites/' . $dir . '/settings.php') || (!$require_settings && file_exists($app_root . '/sites/' . $dir))) {
413 return 'sites/default';
419 public function setSitePath($path) {
420 if ($this->booted && $path !== $this->sitePath) {
421 throw new \LogicException('Site path cannot be changed after calling boot()');
423 $this->sitePath = $path;
429 public function getSitePath() {
430 return $this->sitePath;
436 public function getAppRoot() {
443 public function boot() {
448 // Ensure that findSitePath is set.
449 if (!$this->sitePath) {
450 throw new \Exception('Kernel does not have site path set before calling boot()');
453 // Initialize the FileCacheFactory component. We have to do it here instead
454 // of in \Drupal\Component\FileCache\FileCacheFactory because we can not use
455 // the Settings object in a component.
456 $configuration = Settings::get('file_cache');
458 // Provide a default configuration, if not set.
459 if (!isset($configuration['default'])) {
460 // @todo Use extension_loaded('apcu') for non-testbot
461 // https://www.drupal.org/node/2447753.
462 if (function_exists('apcu_fetch')) {
463 $configuration['default']['cache_backend_class'] = '\Drupal\Component\FileCache\ApcuFileCacheBackend';
466 FileCacheFactory::setConfiguration($configuration);
467 FileCacheFactory::setPrefix(Settings::getApcuPrefix('file_cache', $this->root));
469 $this->bootstrapContainer = new $this->bootstrapContainerClass(Settings::get('bootstrap_container_definition', $this->defaultBootstrapContainerDefinition));
471 // Initialize the container.
472 $this->initializeContainer();
474 $this->booted = TRUE;
482 public function shutdown() {
483 if (FALSE === $this->booted) {
486 $this->container->get('stream_wrapper_manager')->unregister();
487 $this->booted = FALSE;
488 $this->container = NULL;
489 $this->moduleList = NULL;
490 $this->moduleData = [];
496 public function getContainer() {
497 return $this->container;
503 public function setContainer(ContainerInterface $container = NULL) {
504 if (isset($this->container)) {
505 throw new \Exception('The container should not override an existing container.');
508 throw new \Exception('The container cannot be set after a booted kernel.');
511 $this->container = $container;
518 public function getCachedContainerDefinition() {
519 $cache = $this->bootstrapContainer->get('cache.container')->get($this->getContainerCacheKey());
531 public function loadLegacyIncludes() {
532 require_once $this->root . '/core/includes/common.inc';
533 require_once $this->root . '/core/includes/database.inc';
534 require_once $this->root . '/core/includes/module.inc';
535 require_once $this->root . '/core/includes/theme.inc';
536 require_once $this->root . '/core/includes/pager.inc';
537 require_once $this->root . '/core/includes/menu.inc';
538 require_once $this->root . '/core/includes/tablesort.inc';
539 require_once $this->root . '/core/includes/file.inc';
540 require_once $this->root . '/core/includes/unicode.inc';
541 require_once $this->root . '/core/includes/form.inc';
542 require_once $this->root . '/core/includes/errors.inc';
543 require_once $this->root . '/core/includes/schema.inc';
544 require_once $this->root . '/core/includes/entity.inc';
550 public function preHandle(Request $request) {
551 // Sanitize the request.
552 $request = RequestSanitizer::sanitize(
554 (array) Settings::get(RequestSanitizer::SANITIZE_WHITELIST, []),
555 (bool) Settings::get(RequestSanitizer::SANITIZE_LOG, FALSE)
558 $this->loadLegacyIncludes();
560 // Load all enabled modules.
561 $this->container->get('module_handler')->loadAll();
563 // Register stream wrappers.
564 $this->container->get('stream_wrapper_manager')->register();
566 // Initialize legacy request globals.
567 $this->initializeRequestGlobals($request);
569 // Put the request on the stack.
570 $this->container->get('request_stack')->push($request);
572 // Set the allowed protocols.
573 UrlHelper::setAllowedProtocols($this->container->getParameter('filter_protocols'));
575 // Override of Symfony's MIME type guesser singleton.
576 MimeTypeGuesser::registerWithSymfonyGuesser($this->container);
578 $this->prepared = TRUE;
584 public function discoverServiceProviders() {
585 $this->serviceYamls = [
589 $this->serviceProviderClasses = [
593 $this->serviceYamls['app']['core'] = 'core/core.services.yml';
594 $this->serviceProviderClasses['app']['core'] = 'Drupal\Core\CoreServiceProvider';
596 // Retrieve enabled modules and register their namespaces.
597 if (!isset($this->moduleList)) {
598 $extensions = $this->getConfigStorage()->read('core.extension');
599 $this->moduleList = isset($extensions['module']) ? $extensions['module'] : [];
601 $module_filenames = $this->getModuleFileNames();
602 $this->classLoaderAddMultiplePsr4($this->getModuleNamespacesPsr4($module_filenames));
604 // Load each module's serviceProvider class.
605 foreach ($module_filenames as $module => $filename) {
606 $camelized = ContainerBuilder::camelize($module);
607 $name = "{$camelized}ServiceProvider";
608 $class = "Drupal\\{$module}\\{$name}";
609 if (class_exists($class)) {
610 $this->serviceProviderClasses['app'][$module] = $class;
612 $filename = dirname($filename) . "/$module.services.yml";
613 if (file_exists($filename)) {
614 $this->serviceYamls['app'][$module] = $filename;
618 // Add site-specific service providers.
619 if (!empty($GLOBALS['conf']['container_service_providers'])) {
620 foreach ($GLOBALS['conf']['container_service_providers'] as $class) {
621 if ((is_string($class) && class_exists($class)) || (is_object($class) && ($class instanceof ServiceProviderInterface || $class instanceof ServiceModifierInterface))) {
622 $this->serviceProviderClasses['site'][] = $class;
626 $this->addServiceFiles(Settings::get('container_yamls', []));
632 public function getServiceProviders($origin) {
633 return $this->serviceProviders[$origin];
639 public function terminate(Request $request, Response $response) {
640 // Only run terminate() when essential services have been set up properly
641 // by preHandle() before.
642 if (FALSE === $this->prepared) {
646 if ($this->getHttpKernel() instanceof TerminableInterface) {
647 $this->getHttpKernel()->terminate($request, $response);
654 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
655 // Ensure sane PHP environment variables.
656 static::bootEnvironment();
659 $this->initializeSettings($request);
661 // Redirect the user to the installation script if Drupal has not been
662 // installed yet (i.e., if no $databases array has been defined in the
663 // settings.php file) and we are not already installing.
664 if (!Database::getConnectionInfo() && !drupal_installation_attempted() && PHP_SAPI !== 'cli') {
665 $response = new RedirectResponse($request->getBasePath() . '/core/install.php', 302, ['Cache-Control' => 'no-cache']);
669 $response = $this->getHttpKernel()->handle($request, $type, $catch);
672 catch (\Exception $e) {
673 if ($catch === FALSE) {
677 $response = $this->handleException($e, $request, $type);
680 // Adapt response headers to the current request.
681 $response->prepare($request);
687 * Converts an exception into a response.
689 * @param \Exception $e
691 * @param \Symfony\Component\HttpFoundation\Request $request
694 * The type of the request (one of HttpKernelInterface::MASTER_REQUEST or
695 * HttpKernelInterface::SUB_REQUEST)
697 * @return \Symfony\Component\HttpFoundation\Response
698 * A Response instance
701 * If the passed in exception cannot be turned into a response.
703 protected function handleException(\Exception $e, $request, $type) {
704 if ($this->shouldRedirectToInstaller($e, $this->container ? $this->container->get('database') : NULL)) {
705 return new RedirectResponse($request->getBasePath() . '/core/install.php', 302, ['Cache-Control' => 'no-cache']);
708 if ($e instanceof HttpExceptionInterface) {
709 $response = new Response($e->getMessage(), $e->getStatusCode());
710 $response->headers->add($e->getHeaders());
720 public function prepareLegacyRequest(Request $request) {
722 $this->preHandle($request);
723 // Setup services which are normally initialized from within stack
724 // middleware or during the request kernel event.
725 if (PHP_SAPI !== 'cli') {
726 $request->setSession($this->container->get('session'));
728 $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
729 $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
730 $this->container->get('request_stack')->push($request);
731 $this->container->get('router.request_context')->fromRequest($request);
736 * Returns module data on the filesystem.
739 * The name of the module.
741 * @return \Drupal\Core\Extension\Extension|bool
742 * Returns an Extension object if the module is found, FALSE otherwise.
744 protected function moduleData($module) {
745 if (!$this->moduleData) {
746 // First, find profiles.
747 $listing = new ExtensionDiscovery($this->root);
748 $listing->setProfileDirectories([]);
749 $all_profiles = $listing->scan('profile');
750 $profiles = array_intersect_key($all_profiles, $this->moduleList);
752 // If a module is within a profile directory but specifies another
753 // profile for testing, it needs to be found in the parent profile.
754 $settings = $this->getConfigStorage()->read('simpletest.settings');
755 $parent_profile = !empty($settings['parent_profile']) ? $settings['parent_profile'] : NULL;
756 if ($parent_profile && !isset($profiles[$parent_profile])) {
757 // In case both profile directories contain the same extension, the
758 // actual profile always has precedence.
759 $profiles = [$parent_profile => $all_profiles[$parent_profile]] + $profiles;
762 $profile_directories = array_map(function ($profile) {
763 return $profile->getPath();
765 $listing->setProfileDirectories($profile_directories);
768 $this->moduleData = $profiles + $listing->scan('module');
770 return isset($this->moduleData[$module]) ? $this->moduleData[$module] : FALSE;
774 * Implements Drupal\Core\DrupalKernelInterface::updateModules().
776 * @todo Remove obsolete $module_list parameter. Only $module_filenames is
779 public function updateModules(array $module_list, array $module_filenames = []) {
780 $pre_existing_module_namespaces = [];
781 if ($this->booted && is_array($this->moduleList)) {
782 $pre_existing_module_namespaces = $this->getModuleNamespacesPsr4($this->getModuleFileNames());
784 $this->moduleList = $module_list;
785 foreach ($module_filenames as $name => $extension) {
786 $this->moduleData[$name] = $extension;
789 // If we haven't yet booted, we don't need to do anything: the new module
790 // list will take effect when boot() is called. However we set a
791 // flag that the container needs a rebuild, so that a potentially cached
792 // container is not used. If we have already booted, then rebuild the
793 // container in order to refresh the serviceProvider list and container.
794 $this->containerNeedsRebuild = TRUE;
796 // We need to register any new namespaces to a new class loader because
797 // the current class loader might have stored a negative result for a
798 // class that is now available.
799 // @see \Composer\Autoload\ClassLoader::findFile()
800 $new_namespaces = array_diff_key(
801 $this->getModuleNamespacesPsr4($this->getModuleFileNames()),
802 $pre_existing_module_namespaces
804 if (!empty($new_namespaces)) {
805 $additional_class_loader = new ClassLoader();
806 $this->classLoaderAddMultiplePsr4($new_namespaces, $additional_class_loader);
807 $additional_class_loader->register();
810 $this->initializeContainer();
815 * Returns the container cache key based on the environment.
817 * The 'environment' consists of:
818 * - The kernel environment string.
819 * - The Drupal version constant.
820 * - The deployment identifier from settings.php. This allows custom
821 * deployments to force a container rebuild.
822 * - The operating system running PHP. This allows compiler passes to optimize
823 * services for different operating systems.
824 * - The paths to any additional container YAMLs from settings.php.
827 * The cache key used for the service container.
829 protected function getContainerCacheKey() {
830 $parts = ['service_container', $this->environment, \Drupal::VERSION, Settings::get('deployment_identifier'), PHP_OS, serialize(Settings::get('container_yamls'))];
831 return implode(':', $parts);
835 * Returns the kernel parameters.
837 * @return array An array of kernel parameters
839 protected function getKernelParameters() {
841 'kernel.environment' => $this->environment,
846 * Initializes the service container.
848 * @return \Symfony\Component\DependencyInjection\ContainerInterface
850 protected function initializeContainer() {
851 $this->containerNeedsDumping = FALSE;
852 $session_started = FALSE;
853 if (isset($this->container)) {
854 // Save the id of the currently logged in user.
855 if ($this->container->initialized('current_user')) {
856 $current_user_id = $this->container->get('current_user')->id();
859 // If there is a session, close and save it.
860 if ($this->container->initialized('session')) {
861 $session = $this->container->get('session');
862 if ($session->isStarted()) {
863 $session_started = TRUE;
870 // If we haven't booted yet but there is a container, then we're asked to
871 // boot the container injected via setContainer().
872 // @see \Drupal\KernelTests\KernelTestBase::setUp()
873 if (isset($this->container) && !$this->booted) {
874 $container = $this->container;
877 // If the module list hasn't already been set in updateModules and we are
878 // not forcing a rebuild, then try and load the container from the cache.
879 if (empty($this->moduleList) && !$this->containerNeedsRebuild) {
880 $container_definition = $this->getCachedContainerDefinition();
883 // If there is no container and no cached container definition, build a new
885 if (!isset($container) && !isset($container_definition)) {
886 // Building the container creates 1000s of objects. Garbage collection of
887 // these objects is expensive. This appears to be causing random
888 // segmentation faults in PHP 5.6 due to
889 // https://bugs.php.net/bug.php?id=72286. Once the container is rebuilt,
890 // garbage collection is re-enabled.
891 $disable_gc = version_compare(PHP_VERSION, '7', '<') && gc_enabled();
896 $container = $this->compileContainer();
898 // Only dump the container if dumping is allowed. This is useful for
899 // KernelTestBase, which never wants to use the real container, but always
900 // the container builder.
901 if ($this->allowDumping) {
902 $dumper = new $this->phpArrayDumperClass($container);
903 $container_definition = $dumper->getArray();
905 // If garbage collection was disabled prior to rebuilding container,
912 // The container was rebuilt successfully.
913 $this->containerNeedsRebuild = FALSE;
915 // Only create a new class if we have a container definition.
916 if (isset($container_definition)) {
917 $class = Settings::get('container_base_class', '\Drupal\Core\DependencyInjection\Container');
918 $container = new $class($container_definition);
921 $this->attachSynthetic($container);
923 $this->container = $container;
924 if ($session_started) {
925 $this->container->get('session')->start();
928 // The request stack is preserved across container rebuilds. Reinject the
929 // new session into the master request if one was present before.
930 if (($request_stack = $this->container->get('request_stack', ContainerInterface::NULL_ON_INVALID_REFERENCE))) {
931 if ($request = $request_stack->getMasterRequest()) {
933 if ($request->hasSession()) {
934 $request->setSession($this->container->get('session'));
939 if (!empty($current_user_id)) {
940 $this->container->get('current_user')->setInitialAccountId($current_user_id);
943 \Drupal::setContainer($this->container);
945 // Allow other parts of the codebase to react on container initialization in
947 if (!empty($subrequest)) {
948 $this->container->get('event_dispatcher')->dispatch(self::CONTAINER_INITIALIZE_SUBREQUEST_FINISHED);
951 // If needs dumping flag was set, dump the container.
952 if ($this->containerNeedsDumping && !$this->cacheDrupalContainer($container_definition)) {
953 $this->container->get('logger.factory')->get('DrupalKernel')->error('Container cannot be saved to cache.');
956 return $this->container;
960 * Setup a consistent PHP environment.
962 * This method sets PHP environment options we want to be sure are set
963 * correctly for security or just saneness.
965 * @param string $app_root
966 * (optional) The path to the application root as a string. If not supplied,
967 * the application root will be computed.
969 public static function bootEnvironment($app_root = NULL) {
970 if (static::$isEnvironmentInitialized) {
974 // Determine the application root if it's not supplied.
975 if ($app_root === NULL) {
976 $app_root = static::guessApplicationRoot();
979 // Include our bootstrap file.
980 require_once $app_root . '/core/includes/bootstrap.inc';
982 // Enforce E_STRICT, but allow users to set levels not part of E_STRICT.
983 error_reporting(E_STRICT | E_ALL);
985 // Override PHP settings required for Drupal to work properly.
986 // sites/default/default.settings.php contains more runtime settings.
987 // The .htaccess file contains settings that cannot be changed at runtime.
989 if (PHP_SAPI !== 'cli') {
990 // Use session cookies, not transparent sessions that puts the session id
991 // in the query string.
992 ini_set('session.use_cookies', '1');
993 ini_set('session.use_only_cookies', '1');
994 ini_set('session.use_trans_sid', '0');
995 // Don't send HTTP headers using PHP's session handler.
996 // Send an empty string to disable the cache limiter.
997 ini_set('session.cache_limiter', '');
998 // Use httponly session cookies.
999 ini_set('session.cookie_httponly', '1');
1002 // Set sane locale settings, to ensure consistent string, dates, times and
1003 // numbers handling.
1004 setlocale(LC_ALL, 'C');
1006 // Set appropriate configuration for multi-byte strings.
1007 mb_internal_encoding('utf-8');
1010 // Indicate that code is operating in a test child site.
1011 if (!defined('DRUPAL_TEST_IN_CHILD_SITE')) {
1012 if ($test_prefix = drupal_valid_test_ua()) {
1013 $test_db = new TestDatabase($test_prefix);
1014 // Only code that interfaces directly with tests should rely on this
1015 // constant; e.g., the error/exception handler conditionally adds further
1016 // error information into HTTP response headers that are consumed by
1017 // Simpletest's internal browser.
1018 define('DRUPAL_TEST_IN_CHILD_SITE', TRUE);
1020 // Web tests are to be conducted with runtime assertions active.
1021 assert_options(ASSERT_ACTIVE, TRUE);
1022 // Now synchronize PHP 5 and 7's handling of assertions as much as
1026 // Log fatal errors to the test site directory.
1027 ini_set('log_errors', 1);
1028 ini_set('error_log', $app_root . '/' . $test_db->getTestSitePath() . '/error.log');
1030 // Ensure that a rewritten settings.php is used if opcache is on.
1031 ini_set('opcache.validate_timestamps', 'on');
1032 ini_set('opcache.revalidate_freq', 0);
1035 // Ensure that no other code defines this.
1036 define('DRUPAL_TEST_IN_CHILD_SITE', FALSE);
1040 // Set the Drupal custom error handler.
1041 set_error_handler('_drupal_error_handler');
1042 set_exception_handler('_drupal_exception_handler');
1044 static::$isEnvironmentInitialized = TRUE;
1048 * Locate site path and initialize settings singleton.
1050 * @param \Symfony\Component\HttpFoundation\Request $request
1051 * The current request.
1053 * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
1054 * In case the host name in the request is not trusted.
1056 protected function initializeSettings(Request $request) {
1057 $site_path = static::findSitePath($request);
1058 $this->setSitePath($site_path);
1059 $class_loader_class = get_class($this->classLoader);
1060 Settings::initialize($this->root, $site_path, $this->classLoader);
1062 // Initialize our list of trusted HTTP Host headers to protect against
1064 $host_patterns = Settings::get('trusted_host_patterns', []);
1065 if (PHP_SAPI !== 'cli' && !empty($host_patterns)) {
1066 if (static::setupTrustedHosts($request, $host_patterns) === FALSE) {
1067 throw new BadRequestHttpException('The provided host name is not valid for this server.');
1071 // If the class loader is still the same, possibly
1072 // upgrade to an optimized class loader.
1073 if ($class_loader_class == get_class($this->classLoader)
1074 && Settings::get('class_loader_auto_detect', TRUE)) {
1075 $prefix = Settings::getApcuPrefix('class_loader', $this->root);
1078 // We autodetect one of the following three optimized classloaders, if
1079 // their underlying extension exists.
1080 if (function_exists('apcu_fetch')) {
1081 $loader = new ApcClassLoader($prefix, $this->classLoader);
1083 elseif (extension_loaded('wincache')) {
1084 $loader = new WinCacheClassLoader($prefix, $this->classLoader);
1086 elseif (extension_loaded('xcache')) {
1087 $loader = new XcacheClassLoader($prefix, $this->classLoader);
1089 if (!empty($loader)) {
1090 $this->classLoader->unregister();
1091 // The optimized classloader might be persistent and store cache misses.
1092 // For example, once a cache miss is stored in APCu clearing it on a
1093 // specific web-head will not clear any other web-heads. Therefore
1094 // fallback to the composer class loader that only statically caches
1096 $old_loader = $this->classLoader;
1097 $this->classLoader = $loader;
1098 // Our class loaders are prepended to ensure they come first like the
1099 // class loader they are replacing.
1100 $old_loader->register(TRUE);
1101 $loader->register(TRUE);
1107 * Bootstraps the legacy global request variables.
1109 * @param \Symfony\Component\HttpFoundation\Request $request
1110 * The current request.
1112 * @todo D8: Eliminate this entirely in favor of Request object.
1114 protected function initializeRequestGlobals(Request $request) {
1116 // Set and derived from $base_url by this function.
1117 global $base_path, $base_root;
1118 global $base_secure_url, $base_insecure_url;
1121 $base_root = $request->getSchemeAndHttpHost();
1122 $base_url = $base_root;
1124 // For a request URI of '/index.php/foo', $_SERVER['SCRIPT_NAME'] is
1125 // '/index.php', whereas $_SERVER['PHP_SELF'] is '/index.php/foo'.
1126 if ($dir = rtrim(dirname($request->server->get('SCRIPT_NAME')), '\/')) {
1127 // Remove "core" directory if present, allowing install.php,
1128 // authorize.php, and others to auto-detect a base path.
1129 $core_position = strrpos($dir, '/core');
1130 if ($core_position !== FALSE && strlen($dir) - 5 == $core_position) {
1131 $base_path = substr($dir, 0, $core_position);
1136 $base_url .= $base_path;
1142 $base_secure_url = str_replace('http://', 'https://', $base_url);
1143 $base_insecure_url = str_replace('https://', 'http://', $base_url);
1147 * Returns service instances to persist from an old container to a new one.
1149 protected function getServicesToPersist(ContainerInterface $container) {
1151 foreach ($container->getParameter('persist_ids') as $id) {
1152 // It's pointless to persist services not yet initialized.
1153 if ($container->initialized($id)) {
1154 $persist[$id] = $container->get($id);
1161 * Moves persistent service instances into a new container.
1163 protected function persistServices(ContainerInterface $container, array $persist) {
1164 foreach ($persist as $id => $object) {
1165 // Do not override services already set() on the new container, for
1166 // example 'service_container'.
1167 if (!$container->initialized($id)) {
1168 $container->set($id, $object);
1176 public function rebuildContainer() {
1177 // Empty module properties and for them to be reloaded from scratch.
1178 $this->moduleList = NULL;
1179 $this->moduleData = [];
1180 $this->containerNeedsRebuild = TRUE;
1181 return $this->initializeContainer();
1187 public function invalidateContainer() {
1188 // An invalidated container needs a rebuild.
1189 $this->containerNeedsRebuild = TRUE;
1191 // If we have not yet booted, settings or bootstrap services might not yet
1192 // be available. In that case the container will not be loaded from cache
1193 // due to the above setting when the Kernel is booted.
1194 if (!$this->booted) {
1198 // Also remove the container definition from the cache backend.
1199 $this->bootstrapContainer->get('cache.container')->deleteAll();
1203 * Attach synthetic values on to kernel.
1205 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
1208 * @return \Symfony\Component\DependencyInjection\ContainerInterface
1210 protected function attachSynthetic(ContainerInterface $container) {
1212 if (isset($this->container)) {
1213 $persist = $this->getServicesToPersist($this->container);
1215 $this->persistServices($container, $persist);
1217 // All namespaces must be registered before we attempt to use any service
1218 // from the container.
1219 $this->classLoaderAddMultiplePsr4($container->getParameter('container.namespaces'));
1221 $container->set('kernel', $this);
1223 // Set the class loader which was registered as a synthetic service.
1224 $container->set('class_loader', $this->classLoader);
1229 * Compiles a new service container.
1231 * @return \Drupal\Core\DependencyInjection\ContainerBuilder The compiled service container
1233 protected function compileContainer() {
1234 // We are forcing a container build so it is reasonable to assume that the
1235 // calling method knows something about the system has changed requiring the
1236 // container to be dumped to the filesystem.
1237 if ($this->allowDumping) {
1238 $this->containerNeedsDumping = TRUE;
1241 $this->initializeServiceProviders();
1242 $container = $this->getContainerBuilder();
1243 $container->set('kernel', $this);
1244 $container->setParameter('container.modules', $this->getModulesParameter());
1245 $container->setParameter('install_profile', $this->getInstallProfile());
1247 // Get a list of namespaces and put it onto the container.
1248 $namespaces = $this->getModuleNamespacesPsr4($this->getModuleFileNames());
1249 // Add all components in \Drupal\Core and \Drupal\Component that have one of
1250 // the following directories:
1254 foreach (['Core', 'Component'] as $parent_directory) {
1255 $path = 'core/lib/Drupal/' . $parent_directory;
1256 $parent_namespace = 'Drupal\\' . $parent_directory;
1257 foreach (new \DirectoryIterator($this->root . '/' . $path) as $component) {
1258 /** @var $component \DirectoryIterator */
1259 $pathname = $component->getPathname();
1260 if (!$component->isDot() && $component->isDir() && (
1261 is_dir($pathname . '/Plugin') ||
1262 is_dir($pathname . '/Entity') ||
1263 is_dir($pathname . '/Element')
1265 $namespaces[$parent_namespace . '\\' . $component->getFilename()] = $path . '/' . $component->getFilename();
1269 $container->setParameter('container.namespaces', $namespaces);
1271 // Store the default language values on the container. This is so that the
1272 // default language can be configured using the configuration factory. This
1273 // avoids the circular dependencies that would created by
1274 // \Drupal\language\LanguageServiceProvider::alter() and allows the default
1275 // language to not be English in the installer.
1276 $default_language_values = Language::$defaultValues;
1277 if ($system = $this->getConfigStorage()->read('system.site')) {
1278 if ($default_language_values['id'] != $system['langcode']) {
1279 $default_language_values = ['id' => $system['langcode']];
1282 $container->setParameter('language.default_values', $default_language_values);
1284 // Register synthetic services.
1285 $container->register('class_loader')->setSynthetic(TRUE);
1286 $container->register('kernel', 'Symfony\Component\HttpKernel\KernelInterface')->setSynthetic(TRUE);
1287 $container->register('service_container', 'Symfony\Component\DependencyInjection\ContainerInterface')->setSynthetic(TRUE);
1289 // Register application services.
1290 $yaml_loader = new YamlFileLoader($container);
1291 foreach ($this->serviceYamls['app'] as $filename) {
1292 $yaml_loader->load($filename);
1294 foreach ($this->serviceProviders['app'] as $provider) {
1295 if ($provider instanceof ServiceProviderInterface) {
1296 $provider->register($container);
1299 // Register site-specific service overrides.
1300 foreach ($this->serviceYamls['site'] as $filename) {
1301 $yaml_loader->load($filename);
1303 foreach ($this->serviceProviders['site'] as $provider) {
1304 if ($provider instanceof ServiceProviderInterface) {
1305 $provider->register($container);
1309 // Identify all services whose instances should be persisted when rebuilding
1310 // the container during the lifetime of the kernel (e.g., during a kernel
1311 // reboot). Include synthetic services, because by definition, they cannot
1312 // be automatically reinstantiated. Also include services tagged to persist.
1314 foreach ($container->getDefinitions() as $id => $definition) {
1315 // It does not make sense to persist the container itself, exclude it.
1316 if ($id !== 'service_container' && ($definition->isSynthetic() || $definition->getTag('persist'))) {
1317 $persist_ids[] = $id;
1320 $container->setParameter('persist_ids', $persist_ids);
1322 $container->compile();
1327 * Registers all service providers to the kernel.
1329 * @throws \LogicException
1331 protected function initializeServiceProviders() {
1332 $this->discoverServiceProviders();
1333 $this->serviceProviders = [
1337 foreach ($this->serviceProviderClasses as $origin => $classes) {
1338 foreach ($classes as $name => $class) {
1339 if (!is_object($class)) {
1340 $this->serviceProviders[$origin][$name] = new $class();
1343 $this->serviceProviders[$origin][$name] = $class;
1350 * Gets a new ContainerBuilder instance used to build the service container.
1352 * @return \Drupal\Core\DependencyInjection\ContainerBuilder
1354 protected function getContainerBuilder() {
1355 return new ContainerBuilder(new ParameterBag($this->getKernelParameters()));
1359 * Stores the container definition in a cache.
1361 * @param array $container_definition
1362 * The container definition to cache.
1365 * TRUE if the container was successfully cached.
1367 protected function cacheDrupalContainer(array $container_definition) {
1370 $this->bootstrapContainer->get('cache.container')->set($this->getContainerCacheKey(), $container_definition);
1372 catch (\Exception $e) {
1373 // There is no way to get from the Cache API if the cache set was
1374 // successful or not, hence an Exception is caught and the caller informed
1375 // about the error condition.
1383 * Gets a http kernel from the container
1385 * @return \Symfony\Component\HttpKernel\HttpKernelInterface
1387 protected function getHttpKernel() {
1388 return $this->container->get('http_kernel');
1392 * Returns the active configuration storage to use during building the container.
1394 * @return \Drupal\Core\Config\StorageInterface
1396 protected function getConfigStorage() {
1397 if (!isset($this->configStorage)) {
1398 // The active configuration storage may not exist yet; e.g., in the early
1399 // installer. Catch the exception thrown by config_get_config_directory().
1401 $this->configStorage = BootstrapConfigStorageFactory::get($this->classLoader);
1403 catch (\Exception $e) {
1404 $this->configStorage = new NullStorage();
1407 return $this->configStorage;
1411 * Returns an array of Extension class parameters for all enabled modules.
1415 protected function getModulesParameter() {
1417 foreach ($this->moduleList as $name => $weight) {
1418 if ($data = $this->moduleData($name)) {
1419 $extensions[$name] = [
1420 'type' => $data->getType(),
1421 'pathname' => $data->getPathname(),
1422 'filename' => $data->getExtensionFilename(),
1430 * Gets the file name for each enabled module.
1433 * Array where each key is a module name, and each value is a path to the
1434 * respective *.info.yml file.
1436 protected function getModuleFileNames() {
1438 foreach ($this->moduleList as $module => $weight) {
1439 if ($data = $this->moduleData($module)) {
1440 $filenames[$module] = $data->getPathname();
1447 * Gets the PSR-4 base directories for module namespaces.
1449 * @param string[] $module_file_names
1450 * Array where each key is a module name, and each value is a path to the
1451 * respective *.info.yml file.
1454 * Array where each key is a module namespace like 'Drupal\system', and each
1455 * value is the PSR-4 base directory associated with the module namespace.
1457 protected function getModuleNamespacesPsr4($module_file_names) {
1459 foreach ($module_file_names as $module => $filename) {
1460 $namespaces["Drupal\\$module"] = dirname($filename) . '/src';
1466 * Registers a list of namespaces with PSR-4 directories for class loading.
1468 * @param array $namespaces
1469 * Array where each key is a namespace like 'Drupal\system', and each value
1470 * is either a PSR-4 base directory, or an array of PSR-4 base directories
1471 * associated with this namespace.
1472 * @param object $class_loader
1473 * The class loader. Normally \Composer\Autoload\ClassLoader, as included by
1474 * the front controller, but may also be decorated; e.g.,
1475 * \Symfony\Component\ClassLoader\ApcClassLoader.
1477 protected function classLoaderAddMultiplePsr4(array $namespaces = [], $class_loader = NULL) {
1478 if ($class_loader === NULL) {
1479 $class_loader = $this->classLoader;
1481 foreach ($namespaces as $prefix => $paths) {
1482 if (is_array($paths)) {
1483 foreach ($paths as $key => $value) {
1484 $paths[$key] = $this->root . '/' . $value;
1487 elseif (is_string($paths)) {
1488 $paths = $this->root . '/' . $paths;
1490 $class_loader->addPsr4($prefix . '\\', $paths);
1495 * Validates a hostname length.
1497 * @param string $host
1501 * TRUE if the length is appropriate, or FALSE otherwise.
1503 protected static function validateHostnameLength($host) {
1504 // Limit the length of the host name to 1000 bytes to prevent DoS attacks
1505 // with long host names.
1506 return strlen($host) <= 1000
1507 // Limit the number of subdomains and port separators to prevent DoS attacks
1508 // in findSitePath().
1509 && substr_count($host, '.') <= 100
1510 && substr_count($host, ':') <= 100;
1514 * Validates the hostname supplied from the HTTP request.
1516 * @param \Symfony\Component\HttpFoundation\Request $request
1517 * The request object
1520 * TRUE if the hostname is valid, or FALSE otherwise.
1522 public static function validateHostname(Request $request) {
1523 // $request->getHost() can throw an UnexpectedValueException if it
1524 // detects a bad hostname, but it does not validate the length.
1526 $http_host = $request->getHost();
1528 catch (\UnexpectedValueException $e) {
1532 if (static::validateHostnameLength($http_host) === FALSE) {
1540 * Sets up the lists of trusted HTTP Host headers.
1542 * Since the HTTP Host header can be set by the user making the request, it
1543 * is possible to create an attack vectors against a site by overriding this.
1544 * Symfony provides a mechanism for creating a list of trusted Host values.
1546 * Host patterns (as regular expressions) can be configured through
1547 * settings.php for multisite installations, sites using ServerAlias without
1548 * canonical redirection, or configurations where the site responds to default
1549 * requests. For example,
1552 * $settings['trusted_host_patterns'] = array(
1554 * '^*.example\.com$',
1558 * @param \Symfony\Component\HttpFoundation\Request $request
1559 * The request object.
1560 * @param array $host_patterns
1561 * The array of trusted host patterns.
1564 * TRUE if the Host header is trusted, FALSE otherwise.
1566 * @see https://www.drupal.org/node/1992030
1567 * @see \Drupal\Core\Http\TrustedHostsRequestFactory
1569 protected static function setupTrustedHosts(Request $request, $host_patterns) {
1570 $request->setTrustedHosts($host_patterns);
1572 // Get the host, which will validate the current request.
1574 $host = $request->getHost();
1576 // Fake requests created through Request::create() without passing in the
1577 // server variables from the main request have a default host of
1578 // 'localhost'. If 'localhost' does not match any of the trusted host
1579 // patterns these fake requests would fail the host verification. Instead,
1580 // TrustedHostsRequestFactory makes sure to pass in the server variables
1581 // from the main request.
1582 $request_factory = new TrustedHostsRequestFactory($host);
1583 Request::setFactory([$request_factory, 'createRequest']);
1586 catch (\UnexpectedValueException $e) {
1594 * Add service files.
1596 * @param string[] $service_yamls
1597 * A list of service files.
1599 protected function addServiceFiles(array $service_yamls) {
1600 $this->serviceYamls['site'] = array_filter($service_yamls, 'file_exists');
1604 * Gets the active install profile.
1606 * @return string|null
1607 * The name of the any active install profile or distribution.
1609 protected function getInstallProfile() {
1610 $config = $this->getConfigStorage()->read('core.extension');
1611 if (isset($config['profile'])) {
1612 $install_profile = $config['profile'];
1614 // @todo https://www.drupal.org/node/2831065 remove the BC layer.
1616 // If system_update_8300() has not yet run fallback to using settings.
1617 $settings = Settings::getAll();
1618 $install_profile = isset($settings['install_profile']) ? $settings['install_profile'] : NULL;
1621 // Normalize an empty string to a NULL value.
1622 return empty($install_profile) ? NULL : $install_profile;