5 use Composer\Autoload\ClassLoader;
6 use Drupal\Component\Assertion\Handle;
7 use Drupal\Component\FileCache\FileCacheFactory;
8 use Drupal\Component\Utility\Unicode;
9 use Drupal\Component\Utility\UrlHelper;
10 use Drupal\Core\Cache\DatabaseBackend;
11 use Drupal\Core\Config\BootstrapConfigStorageFactory;
12 use Drupal\Core\Config\NullStorage;
13 use Drupal\Core\Database\Database;
14 use Drupal\Core\DependencyInjection\ContainerBuilder;
15 use Drupal\Core\DependencyInjection\ServiceModifierInterface;
16 use Drupal\Core\DependencyInjection\ServiceProviderInterface;
17 use Drupal\Core\DependencyInjection\YamlFileLoader;
18 use Drupal\Core\Extension\ExtensionDiscovery;
19 use Drupal\Core\File\MimeType\MimeTypeGuesser;
20 use Drupal\Core\Http\TrustedHostsRequestFactory;
21 use Drupal\Core\Installer\InstallerRedirectTrait;
22 use Drupal\Core\Language\Language;
23 use Drupal\Core\Security\RequestSanitizer;
24 use Drupal\Core\Site\Settings;
25 use Drupal\Core\Test\TestDatabase;
26 use Symfony\Cmf\Component\Routing\RouteObjectInterface;
27 use Symfony\Component\ClassLoader\ApcClassLoader;
28 use Symfony\Component\ClassLoader\WinCacheClassLoader;
29 use Symfony\Component\ClassLoader\XcacheClassLoader;
30 use Symfony\Component\DependencyInjection\ContainerInterface;
31 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
32 use Symfony\Component\HttpFoundation\RedirectResponse;
33 use Symfony\Component\HttpFoundation\Request;
34 use Symfony\Component\HttpFoundation\Response;
35 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
36 use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
37 use Symfony\Component\HttpKernel\TerminableInterface;
38 use Symfony\Component\Routing\Route;
41 * The DrupalKernel class is the core of Drupal itself.
43 * This class is responsible for building the Dependency Injection Container and
44 * also deals with the registration of service providers. It allows registered
45 * service providers to add their services to the container. Core provides the
46 * CoreServiceProvider, which, in addition to registering any core services that
47 * cannot be registered in the core.services.yaml file, adds any compiler passes
48 * needed by core, e.g. for processing tagged services. Each module can add its
49 * own service provider, i.e. a class implementing
50 * Drupal\Core\DependencyInjection\ServiceProvider, to register services to the
51 * container, or modify existing services.
53 class DrupalKernel implements DrupalKernelInterface, TerminableInterface {
54 use InstallerRedirectTrait;
57 * Holds the class used for dumping the container to a PHP array.
59 * In combination with swapping the container class this is useful to e.g.
60 * dump to the human-readable PHP array format to debug the container
61 * definition in an easier way.
65 protected $phpArrayDumperClass = '\Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper';
68 * Holds the default bootstrap container definition.
72 protected $defaultBootstrapContainerDefinition = [
76 'class' => 'Drupal\Core\Database\Connection',
77 'factory' => 'Drupal\Core\Database\Database::getConnection',
78 'arguments' => ['default'],
80 'cache.container' => [
81 'class' => 'Drupal\Core\Cache\DatabaseBackend',
82 'arguments' => ['@database', '@cache_tags_provider.container', 'container', DatabaseBackend::MAXIMUM_NONE],
84 'cache_tags_provider.container' => [
85 'class' => 'Drupal\Core\Cache\DatabaseCacheTagsChecksum',
86 'arguments' => ['@database'],
92 * Holds the class used for instantiating the bootstrap container.
96 protected $bootstrapContainerClass = '\Drupal\Component\DependencyInjection\PhpArrayContainer';
99 * Holds the bootstrap container.
101 * @var \Symfony\Component\DependencyInjection\ContainerInterface
103 protected $bootstrapContainer;
106 * Holds the container instance.
108 * @var \Symfony\Component\DependencyInjection\ContainerInterface
110 protected $container;
113 * The environment, e.g. 'testing', 'install'.
117 protected $environment;
120 * Whether the kernel has been booted.
124 protected $booted = FALSE;
127 * Whether essential services have been set up properly by preHandle().
131 protected $prepared = FALSE;
134 * Holds the list of enabled modules.
137 * An associative array whose keys are module names and whose values are
140 protected $moduleList;
143 * List of available modules and installation profiles.
145 * @var \Drupal\Core\Extension\Extension[]
147 protected $moduleData = [];
150 * The class loader object.
152 * @var \Composer\Autoload\ClassLoader
154 protected $classLoader;
157 * Config storage object used for reading enabled modules configuration.
159 * @var \Drupal\Core\Config\StorageInterface
161 protected $configStorage;
164 * Whether the container can be dumped.
168 protected $allowDumping;
171 * Whether the container needs to be rebuilt the next time it is initialized.
175 protected $containerNeedsRebuild = FALSE;
178 * Whether the container needs to be dumped once booting is complete.
182 protected $containerNeedsDumping;
185 * List of discovered services.yml pathnames.
187 * This is a nested array whose top-level keys are 'app' and 'site', denoting
188 * the origin of a service provider. Site-specific providers have to be
189 * collected separately, because they need to be processed last, so as to be
190 * able to override services from application service providers.
194 protected $serviceYamls;
197 * List of discovered service provider class names or objects.
199 * This is a nested array whose top-level keys are 'app' and 'site', denoting
200 * the origin of a service provider. Site-specific providers have to be
201 * collected separately, because they need to be processed last, so as to be
202 * able to override services from application service providers.
204 * Allowing objects is for example used to allow
205 * \Drupal\KernelTests\KernelTestBase to register itself as service provider.
209 protected $serviceProviderClasses;
212 * List of instantiated service provider classes.
214 * @see \Drupal\Core\DrupalKernel::$serviceProviderClasses
218 protected $serviceProviders;
221 * Whether the PHP environment has been initialized.
223 * This legacy phase can only be booted once because it sets session INI
224 * settings. If a session has already been started, re-generating these
225 * settings would break the session.
229 protected static $isEnvironmentInitialized = FALSE;
232 * The site directory.
246 * Create a DrupalKernel object from a request.
248 * @param \Symfony\Component\HttpFoundation\Request $request
250 * @param $class_loader
251 * The class loader. Normally Composer's ClassLoader, as included by the
252 * front controller, but may also be decorated; e.g.,
253 * \Symfony\Component\ClassLoader\ApcClassLoader.
254 * @param string $environment
255 * String indicating the environment, e.g. 'prod' or 'dev'.
256 * @param bool $allow_dumping
257 * (optional) FALSE to stop the container from being written to or read
258 * from disk. Defaults to TRUE.
259 * @param string $app_root
260 * (optional) The path to the application root as a string. If not supplied,
261 * the application root will be computed.
265 * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
266 * In case the host name in the request is not trusted.
268 public static function createFromRequest(Request $request, $class_loader, $environment, $allow_dumping = TRUE, $app_root = NULL) {
269 $kernel = new static($environment, $class_loader, $allow_dumping, $app_root);
270 static::bootEnvironment($app_root);
271 $kernel->initializeSettings($request);
276 * Constructs a DrupalKernel object.
278 * @param string $environment
279 * String indicating the environment, e.g. 'prod' or 'dev'.
280 * @param $class_loader
281 * The class loader. Normally \Composer\Autoload\ClassLoader, as included by
282 * the front controller, but may also be decorated; e.g.,
283 * \Symfony\Component\ClassLoader\ApcClassLoader.
284 * @param bool $allow_dumping
285 * (optional) FALSE to stop the container from being written to or read
286 * from disk. Defaults to TRUE.
287 * @param string $app_root
288 * (optional) The path to the application root as a string. If not supplied,
289 * the application root will be computed.
291 public function __construct($environment, $class_loader, $allow_dumping = TRUE, $app_root = NULL) {
292 $this->environment = $environment;
293 $this->classLoader = $class_loader;
294 $this->allowDumping = $allow_dumping;
295 if ($app_root === NULL) {
296 $app_root = static::guessApplicationRoot();
298 $this->root = $app_root;
302 * Determine the application root directory based on assumptions.
305 * The application root.
307 protected static function guessApplicationRoot() {
308 return dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
312 * Returns the appropriate site directory for a request.
314 * Once the kernel has been created DrupalKernelInterface::getSitePath() is
315 * preferred since it gets the statically cached result of this method.
317 * Site directories contain all site specific code. This includes settings.php
318 * for bootstrap level configuration, file configuration stores, public file
319 * storage and site specific modules and themes.
321 * Finds a matching site directory file by stripping the website's hostname
322 * from left to right and pathname from right to left. By default, the
323 * directory must contain a 'settings.php' file for it to match. If the
324 * parameter $require_settings is set to FALSE, then a directory without a
325 * 'settings.php' file will match as well. The first configuration file found
326 * will be used and the remaining ones will be ignored. If no configuration
327 * file is found, returns a default value 'sites/default'. See
328 * default.settings.php for examples on how the URL is converted to a
331 * If a file named sites.php is present in the sites directory, it will be
332 * loaded prior to scanning for directories. That file can define aliases in
333 * an associative array named $sites. The array is written in the format
334 * '<port>.<domain>.<path>' => 'directory'. As an example, to create a
335 * directory alias for https://www.drupal.org:8080/mysite/test whose
336 * configuration file is in sites/example.com, the array should be defined as:
339 * '8080.www.drupal.org.mysite.test' => 'example.com',
343 * @param \Symfony\Component\HttpFoundation\Request $request
344 * The current request.
345 * @param bool $require_settings
346 * Only directories with an existing settings.php file will be recognized.
347 * Defaults to TRUE. During initial installation, this is set to FALSE so
348 * that Drupal can detect a matching directory, then create a new
349 * settings.php file in it.
350 * @param string $app_root
351 * (optional) The path to the application root as a string. If not supplied,
352 * the application root will be computed.
355 * The path of the matching directory.
357 * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
358 * In case the host name in the request is invalid.
360 * @see \Drupal\Core\DrupalKernelInterface::getSitePath()
361 * @see \Drupal\Core\DrupalKernelInterface::setSitePath()
362 * @see default.settings.php
363 * @see example.sites.php
365 public static function findSitePath(Request $request, $require_settings = TRUE, $app_root = NULL) {
366 if (static::validateHostname($request) === FALSE) {
367 throw new BadRequestHttpException();
370 if ($app_root === NULL) {
371 $app_root = static::guessApplicationRoot();
374 // Check for a simpletest override.
375 if ($test_prefix = drupal_valid_test_ua()) {
376 $test_db = new TestDatabase($test_prefix);
377 return $test_db->getTestSitePath();
380 // Determine whether multi-site functionality is enabled.
381 if (!file_exists($app_root . '/sites/sites.php')) {
382 return 'sites/default';
385 // Otherwise, use find the site path using the request.
386 $script_name = $request->server->get('SCRIPT_NAME');
388 $script_name = $request->server->get('SCRIPT_FILENAME');
390 $http_host = $request->getHttpHost();
393 include $app_root . '/sites/sites.php';
395 $uri = explode('/', $script_name);
396 $server = explode('.', implode('.', array_reverse(explode(':', rtrim($http_host, '.')))));
397 for ($i = count($uri) - 1; $i > 0; $i--) {
398 for ($j = count($server); $j > 0; $j--) {
399 $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
400 if (isset($sites[$dir]) && file_exists($app_root . '/sites/' . $sites[$dir])) {
403 if (file_exists($app_root . '/sites/' . $dir . '/settings.php') || (!$require_settings && file_exists($app_root . '/sites/' . $dir))) {
408 return 'sites/default';
414 public function setSitePath($path) {
415 if ($this->booted && $path !== $this->sitePath) {
416 throw new \LogicException('Site path cannot be changed after calling boot()');
418 $this->sitePath = $path;
424 public function getSitePath() {
425 return $this->sitePath;
431 public function getAppRoot() {
438 public function boot() {
443 // Ensure that findSitePath is set.
444 if (!$this->sitePath) {
445 throw new \Exception('Kernel does not have site path set before calling boot()');
448 // Initialize the FileCacheFactory component. We have to do it here instead
449 // of in \Drupal\Component\FileCache\FileCacheFactory because we can not use
450 // the Settings object in a component.
451 $configuration = Settings::get('file_cache');
453 // Provide a default configuration, if not set.
454 if (!isset($configuration['default'])) {
455 // @todo Use extension_loaded('apcu') for non-testbot
456 // https://www.drupal.org/node/2447753.
457 if (function_exists('apcu_fetch')) {
458 $configuration['default']['cache_backend_class'] = '\Drupal\Component\FileCache\ApcuFileCacheBackend';
461 FileCacheFactory::setConfiguration($configuration);
462 FileCacheFactory::setPrefix(Settings::getApcuPrefix('file_cache', $this->root));
464 $this->bootstrapContainer = new $this->bootstrapContainerClass(Settings::get('bootstrap_container_definition', $this->defaultBootstrapContainerDefinition));
466 // Initialize the container.
467 $this->initializeContainer();
469 $this->booted = TRUE;
477 public function shutdown() {
478 if (FALSE === $this->booted) {
481 $this->container->get('stream_wrapper_manager')->unregister();
482 $this->booted = FALSE;
483 $this->container = NULL;
484 $this->moduleList = NULL;
485 $this->moduleData = [];
491 public function getContainer() {
492 return $this->container;
498 public function setContainer(ContainerInterface $container = NULL) {
499 if (isset($this->container)) {
500 throw new \Exception('The container should not override an existing container.');
503 throw new \Exception('The container cannot be set after a booted kernel.');
506 $this->container = $container;
513 public function getCachedContainerDefinition() {
514 $cache = $this->bootstrapContainer->get('cache.container')->get($this->getContainerCacheKey());
526 public function loadLegacyIncludes() {
527 require_once $this->root . '/core/includes/common.inc';
528 require_once $this->root . '/core/includes/database.inc';
529 require_once $this->root . '/core/includes/module.inc';
530 require_once $this->root . '/core/includes/theme.inc';
531 require_once $this->root . '/core/includes/pager.inc';
532 require_once $this->root . '/core/includes/menu.inc';
533 require_once $this->root . '/core/includes/tablesort.inc';
534 require_once $this->root . '/core/includes/file.inc';
535 require_once $this->root . '/core/includes/unicode.inc';
536 require_once $this->root . '/core/includes/form.inc';
537 require_once $this->root . '/core/includes/errors.inc';
538 require_once $this->root . '/core/includes/schema.inc';
539 require_once $this->root . '/core/includes/entity.inc';
545 public function preHandle(Request $request) {
546 // Sanitize the request.
547 $request = RequestSanitizer::sanitize(
549 (array) Settings::get(RequestSanitizer::SANITIZE_WHITELIST, []),
550 (bool) Settings::get(RequestSanitizer::SANITIZE_LOG, FALSE)
553 $this->loadLegacyIncludes();
555 // Load all enabled modules.
556 $this->container->get('module_handler')->loadAll();
558 // Register stream wrappers.
559 $this->container->get('stream_wrapper_manager')->register();
561 // Initialize legacy request globals.
562 $this->initializeRequestGlobals($request);
564 // Put the request on the stack.
565 $this->container->get('request_stack')->push($request);
567 // Set the allowed protocols.
568 UrlHelper::setAllowedProtocols($this->container->getParameter('filter_protocols'));
570 // Override of Symfony's MIME type guesser singleton.
571 MimeTypeGuesser::registerWithSymfonyGuesser($this->container);
573 $this->prepared = TRUE;
579 public function discoverServiceProviders() {
580 $this->serviceYamls = [
584 $this->serviceProviderClasses = [
588 $this->serviceYamls['app']['core'] = 'core/core.services.yml';
589 $this->serviceProviderClasses['app']['core'] = 'Drupal\Core\CoreServiceProvider';
591 // Retrieve enabled modules and register their namespaces.
592 if (!isset($this->moduleList)) {
593 $extensions = $this->getConfigStorage()->read('core.extension');
594 $this->moduleList = isset($extensions['module']) ? $extensions['module'] : [];
596 $module_filenames = $this->getModuleFileNames();
597 $this->classLoaderAddMultiplePsr4($this->getModuleNamespacesPsr4($module_filenames));
599 // Load each module's serviceProvider class.
600 foreach ($module_filenames as $module => $filename) {
601 $camelized = ContainerBuilder::camelize($module);
602 $name = "{$camelized}ServiceProvider";
603 $class = "Drupal\\{$module}\\{$name}";
604 if (class_exists($class)) {
605 $this->serviceProviderClasses['app'][$module] = $class;
607 $filename = dirname($filename) . "/$module.services.yml";
608 if (file_exists($filename)) {
609 $this->serviceYamls['app'][$module] = $filename;
613 // Add site-specific service providers.
614 if (!empty($GLOBALS['conf']['container_service_providers'])) {
615 foreach ($GLOBALS['conf']['container_service_providers'] as $class) {
616 if ((is_string($class) && class_exists($class)) || (is_object($class) && ($class instanceof ServiceProviderInterface || $class instanceof ServiceModifierInterface))) {
617 $this->serviceProviderClasses['site'][] = $class;
621 $this->addServiceFiles(Settings::get('container_yamls', []));
627 public function getServiceProviders($origin) {
628 return $this->serviceProviders[$origin];
634 public function terminate(Request $request, Response $response) {
635 // Only run terminate() when essential services have been set up properly
636 // by preHandle() before.
637 if (FALSE === $this->prepared) {
641 if ($this->getHttpKernel() instanceof TerminableInterface) {
642 $this->getHttpKernel()->terminate($request, $response);
649 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
650 // Ensure sane PHP environment variables.
651 static::bootEnvironment();
654 $this->initializeSettings($request);
656 // Redirect the user to the installation script if Drupal has not been
657 // installed yet (i.e., if no $databases array has been defined in the
658 // settings.php file) and we are not already installing.
659 if (!Database::getConnectionInfo() && !drupal_installation_attempted() && PHP_SAPI !== 'cli') {
660 $response = new RedirectResponse($request->getBasePath() . '/core/install.php', 302, ['Cache-Control' => 'no-cache']);
664 $response = $this->getHttpKernel()->handle($request, $type, $catch);
667 catch (\Exception $e) {
668 if ($catch === FALSE) {
672 $response = $this->handleException($e, $request, $type);
675 // Adapt response headers to the current request.
676 $response->prepare($request);
682 * Converts an exception into a response.
684 * @param \Exception $e
686 * @param \Symfony\Component\HttpFoundation\Request $request
689 * The type of the request (one of HttpKernelInterface::MASTER_REQUEST or
690 * HttpKernelInterface::SUB_REQUEST)
692 * @return \Symfony\Component\HttpFoundation\Response
693 * A Response instance
696 * If the passed in exception cannot be turned into a response.
698 protected function handleException(\Exception $e, $request, $type) {
699 if ($this->shouldRedirectToInstaller($e, $this->container ? $this->container->get('database') : NULL)) {
700 return new RedirectResponse($request->getBasePath() . '/core/install.php', 302, ['Cache-Control' => 'no-cache']);
703 if ($e instanceof HttpExceptionInterface) {
704 $response = new Response($e->getMessage(), $e->getStatusCode());
705 $response->headers->add($e->getHeaders());
715 public function prepareLegacyRequest(Request $request) {
717 $this->preHandle($request);
718 // Setup services which are normally initialized from within stack
719 // middleware or during the request kernel event.
720 if (PHP_SAPI !== 'cli') {
721 $request->setSession($this->container->get('session'));
723 $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
724 $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
725 $this->container->get('request_stack')->push($request);
726 $this->container->get('router.request_context')->fromRequest($request);
731 * Returns module data on the filesystem.
734 * The name of the module.
736 * @return \Drupal\Core\Extension\Extension|bool
737 * Returns an Extension object if the module is found, FALSE otherwise.
739 protected function moduleData($module) {
740 if (!$this->moduleData) {
741 // First, find profiles.
742 $listing = new ExtensionDiscovery($this->root);
743 $listing->setProfileDirectories([]);
744 $all_profiles = $listing->scan('profile');
745 $profiles = array_intersect_key($all_profiles, $this->moduleList);
747 // If a module is within a profile directory but specifies another
748 // profile for testing, it needs to be found in the parent profile.
749 $settings = $this->getConfigStorage()->read('simpletest.settings');
750 $parent_profile = !empty($settings['parent_profile']) ? $settings['parent_profile'] : NULL;
751 if ($parent_profile && !isset($profiles[$parent_profile])) {
752 // In case both profile directories contain the same extension, the
753 // actual profile always has precedence.
754 $profiles = [$parent_profile => $all_profiles[$parent_profile]] + $profiles;
757 $profile_directories = array_map(function ($profile) {
758 return $profile->getPath();
760 $listing->setProfileDirectories($profile_directories);
763 $this->moduleData = $profiles + $listing->scan('module');
765 return isset($this->moduleData[$module]) ? $this->moduleData[$module] : FALSE;
769 * Implements Drupal\Core\DrupalKernelInterface::updateModules().
771 * @todo Remove obsolete $module_list parameter. Only $module_filenames is
774 public function updateModules(array $module_list, array $module_filenames = []) {
775 $pre_existing_module_namespaces = [];
776 if ($this->booted && is_array($this->moduleList)) {
777 $pre_existing_module_namespaces = $this->getModuleNamespacesPsr4($this->getModuleFileNames());
779 $this->moduleList = $module_list;
780 foreach ($module_filenames as $name => $extension) {
781 $this->moduleData[$name] = $extension;
784 // If we haven't yet booted, we don't need to do anything: the new module
785 // list will take effect when boot() is called. However we set a
786 // flag that the container needs a rebuild, so that a potentially cached
787 // container is not used. If we have already booted, then rebuild the
788 // container in order to refresh the serviceProvider list and container.
789 $this->containerNeedsRebuild = TRUE;
791 // We need to register any new namespaces to a new class loader because
792 // the current class loader might have stored a negative result for a
793 // class that is now available.
794 // @see \Composer\Autoload\ClassLoader::findFile()
795 $new_namespaces = array_diff_key(
796 $this->getModuleNamespacesPsr4($this->getModuleFileNames()),
797 $pre_existing_module_namespaces
799 if (!empty($new_namespaces)) {
800 $additional_class_loader = new ClassLoader();
801 $this->classLoaderAddMultiplePsr4($new_namespaces, $additional_class_loader);
802 $additional_class_loader->register();
805 $this->initializeContainer();
810 * Returns the container cache key based on the environment.
812 * The 'environment' consists of:
813 * - The kernel environment string.
814 * - The Drupal version constant.
815 * - The deployment identifier from settings.php. This allows custom
816 * deployments to force a container rebuild.
817 * - The operating system running PHP. This allows compiler passes to optimize
818 * services for different operating systems.
819 * - The paths to any additional container YAMLs from settings.php.
822 * The cache key used for the service container.
824 protected function getContainerCacheKey() {
825 $parts = ['service_container', $this->environment, \Drupal::VERSION, Settings::get('deployment_identifier'), PHP_OS, serialize(Settings::get('container_yamls'))];
826 return implode(':', $parts);
830 * Returns the kernel parameters.
832 * @return array An array of kernel parameters
834 protected function getKernelParameters() {
836 'kernel.environment' => $this->environment,
841 * Initializes the service container.
843 * @return \Symfony\Component\DependencyInjection\ContainerInterface
845 protected function initializeContainer() {
846 $this->containerNeedsDumping = FALSE;
847 $session_started = FALSE;
848 if (isset($this->container)) {
849 // Save the id of the currently logged in user.
850 if ($this->container->initialized('current_user')) {
851 $current_user_id = $this->container->get('current_user')->id();
854 // If there is a session, close and save it.
855 if ($this->container->initialized('session')) {
856 $session = $this->container->get('session');
857 if ($session->isStarted()) {
858 $session_started = TRUE;
865 // If we haven't booted yet but there is a container, then we're asked to
866 // boot the container injected via setContainer().
867 // @see \Drupal\KernelTests\KernelTestBase::setUp()
868 if (isset($this->container) && !$this->booted) {
869 $container = $this->container;
872 // If the module list hasn't already been set in updateModules and we are
873 // not forcing a rebuild, then try and load the container from the cache.
874 if (empty($this->moduleList) && !$this->containerNeedsRebuild) {
875 $container_definition = $this->getCachedContainerDefinition();
878 // If there is no container and no cached container definition, build a new
880 if (!isset($container) && !isset($container_definition)) {
881 // Building the container creates 1000s of objects. Garbage collection of
882 // these objects is expensive. This appears to be causing random
883 // segmentation faults in PHP 5.6 due to
884 // https://bugs.php.net/bug.php?id=72286. Once the container is rebuilt,
885 // garbage collection is re-enabled.
886 $disable_gc = version_compare(PHP_VERSION, '7', '<') && gc_enabled();
891 $container = $this->compileContainer();
893 // Only dump the container if dumping is allowed. This is useful for
894 // KernelTestBase, which never wants to use the real container, but always
895 // the container builder.
896 if ($this->allowDumping) {
897 $dumper = new $this->phpArrayDumperClass($container);
898 $container_definition = $dumper->getArray();
900 // If garbage collection was disabled prior to rebuilding container,
907 // The container was rebuilt successfully.
908 $this->containerNeedsRebuild = FALSE;
910 // Only create a new class if we have a container definition.
911 if (isset($container_definition)) {
912 $class = Settings::get('container_base_class', '\Drupal\Core\DependencyInjection\Container');
913 $container = new $class($container_definition);
916 $this->attachSynthetic($container);
918 $this->container = $container;
919 if ($session_started) {
920 $this->container->get('session')->start();
923 // The request stack is preserved across container rebuilds. Reinject the
924 // new session into the master request if one was present before.
925 if (($request_stack = $this->container->get('request_stack', ContainerInterface::NULL_ON_INVALID_REFERENCE))) {
926 if ($request = $request_stack->getMasterRequest()) {
928 if ($request->hasSession()) {
929 $request->setSession($this->container->get('session'));
934 if (!empty($current_user_id)) {
935 $this->container->get('current_user')->setInitialAccountId($current_user_id);
938 \Drupal::setContainer($this->container);
940 // Allow other parts of the codebase to react on container initialization in
942 if (!empty($subrequest)) {
943 $this->container->get('event_dispatcher')->dispatch(self::CONTAINER_INITIALIZE_SUBREQUEST_FINISHED);
946 // If needs dumping flag was set, dump the container.
947 if ($this->containerNeedsDumping && !$this->cacheDrupalContainer($container_definition)) {
948 $this->container->get('logger.factory')->get('DrupalKernel')->error('Container cannot be saved to cache.');
951 return $this->container;
955 * Setup a consistent PHP environment.
957 * This method sets PHP environment options we want to be sure are set
958 * correctly for security or just saneness.
960 * @param string $app_root
961 * (optional) The path to the application root as a string. If not supplied,
962 * the application root will be computed.
964 public static function bootEnvironment($app_root = NULL) {
965 if (static::$isEnvironmentInitialized) {
969 // Determine the application root if it's not supplied.
970 if ($app_root === NULL) {
971 $app_root = static::guessApplicationRoot();
974 // Include our bootstrap file.
975 require_once $app_root . '/core/includes/bootstrap.inc';
977 // Enforce E_STRICT, but allow users to set levels not part of E_STRICT.
978 error_reporting(E_STRICT | E_ALL);
980 // Override PHP settings required for Drupal to work properly.
981 // sites/default/default.settings.php contains more runtime settings.
982 // The .htaccess file contains settings that cannot be changed at runtime.
984 // Use session cookies, not transparent sessions that puts the session id in
986 ini_set('session.use_cookies', '1');
987 ini_set('session.use_only_cookies', '1');
988 ini_set('session.use_trans_sid', '0');
989 // Don't send HTTP headers using PHP's session handler.
990 // Send an empty string to disable the cache limiter.
991 ini_set('session.cache_limiter', '');
992 // Use httponly session cookies.
993 ini_set('session.cookie_httponly', '1');
995 // Set sane locale settings, to ensure consistent string, dates, times and
997 setlocale(LC_ALL, 'C');
999 // Detect string handling method.
1002 // Indicate that code is operating in a test child site.
1003 if (!defined('DRUPAL_TEST_IN_CHILD_SITE')) {
1004 if ($test_prefix = drupal_valid_test_ua()) {
1005 $test_db = new TestDatabase($test_prefix);
1006 // Only code that interfaces directly with tests should rely on this
1007 // constant; e.g., the error/exception handler conditionally adds further
1008 // error information into HTTP response headers that are consumed by
1009 // Simpletest's internal browser.
1010 define('DRUPAL_TEST_IN_CHILD_SITE', TRUE);
1012 // Web tests are to be conducted with runtime assertions active.
1013 assert_options(ASSERT_ACTIVE, TRUE);
1014 // Now synchronize PHP 5 and 7's handling of assertions as much as
1018 // Log fatal errors to the test site directory.
1019 ini_set('log_errors', 1);
1020 ini_set('error_log', $app_root . '/' . $test_db->getTestSitePath() . '/error.log');
1022 // Ensure that a rewritten settings.php is used if opcache is on.
1023 ini_set('opcache.validate_timestamps', 'on');
1024 ini_set('opcache.revalidate_freq', 0);
1027 // Ensure that no other code defines this.
1028 define('DRUPAL_TEST_IN_CHILD_SITE', FALSE);
1032 // Set the Drupal custom error handler.
1033 set_error_handler('_drupal_error_handler');
1034 set_exception_handler('_drupal_exception_handler');
1036 static::$isEnvironmentInitialized = TRUE;
1040 * Locate site path and initialize settings singleton.
1042 * @param \Symfony\Component\HttpFoundation\Request $request
1043 * The current request.
1045 * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
1046 * In case the host name in the request is not trusted.
1048 protected function initializeSettings(Request $request) {
1049 $site_path = static::findSitePath($request);
1050 $this->setSitePath($site_path);
1051 $class_loader_class = get_class($this->classLoader);
1052 Settings::initialize($this->root, $site_path, $this->classLoader);
1054 // Initialize our list of trusted HTTP Host headers to protect against
1056 $host_patterns = Settings::get('trusted_host_patterns', []);
1057 if (PHP_SAPI !== 'cli' && !empty($host_patterns)) {
1058 if (static::setupTrustedHosts($request, $host_patterns) === FALSE) {
1059 throw new BadRequestHttpException('The provided host name is not valid for this server.');
1063 // If the class loader is still the same, possibly
1064 // upgrade to an optimized class loader.
1065 if ($class_loader_class == get_class($this->classLoader)
1066 && Settings::get('class_loader_auto_detect', TRUE)) {
1067 $prefix = Settings::getApcuPrefix('class_loader', $this->root);
1070 // We autodetect one of the following three optimized classloaders, if
1071 // their underlying extension exists.
1072 if (function_exists('apcu_fetch')) {
1073 $loader = new ApcClassLoader($prefix, $this->classLoader);
1075 elseif (extension_loaded('wincache')) {
1076 $loader = new WinCacheClassLoader($prefix, $this->classLoader);
1078 elseif (extension_loaded('xcache')) {
1079 $loader = new XcacheClassLoader($prefix, $this->classLoader);
1081 if (!empty($loader)) {
1082 $this->classLoader->unregister();
1083 // The optimized classloader might be persistent and store cache misses.
1084 // For example, once a cache miss is stored in APCu clearing it on a
1085 // specific web-head will not clear any other web-heads. Therefore
1086 // fallback to the composer class loader that only statically caches
1088 $old_loader = $this->classLoader;
1089 $this->classLoader = $loader;
1090 // Our class loaders are preprended to ensure they come first like the
1091 // class loader they are replacing.
1092 $old_loader->register(TRUE);
1093 $loader->register(TRUE);
1099 * Bootstraps the legacy global request variables.
1101 * @param \Symfony\Component\HttpFoundation\Request $request
1102 * The current request.
1104 * @todo D8: Eliminate this entirely in favor of Request object.
1106 protected function initializeRequestGlobals(Request $request) {
1108 // Set and derived from $base_url by this function.
1109 global $base_path, $base_root;
1110 global $base_secure_url, $base_insecure_url;
1113 $base_root = $request->getSchemeAndHttpHost();
1114 $base_url = $base_root;
1116 // For a request URI of '/index.php/foo', $_SERVER['SCRIPT_NAME'] is
1117 // '/index.php', whereas $_SERVER['PHP_SELF'] is '/index.php/foo'.
1118 if ($dir = rtrim(dirname($request->server->get('SCRIPT_NAME')), '\/')) {
1119 // Remove "core" directory if present, allowing install.php,
1120 // authorize.php, and others to auto-detect a base path.
1121 $core_position = strrpos($dir, '/core');
1122 if ($core_position !== FALSE && strlen($dir) - 5 == $core_position) {
1123 $base_path = substr($dir, 0, $core_position);
1128 $base_url .= $base_path;
1134 $base_secure_url = str_replace('http://', 'https://', $base_url);
1135 $base_insecure_url = str_replace('https://', 'http://', $base_url);
1139 * Returns service instances to persist from an old container to a new one.
1141 protected function getServicesToPersist(ContainerInterface $container) {
1143 foreach ($container->getParameter('persist_ids') as $id) {
1144 // It's pointless to persist services not yet initialized.
1145 if ($container->initialized($id)) {
1146 $persist[$id] = $container->get($id);
1153 * Moves persistent service instances into a new container.
1155 protected function persistServices(ContainerInterface $container, array $persist) {
1156 foreach ($persist as $id => $object) {
1157 // Do not override services already set() on the new container, for
1158 // example 'service_container'.
1159 if (!$container->initialized($id)) {
1160 $container->set($id, $object);
1168 public function rebuildContainer() {
1169 // Empty module properties and for them to be reloaded from scratch.
1170 $this->moduleList = NULL;
1171 $this->moduleData = [];
1172 $this->containerNeedsRebuild = TRUE;
1173 return $this->initializeContainer();
1179 public function invalidateContainer() {
1180 // An invalidated container needs a rebuild.
1181 $this->containerNeedsRebuild = TRUE;
1183 // If we have not yet booted, settings or bootstrap services might not yet
1184 // be available. In that case the container will not be loaded from cache
1185 // due to the above setting when the Kernel is booted.
1186 if (!$this->booted) {
1190 // Also remove the container definition from the cache backend.
1191 $this->bootstrapContainer->get('cache.container')->deleteAll();
1195 * Attach synthetic values on to kernel.
1197 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
1200 * @return \Symfony\Component\DependencyInjection\ContainerInterface
1202 protected function attachSynthetic(ContainerInterface $container) {
1204 if (isset($this->container)) {
1205 $persist = $this->getServicesToPersist($this->container);
1207 $this->persistServices($container, $persist);
1209 // All namespaces must be registered before we attempt to use any service
1210 // from the container.
1211 $this->classLoaderAddMultiplePsr4($container->getParameter('container.namespaces'));
1213 $container->set('kernel', $this);
1215 // Set the class loader which was registered as a synthetic service.
1216 $container->set('class_loader', $this->classLoader);
1221 * Compiles a new service container.
1223 * @return \Drupal\Core\DependencyInjection\ContainerBuilder The compiled service container
1225 protected function compileContainer() {
1226 // We are forcing a container build so it is reasonable to assume that the
1227 // calling method knows something about the system has changed requiring the
1228 // container to be dumped to the filesystem.
1229 if ($this->allowDumping) {
1230 $this->containerNeedsDumping = TRUE;
1233 $this->initializeServiceProviders();
1234 $container = $this->getContainerBuilder();
1235 $container->set('kernel', $this);
1236 $container->setParameter('container.modules', $this->getModulesParameter());
1237 $container->setParameter('install_profile', $this->getInstallProfile());
1239 // Get a list of namespaces and put it onto the container.
1240 $namespaces = $this->getModuleNamespacesPsr4($this->getModuleFileNames());
1241 // Add all components in \Drupal\Core and \Drupal\Component that have one of
1242 // the following directories:
1246 foreach (['Core', 'Component'] as $parent_directory) {
1247 $path = 'core/lib/Drupal/' . $parent_directory;
1248 $parent_namespace = 'Drupal\\' . $parent_directory;
1249 foreach (new \DirectoryIterator($this->root . '/' . $path) as $component) {
1250 /** @var $component \DirectoryIterator */
1251 $pathname = $component->getPathname();
1252 if (!$component->isDot() && $component->isDir() && (
1253 is_dir($pathname . '/Plugin') ||
1254 is_dir($pathname . '/Entity') ||
1255 is_dir($pathname . '/Element')
1257 $namespaces[$parent_namespace . '\\' . $component->getFilename()] = $path . '/' . $component->getFilename();
1261 $container->setParameter('container.namespaces', $namespaces);
1263 // Store the default language values on the container. This is so that the
1264 // default language can be configured using the configuration factory. This
1265 // avoids the circular dependencies that would created by
1266 // \Drupal\language\LanguageServiceProvider::alter() and allows the default
1267 // language to not be English in the installer.
1268 $default_language_values = Language::$defaultValues;
1269 if ($system = $this->getConfigStorage()->read('system.site')) {
1270 if ($default_language_values['id'] != $system['langcode']) {
1271 $default_language_values = ['id' => $system['langcode']];
1274 $container->setParameter('language.default_values', $default_language_values);
1276 // Register synthetic services.
1277 $container->register('class_loader')->setSynthetic(TRUE);
1278 $container->register('kernel', 'Symfony\Component\HttpKernel\KernelInterface')->setSynthetic(TRUE);
1279 $container->register('service_container', 'Symfony\Component\DependencyInjection\ContainerInterface')->setSynthetic(TRUE);
1281 // Register application services.
1282 $yaml_loader = new YamlFileLoader($container);
1283 foreach ($this->serviceYamls['app'] as $filename) {
1284 $yaml_loader->load($filename);
1286 foreach ($this->serviceProviders['app'] as $provider) {
1287 if ($provider instanceof ServiceProviderInterface) {
1288 $provider->register($container);
1291 // Register site-specific service overrides.
1292 foreach ($this->serviceYamls['site'] as $filename) {
1293 $yaml_loader->load($filename);
1295 foreach ($this->serviceProviders['site'] as $provider) {
1296 if ($provider instanceof ServiceProviderInterface) {
1297 $provider->register($container);
1301 // Identify all services whose instances should be persisted when rebuilding
1302 // the container during the lifetime of the kernel (e.g., during a kernel
1303 // reboot). Include synthetic services, because by definition, they cannot
1304 // be automatically reinstantiated. Also include services tagged to persist.
1306 foreach ($container->getDefinitions() as $id => $definition) {
1307 // It does not make sense to persist the container itself, exclude it.
1308 if ($id !== 'service_container' && ($definition->isSynthetic() || $definition->getTag('persist'))) {
1309 $persist_ids[] = $id;
1312 $container->setParameter('persist_ids', $persist_ids);
1314 $container->compile();
1319 * Registers all service providers to the kernel.
1321 * @throws \LogicException
1323 protected function initializeServiceProviders() {
1324 $this->discoverServiceProviders();
1325 $this->serviceProviders = [
1329 foreach ($this->serviceProviderClasses as $origin => $classes) {
1330 foreach ($classes as $name => $class) {
1331 if (!is_object($class)) {
1332 $this->serviceProviders[$origin][$name] = new $class();
1335 $this->serviceProviders[$origin][$name] = $class;
1342 * Gets a new ContainerBuilder instance used to build the service container.
1344 * @return \Drupal\Core\DependencyInjection\ContainerBuilder
1346 protected function getContainerBuilder() {
1347 return new ContainerBuilder(new ParameterBag($this->getKernelParameters()));
1351 * Stores the container definition in a cache.
1353 * @param array $container_definition
1354 * The container definition to cache.
1357 * TRUE if the container was successfully cached.
1359 protected function cacheDrupalContainer(array $container_definition) {
1362 $this->bootstrapContainer->get('cache.container')->set($this->getContainerCacheKey(), $container_definition);
1364 catch (\Exception $e) {
1365 // There is no way to get from the Cache API if the cache set was
1366 // successful or not, hence an Exception is caught and the caller informed
1367 // about the error condition.
1375 * Gets a http kernel from the container
1377 * @return \Symfony\Component\HttpKernel\HttpKernelInterface
1379 protected function getHttpKernel() {
1380 return $this->container->get('http_kernel');
1384 * Returns the active configuration storage to use during building the container.
1386 * @return \Drupal\Core\Config\StorageInterface
1388 protected function getConfigStorage() {
1389 if (!isset($this->configStorage)) {
1390 // The active configuration storage may not exist yet; e.g., in the early
1391 // installer. Catch the exception thrown by config_get_config_directory().
1393 $this->configStorage = BootstrapConfigStorageFactory::get($this->classLoader);
1395 catch (\Exception $e) {
1396 $this->configStorage = new NullStorage();
1399 return $this->configStorage;
1403 * Returns an array of Extension class parameters for all enabled modules.
1407 protected function getModulesParameter() {
1409 foreach ($this->moduleList as $name => $weight) {
1410 if ($data = $this->moduleData($name)) {
1411 $extensions[$name] = [
1412 'type' => $data->getType(),
1413 'pathname' => $data->getPathname(),
1414 'filename' => $data->getExtensionFilename(),
1422 * Gets the file name for each enabled module.
1425 * Array where each key is a module name, and each value is a path to the
1426 * respective *.info.yml file.
1428 protected function getModuleFileNames() {
1430 foreach ($this->moduleList as $module => $weight) {
1431 if ($data = $this->moduleData($module)) {
1432 $filenames[$module] = $data->getPathname();
1439 * Gets the PSR-4 base directories for module namespaces.
1441 * @param string[] $module_file_names
1442 * Array where each key is a module name, and each value is a path to the
1443 * respective *.info.yml file.
1446 * Array where each key is a module namespace like 'Drupal\system', and each
1447 * value is the PSR-4 base directory associated with the module namespace.
1449 protected function getModuleNamespacesPsr4($module_file_names) {
1451 foreach ($module_file_names as $module => $filename) {
1452 $namespaces["Drupal\\$module"] = dirname($filename) . '/src';
1458 * Registers a list of namespaces with PSR-4 directories for class loading.
1460 * @param array $namespaces
1461 * Array where each key is a namespace like 'Drupal\system', and each value
1462 * is either a PSR-4 base directory, or an array of PSR-4 base directories
1463 * associated with this namespace.
1464 * @param object $class_loader
1465 * The class loader. Normally \Composer\Autoload\ClassLoader, as included by
1466 * the front controller, but may also be decorated; e.g.,
1467 * \Symfony\Component\ClassLoader\ApcClassLoader.
1469 protected function classLoaderAddMultiplePsr4(array $namespaces = [], $class_loader = NULL) {
1470 if ($class_loader === NULL) {
1471 $class_loader = $this->classLoader;
1473 foreach ($namespaces as $prefix => $paths) {
1474 if (is_array($paths)) {
1475 foreach ($paths as $key => $value) {
1476 $paths[$key] = $this->root . '/' . $value;
1479 elseif (is_string($paths)) {
1480 $paths = $this->root . '/' . $paths;
1482 $class_loader->addPsr4($prefix . '\\', $paths);
1487 * Validates a hostname length.
1489 * @param string $host
1493 * TRUE if the length is appropriate, or FALSE otherwise.
1495 protected static function validateHostnameLength($host) {
1496 // Limit the length of the host name to 1000 bytes to prevent DoS attacks
1497 // with long host names.
1498 return strlen($host) <= 1000
1499 // Limit the number of subdomains and port separators to prevent DoS attacks
1500 // in findSitePath().
1501 && substr_count($host, '.') <= 100
1502 && substr_count($host, ':') <= 100;
1506 * Validates the hostname supplied from the HTTP request.
1508 * @param \Symfony\Component\HttpFoundation\Request $request
1509 * The request object
1512 * TRUE if the hostname is valid, or FALSE otherwise.
1514 public static function validateHostname(Request $request) {
1515 // $request->getHost() can throw an UnexpectedValueException if it
1516 // detects a bad hostname, but it does not validate the length.
1518 $http_host = $request->getHost();
1520 catch (\UnexpectedValueException $e) {
1524 if (static::validateHostnameLength($http_host) === FALSE) {
1532 * Sets up the lists of trusted HTTP Host headers.
1534 * Since the HTTP Host header can be set by the user making the request, it
1535 * is possible to create an attack vectors against a site by overriding this.
1536 * Symfony provides a mechanism for creating a list of trusted Host values.
1538 * Host patterns (as regular expressions) can be configured through
1539 * settings.php for multisite installations, sites using ServerAlias without
1540 * canonical redirection, or configurations where the site responds to default
1541 * requests. For example,
1544 * $settings['trusted_host_patterns'] = array(
1546 * '^*.example\.com$',
1550 * @param \Symfony\Component\HttpFoundation\Request $request
1551 * The request object.
1552 * @param array $host_patterns
1553 * The array of trusted host patterns.
1556 * TRUE if the Host header is trusted, FALSE otherwise.
1558 * @see https://www.drupal.org/node/1992030
1559 * @see \Drupal\Core\Http\TrustedHostsRequestFactory
1561 protected static function setupTrustedHosts(Request $request, $host_patterns) {
1562 $request->setTrustedHosts($host_patterns);
1564 // Get the host, which will validate the current request.
1566 $host = $request->getHost();
1568 // Fake requests created through Request::create() without passing in the
1569 // server variables from the main request have a default host of
1570 // 'localhost'. If 'localhost' does not match any of the trusted host
1571 // patterns these fake requests would fail the host verification. Instead,
1572 // TrustedHostsRequestFactory makes sure to pass in the server variables
1573 // from the main request.
1574 $request_factory = new TrustedHostsRequestFactory($host);
1575 Request::setFactory([$request_factory, 'createRequest']);
1578 catch (\UnexpectedValueException $e) {
1586 * Add service files.
1588 * @param string[] $service_yamls
1589 * A list of service files.
1591 protected function addServiceFiles(array $service_yamls) {
1592 $this->serviceYamls['site'] = array_filter($service_yamls, 'file_exists');
1596 * Gets the active install profile.
1598 * @return string|null
1599 * The name of the any active install profile or distribution.
1601 protected function getInstallProfile() {
1602 $config = $this->getConfigStorage()->read('core.extension');
1603 if (!empty($config['profile'])) {
1604 $install_profile = $config['profile'];
1606 // @todo https://www.drupal.org/node/2831065 remove the BC layer.
1608 // If system_update_8300() has not yet run fallback to using settings.
1609 $install_profile = Settings::get('install_profile');
1612 // Normalize an empty string to a NULL value.
1613 return empty($install_profile) ? NULL : $install_profile;