5 use Composer\Autoload\ClassLoader;
6 use Drupal\Component\Assertion\Handle;
7 use Drupal\Component\FileCache\FileCacheFactory;
8 use Drupal\Component\Utility\Unicode;
9 use Drupal\Component\Utility\UrlHelper;
10 use Drupal\Core\Config\BootstrapConfigStorageFactory;
11 use Drupal\Core\Config\NullStorage;
12 use Drupal\Core\Database\Database;
13 use Drupal\Core\DependencyInjection\ContainerBuilder;
14 use Drupal\Core\DependencyInjection\ServiceModifierInterface;
15 use Drupal\Core\DependencyInjection\ServiceProviderInterface;
16 use Drupal\Core\DependencyInjection\YamlFileLoader;
17 use Drupal\Core\Extension\ExtensionDiscovery;
18 use Drupal\Core\File\MimeType\MimeTypeGuesser;
19 use Drupal\Core\Http\TrustedHostsRequestFactory;
20 use Drupal\Core\Installer\InstallerRedirectTrait;
21 use Drupal\Core\Language\Language;
22 use Drupal\Core\Site\Settings;
23 use Drupal\Core\Test\TestDatabase;
24 use Symfony\Cmf\Component\Routing\RouteObjectInterface;
25 use Symfony\Component\ClassLoader\ApcClassLoader;
26 use Symfony\Component\ClassLoader\WinCacheClassLoader;
27 use Symfony\Component\ClassLoader\XcacheClassLoader;
28 use Symfony\Component\DependencyInjection\ContainerInterface;
29 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
30 use Symfony\Component\HttpFoundation\RedirectResponse;
31 use Symfony\Component\HttpFoundation\Request;
32 use Symfony\Component\HttpFoundation\Response;
33 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
34 use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
35 use Symfony\Component\HttpKernel\TerminableInterface;
36 use Symfony\Component\Routing\Route;
39 * The DrupalKernel class is the core of Drupal itself.
41 * This class is responsible for building the Dependency Injection Container and
42 * also deals with the registration of service providers. It allows registered
43 * service providers to add their services to the container. Core provides the
44 * CoreServiceProvider, which, in addition to registering any core services that
45 * cannot be registered in the core.services.yaml file, adds any compiler passes
46 * needed by core, e.g. for processing tagged services. Each module can add its
47 * own service provider, i.e. a class implementing
48 * Drupal\Core\DependencyInjection\ServiceProvider, to register services to the
49 * container, or modify existing services.
51 class DrupalKernel implements DrupalKernelInterface, TerminableInterface {
52 use InstallerRedirectTrait;
55 * Holds the class used for dumping the container to a PHP array.
57 * In combination with swapping the container class this is useful to e.g.
58 * dump to the human-readable PHP array format to debug the container
59 * definition in an easier way.
63 protected $phpArrayDumperClass = '\Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper';
66 * Holds the default bootstrap container definition.
70 protected $defaultBootstrapContainerDefinition = [
74 'class' => 'Drupal\Core\Database\Connection',
75 'factory' => 'Drupal\Core\Database\Database::getConnection',
76 'arguments' => ['default'],
78 'cache.container' => [
79 'class' => 'Drupal\Core\Cache\DatabaseBackend',
80 'arguments' => ['@database', '@cache_tags_provider.container', 'container'],
82 'cache_tags_provider.container' => [
83 'class' => 'Drupal\Core\Cache\DatabaseCacheTagsChecksum',
84 'arguments' => ['@database'],
90 * Holds the class used for instantiating the bootstrap container.
94 protected $bootstrapContainerClass = '\Drupal\Component\DependencyInjection\PhpArrayContainer';
97 * Holds the bootstrap container.
99 * @var \Symfony\Component\DependencyInjection\ContainerInterface
101 protected $bootstrapContainer;
104 * Holds the container instance.
106 * @var \Symfony\Component\DependencyInjection\ContainerInterface
108 protected $container;
111 * The environment, e.g. 'testing', 'install'.
115 protected $environment;
118 * Whether the kernel has been booted.
122 protected $booted = FALSE;
125 * Whether essential services have been set up properly by preHandle().
129 protected $prepared = FALSE;
132 * Holds the list of enabled modules.
135 * An associative array whose keys are module names and whose values are
138 protected $moduleList;
141 * List of available modules and installation profiles.
143 * @var \Drupal\Core\Extension\Extension[]
145 protected $moduleData = [];
148 * The class loader object.
150 * @var \Composer\Autoload\ClassLoader
152 protected $classLoader;
155 * Config storage object used for reading enabled modules configuration.
157 * @var \Drupal\Core\Config\StorageInterface
159 protected $configStorage;
162 * Whether the container can be dumped.
166 protected $allowDumping;
169 * Whether the container needs to be rebuilt the next time it is initialized.
173 protected $containerNeedsRebuild = FALSE;
176 * Whether the container needs to be dumped once booting is complete.
180 protected $containerNeedsDumping;
183 * List of discovered services.yml pathnames.
185 * This is a nested array whose top-level keys are 'app' and 'site', denoting
186 * the origin of a service provider. Site-specific providers have to be
187 * collected separately, because they need to be processed last, so as to be
188 * able to override services from application service providers.
192 protected $serviceYamls;
195 * List of discovered service provider class names or objects.
197 * This is a nested array whose top-level keys are 'app' and 'site', denoting
198 * the origin of a service provider. Site-specific providers have to be
199 * collected separately, because they need to be processed last, so as to be
200 * able to override services from application service providers.
202 * Allowing objects is for example used to allow
203 * \Drupal\KernelTests\KernelTestBase to register itself as service provider.
207 protected $serviceProviderClasses;
210 * List of instantiated service provider classes.
212 * @see \Drupal\Core\DrupalKernel::$serviceProviderClasses
216 protected $serviceProviders;
219 * Whether the PHP environment has been initialized.
221 * This legacy phase can only be booted once because it sets session INI
222 * settings. If a session has already been started, re-generating these
223 * settings would break the session.
227 protected static $isEnvironmentInitialized = FALSE;
230 * The site directory.
244 * Create a DrupalKernel object from a request.
246 * @param \Symfony\Component\HttpFoundation\Request $request
248 * @param $class_loader
249 * The class loader. Normally Composer's ClassLoader, as included by the
250 * front controller, but may also be decorated; e.g.,
251 * \Symfony\Component\ClassLoader\ApcClassLoader.
252 * @param string $environment
253 * String indicating the environment, e.g. 'prod' or 'dev'.
254 * @param bool $allow_dumping
255 * (optional) FALSE to stop the container from being written to or read
256 * from disk. Defaults to TRUE.
257 * @param string $app_root
258 * (optional) The path to the application root as a string. If not supplied,
259 * the application root will be computed.
263 * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
264 * In case the host name in the request is not trusted.
266 public static function createFromRequest(Request $request, $class_loader, $environment, $allow_dumping = TRUE, $app_root = NULL) {
267 $kernel = new static($environment, $class_loader, $allow_dumping, $app_root);
268 static::bootEnvironment($app_root);
269 $kernel->initializeSettings($request);
274 * Constructs a DrupalKernel object.
276 * @param string $environment
277 * String indicating the environment, e.g. 'prod' or 'dev'.
278 * @param $class_loader
279 * The class loader. Normally \Composer\Autoload\ClassLoader, as included by
280 * the front controller, but may also be decorated; e.g.,
281 * \Symfony\Component\ClassLoader\ApcClassLoader.
282 * @param bool $allow_dumping
283 * (optional) FALSE to stop the container from being written to or read
284 * from disk. Defaults to TRUE.
285 * @param string $app_root
286 * (optional) The path to the application root as a string. If not supplied,
287 * the application root will be computed.
289 public function __construct($environment, $class_loader, $allow_dumping = TRUE, $app_root = NULL) {
290 $this->environment = $environment;
291 $this->classLoader = $class_loader;
292 $this->allowDumping = $allow_dumping;
293 if ($app_root === NULL) {
294 $app_root = static::guessApplicationRoot();
296 $this->root = $app_root;
300 * Determine the application root directory based on assumptions.
303 * The application root.
305 protected static function guessApplicationRoot() {
306 return dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
310 * Returns the appropriate site directory for a request.
312 * Once the kernel has been created DrupalKernelInterface::getSitePath() is
313 * preferred since it gets the statically cached result of this method.
315 * Site directories contain all site specific code. This includes settings.php
316 * for bootstrap level configuration, file configuration stores, public file
317 * storage and site specific modules and themes.
319 * Finds a matching site directory file by stripping the website's hostname
320 * from left to right and pathname from right to left. By default, the
321 * directory must contain a 'settings.php' file for it to match. If the
322 * parameter $require_settings is set to FALSE, then a directory without a
323 * 'settings.php' file will match as well. The first configuration file found
324 * will be used and the remaining ones will be ignored. If no configuration
325 * file is found, returns a default value 'sites/default'. See
326 * default.settings.php for examples on how the URL is converted to a
329 * If a file named sites.php is present in the sites directory, it will be
330 * loaded prior to scanning for directories. That file can define aliases in
331 * an associative array named $sites. The array is written in the format
332 * '<port>.<domain>.<path>' => 'directory'. As an example, to create a
333 * directory alias for https://www.drupal.org:8080/mysite/test whose
334 * configuration file is in sites/example.com, the array should be defined as:
337 * '8080.www.drupal.org.mysite.test' => 'example.com',
341 * @param \Symfony\Component\HttpFoundation\Request $request
342 * The current request.
343 * @param bool $require_settings
344 * Only directories with an existing settings.php file will be recognized.
345 * Defaults to TRUE. During initial installation, this is set to FALSE so
346 * that Drupal can detect a matching directory, then create a new
347 * settings.php file in it.
348 * @param string $app_root
349 * (optional) The path to the application root as a string. If not supplied,
350 * the application root will be computed.
353 * The path of the matching directory.
355 * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
356 * In case the host name in the request is invalid.
358 * @see \Drupal\Core\DrupalKernelInterface::getSitePath()
359 * @see \Drupal\Core\DrupalKernelInterface::setSitePath()
360 * @see default.settings.php
361 * @see example.sites.php
363 public static function findSitePath(Request $request, $require_settings = TRUE, $app_root = NULL) {
364 if (static::validateHostname($request) === FALSE) {
365 throw new BadRequestHttpException();
368 if ($app_root === NULL) {
369 $app_root = static::guessApplicationRoot();
372 // Check for a simpletest override.
373 if ($test_prefix = drupal_valid_test_ua()) {
374 $test_db = new TestDatabase($test_prefix);
375 return $test_db->getTestSitePath();
378 // Determine whether multi-site functionality is enabled.
379 if (!file_exists($app_root . '/sites/sites.php')) {
380 return 'sites/default';
383 // Otherwise, use find the site path using the request.
384 $script_name = $request->server->get('SCRIPT_NAME');
386 $script_name = $request->server->get('SCRIPT_FILENAME');
388 $http_host = $request->getHttpHost();
391 include $app_root . '/sites/sites.php';
393 $uri = explode('/', $script_name);
394 $server = explode('.', implode('.', array_reverse(explode(':', rtrim($http_host, '.')))));
395 for ($i = count($uri) - 1; $i > 0; $i--) {
396 for ($j = count($server); $j > 0; $j--) {
397 $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
398 if (isset($sites[$dir]) && file_exists($app_root . '/sites/' . $sites[$dir])) {
401 if (file_exists($app_root . '/sites/' . $dir . '/settings.php') || (!$require_settings && file_exists($app_root . '/sites/' . $dir))) {
406 return 'sites/default';
412 public function setSitePath($path) {
414 throw new \LogicException('Site path cannot be changed after calling boot()');
416 $this->sitePath = $path;
422 public function getSitePath() {
423 return $this->sitePath;
429 public function getAppRoot() {
436 public function boot() {
441 // Ensure that findSitePath is set.
442 if (!$this->sitePath) {
443 throw new \Exception('Kernel does not have site path set before calling boot()');
446 // Initialize the FileCacheFactory component. We have to do it here instead
447 // of in \Drupal\Component\FileCache\FileCacheFactory because we can not use
448 // the Settings object in a component.
449 $configuration = Settings::get('file_cache');
451 // Provide a default configuration, if not set.
452 if (!isset($configuration['default'])) {
453 // @todo Use extension_loaded('apcu') for non-testbot
454 // https://www.drupal.org/node/2447753.
455 if (function_exists('apcu_fetch')) {
456 $configuration['default']['cache_backend_class'] = '\Drupal\Component\FileCache\ApcuFileCacheBackend';
459 FileCacheFactory::setConfiguration($configuration);
460 FileCacheFactory::setPrefix(Settings::getApcuPrefix('file_cache', $this->root));
462 $this->bootstrapContainer = new $this->bootstrapContainerClass(Settings::get('bootstrap_container_definition', $this->defaultBootstrapContainerDefinition));
464 // Initialize the container.
465 $this->initializeContainer();
467 $this->booted = TRUE;
475 public function shutdown() {
476 if (FALSE === $this->booted) {
479 $this->container->get('stream_wrapper_manager')->unregister();
480 $this->booted = FALSE;
481 $this->container = NULL;
482 $this->moduleList = NULL;
483 $this->moduleData = [];
489 public function getContainer() {
490 return $this->container;
496 public function setContainer(ContainerInterface $container = NULL) {
497 if (isset($this->container)) {
498 throw new \Exception('The container should not override an existing container.');
501 throw new \Exception('The container cannot be set after a booted kernel.');
504 $this->container = $container;
511 public function getCachedContainerDefinition() {
512 $cache = $this->bootstrapContainer->get('cache.container')->get($this->getContainerCacheKey());
524 public function loadLegacyIncludes() {
525 require_once $this->root . '/core/includes/common.inc';
526 require_once $this->root . '/core/includes/database.inc';
527 require_once $this->root . '/core/includes/module.inc';
528 require_once $this->root . '/core/includes/theme.inc';
529 require_once $this->root . '/core/includes/pager.inc';
530 require_once $this->root . '/core/includes/menu.inc';
531 require_once $this->root . '/core/includes/tablesort.inc';
532 require_once $this->root . '/core/includes/file.inc';
533 require_once $this->root . '/core/includes/unicode.inc';
534 require_once $this->root . '/core/includes/form.inc';
535 require_once $this->root . '/core/includes/errors.inc';
536 require_once $this->root . '/core/includes/schema.inc';
537 require_once $this->root . '/core/includes/entity.inc';
543 public function preHandle(Request $request) {
545 $this->loadLegacyIncludes();
547 // Load all enabled modules.
548 $this->container->get('module_handler')->loadAll();
550 // Register stream wrappers.
551 $this->container->get('stream_wrapper_manager')->register();
553 // Initialize legacy request globals.
554 $this->initializeRequestGlobals($request);
556 // Put the request on the stack.
557 $this->container->get('request_stack')->push($request);
559 // Set the allowed protocols.
560 UrlHelper::setAllowedProtocols($this->container->getParameter('filter_protocols'));
562 // Override of Symfony's MIME type guesser singleton.
563 MimeTypeGuesser::registerWithSymfonyGuesser($this->container);
565 $this->prepared = TRUE;
571 public function discoverServiceProviders() {
572 $this->serviceYamls = [
576 $this->serviceProviderClasses = [
580 $this->serviceYamls['app']['core'] = 'core/core.services.yml';
581 $this->serviceProviderClasses['app']['core'] = 'Drupal\Core\CoreServiceProvider';
583 // Retrieve enabled modules and register their namespaces.
584 if (!isset($this->moduleList)) {
585 $extensions = $this->getConfigStorage()->read('core.extension');
586 $this->moduleList = isset($extensions['module']) ? $extensions['module'] : [];
588 $module_filenames = $this->getModuleFileNames();
589 $this->classLoaderAddMultiplePsr4($this->getModuleNamespacesPsr4($module_filenames));
591 // Load each module's serviceProvider class.
592 foreach ($module_filenames as $module => $filename) {
593 $camelized = ContainerBuilder::camelize($module);
594 $name = "{$camelized}ServiceProvider";
595 $class = "Drupal\\{$module}\\{$name}";
596 if (class_exists($class)) {
597 $this->serviceProviderClasses['app'][$module] = $class;
599 $filename = dirname($filename) . "/$module.services.yml";
600 if (file_exists($filename)) {
601 $this->serviceYamls['app'][$module] = $filename;
605 // Add site-specific service providers.
606 if (!empty($GLOBALS['conf']['container_service_providers'])) {
607 foreach ($GLOBALS['conf']['container_service_providers'] as $class) {
608 if ((is_string($class) && class_exists($class)) || (is_object($class) && ($class instanceof ServiceProviderInterface || $class instanceof ServiceModifierInterface))) {
609 $this->serviceProviderClasses['site'][] = $class;
613 $this->addServiceFiles(Settings::get('container_yamls', []));
619 public function getServiceProviders($origin) {
620 return $this->serviceProviders[$origin];
626 public function terminate(Request $request, Response $response) {
627 // Only run terminate() when essential services have been set up properly
628 // by preHandle() before.
629 if (FALSE === $this->prepared) {
633 if ($this->getHttpKernel() instanceof TerminableInterface) {
634 $this->getHttpKernel()->terminate($request, $response);
641 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
642 // Ensure sane PHP environment variables.
643 static::bootEnvironment();
646 $this->initializeSettings($request);
648 // Redirect the user to the installation script if Drupal has not been
649 // installed yet (i.e., if no $databases array has been defined in the
650 // settings.php file) and we are not already installing.
651 if (!Database::getConnectionInfo() && !drupal_installation_attempted() && PHP_SAPI !== 'cli') {
652 $response = new RedirectResponse($request->getBasePath() . '/core/install.php', 302, ['Cache-Control' => 'no-cache']);
656 $response = $this->getHttpKernel()->handle($request, $type, $catch);
659 catch (\Exception $e) {
660 if ($catch === FALSE) {
664 $response = $this->handleException($e, $request, $type);
667 // Adapt response headers to the current request.
668 $response->prepare($request);
674 * Converts an exception into a response.
676 * @param \Exception $e
678 * @param Request $request
681 * The type of the request (one of HttpKernelInterface::MASTER_REQUEST or
682 * HttpKernelInterface::SUB_REQUEST)
685 * A Response instance
688 * If the passed in exception cannot be turned into a response.
690 protected function handleException(\Exception $e, $request, $type) {
691 if ($this->shouldRedirectToInstaller($e, $this->container ? $this->container->get('database') : NULL)) {
692 return new RedirectResponse($request->getBasePath() . '/core/install.php', 302, ['Cache-Control' => 'no-cache']);
695 if ($e instanceof HttpExceptionInterface) {
696 $response = new Response($e->getMessage(), $e->getStatusCode());
697 $response->headers->add($e->getHeaders());
707 public function prepareLegacyRequest(Request $request) {
709 $this->preHandle($request);
710 // Setup services which are normally initialized from within stack
711 // middleware or during the request kernel event.
712 if (PHP_SAPI !== 'cli') {
713 $request->setSession($this->container->get('session'));
715 $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
716 $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
717 $this->container->get('request_stack')->push($request);
718 $this->container->get('router.request_context')->fromRequest($request);
723 * Returns module data on the filesystem.
726 * The name of the module.
728 * @return \Drupal\Core\Extension\Extension|bool
729 * Returns an Extension object if the module is found, FALSE otherwise.
731 protected function moduleData($module) {
732 if (!$this->moduleData) {
733 // First, find profiles.
734 $listing = new ExtensionDiscovery($this->root);
735 $listing->setProfileDirectories([]);
736 $all_profiles = $listing->scan('profile');
737 $profiles = array_intersect_key($all_profiles, $this->moduleList);
739 // If a module is within a profile directory but specifies another
740 // profile for testing, it needs to be found in the parent profile.
741 $settings = $this->getConfigStorage()->read('simpletest.settings');
742 $parent_profile = !empty($settings['parent_profile']) ? $settings['parent_profile'] : NULL;
743 if ($parent_profile && !isset($profiles[$parent_profile])) {
744 // In case both profile directories contain the same extension, the
745 // actual profile always has precedence.
746 $profiles = [$parent_profile => $all_profiles[$parent_profile]] + $profiles;
749 $profile_directories = array_map(function ($profile) {
750 return $profile->getPath();
752 $listing->setProfileDirectories($profile_directories);
755 $this->moduleData = $profiles + $listing->scan('module');
757 return isset($this->moduleData[$module]) ? $this->moduleData[$module] : FALSE;
761 * Implements Drupal\Core\DrupalKernelInterface::updateModules().
763 * @todo Remove obsolete $module_list parameter. Only $module_filenames is
766 public function updateModules(array $module_list, array $module_filenames = []) {
767 $pre_existing_module_namespaces = [];
768 if ($this->booted && is_array($this->moduleList)) {
769 $pre_existing_module_namespaces = $this->getModuleNamespacesPsr4($this->getModuleFileNames());
771 $this->moduleList = $module_list;
772 foreach ($module_filenames as $name => $extension) {
773 $this->moduleData[$name] = $extension;
776 // If we haven't yet booted, we don't need to do anything: the new module
777 // list will take effect when boot() is called. However we set a
778 // flag that the container needs a rebuild, so that a potentially cached
779 // container is not used. If we have already booted, then rebuild the
780 // container in order to refresh the serviceProvider list and container.
781 $this->containerNeedsRebuild = TRUE;
783 // We need to register any new namespaces to a new class loader because
784 // the current class loader might have stored a negative result for a
785 // class that is now available.
786 // @see \Composer\Autoload\ClassLoader::findFile()
787 $new_namespaces = array_diff_key(
788 $this->getModuleNamespacesPsr4($this->getModuleFileNames()),
789 $pre_existing_module_namespaces
791 if (!empty($new_namespaces)) {
792 $additional_class_loader = new ClassLoader();
793 $this->classLoaderAddMultiplePsr4($new_namespaces, $additional_class_loader);
794 $additional_class_loader->register();
797 $this->initializeContainer();
802 * Returns the container cache key based on the environment.
804 * The 'environment' consists of:
805 * - The kernel environment string.
806 * - The Drupal version constant.
807 * - The deployment identifier from settings.php. This allows custom
808 * deployments to force a container rebuild.
809 * - The operating system running PHP. This allows compiler passes to optimize
810 * services for different operating systems.
811 * - The paths to any additional container YAMLs from settings.php.
814 * The cache key used for the service container.
816 protected function getContainerCacheKey() {
817 $parts = ['service_container', $this->environment, \Drupal::VERSION, Settings::get('deployment_identifier'), PHP_OS, serialize(Settings::get('container_yamls'))];
818 return implode(':', $parts);
822 * Returns the kernel parameters.
824 * @return array An array of kernel parameters
826 protected function getKernelParameters() {
828 'kernel.environment' => $this->environment,
833 * Initializes the service container.
835 * @return \Symfony\Component\DependencyInjection\ContainerInterface
837 protected function initializeContainer() {
838 $this->containerNeedsDumping = FALSE;
839 $session_started = FALSE;
840 if (isset($this->container)) {
841 // Save the id of the currently logged in user.
842 if ($this->container->initialized('current_user')) {
843 $current_user_id = $this->container->get('current_user')->id();
846 // If there is a session, close and save it.
847 if ($this->container->initialized('session')) {
848 $session = $this->container->get('session');
849 if ($session->isStarted()) {
850 $session_started = TRUE;
857 // If we haven't booted yet but there is a container, then we're asked to
858 // boot the container injected via setContainer().
859 // @see \Drupal\KernelTests\KernelTestBase::setUp()
860 if (isset($this->container) && !$this->booted) {
861 $container = $this->container;
864 // If the module list hasn't already been set in updateModules and we are
865 // not forcing a rebuild, then try and load the container from the cache.
866 if (empty($this->moduleList) && !$this->containerNeedsRebuild) {
867 $container_definition = $this->getCachedContainerDefinition();
870 // If there is no container and no cached container definition, build a new
872 if (!isset($container) && !isset($container_definition)) {
873 // Building the container creates 1000s of objects. Garbage collection of
874 // these objects is expensive. This appears to be causing random
875 // segmentation faults in PHP 5.6 due to
876 // https://bugs.php.net/bug.php?id=72286. Once the container is rebuilt,
877 // garbage collection is re-enabled.
878 $disable_gc = version_compare(PHP_VERSION, '7', '<') && gc_enabled();
883 $container = $this->compileContainer();
885 // Only dump the container if dumping is allowed. This is useful for
886 // KernelTestBase, which never wants to use the real container, but always
887 // the container builder.
888 if ($this->allowDumping) {
889 $dumper = new $this->phpArrayDumperClass($container);
890 $container_definition = $dumper->getArray();
892 // If garbage collection was disabled prior to rebuilding container,
899 // The container was rebuilt successfully.
900 $this->containerNeedsRebuild = FALSE;
902 // Only create a new class if we have a container definition.
903 if (isset($container_definition)) {
904 $class = Settings::get('container_base_class', '\Drupal\Core\DependencyInjection\Container');
905 $container = new $class($container_definition);
908 $this->attachSynthetic($container);
910 $this->container = $container;
911 if ($session_started) {
912 $this->container->get('session')->start();
915 // The request stack is preserved across container rebuilds. Reinject the
916 // new session into the master request if one was present before.
917 if (($request_stack = $this->container->get('request_stack', ContainerInterface::NULL_ON_INVALID_REFERENCE))) {
918 if ($request = $request_stack->getMasterRequest()) {
919 if ($request->hasSession()) {
920 $request->setSession($this->container->get('session'));
925 if (!empty($current_user_id)) {
926 $this->container->get('current_user')->setInitialAccountId($current_user_id);
929 \Drupal::setContainer($this->container);
931 // If needs dumping flag was set, dump the container.
932 if ($this->containerNeedsDumping && !$this->cacheDrupalContainer($container_definition)) {
933 $this->container->get('logger.factory')->get('DrupalKernel')->error('Container cannot be saved to cache.');
936 return $this->container;
940 * Setup a consistent PHP environment.
942 * This method sets PHP environment options we want to be sure are set
943 * correctly for security or just saneness.
945 * @param string $app_root
946 * (optional) The path to the application root as a string. If not supplied,
947 * the application root will be computed.
949 public static function bootEnvironment($app_root = NULL) {
950 if (static::$isEnvironmentInitialized) {
954 // Determine the application root if it's not supplied.
955 if ($app_root === NULL) {
956 $app_root = static::guessApplicationRoot();
959 // Include our bootstrap file.
960 require_once $app_root . '/core/includes/bootstrap.inc';
962 // Enforce E_STRICT, but allow users to set levels not part of E_STRICT.
963 error_reporting(E_STRICT | E_ALL);
965 // Override PHP settings required for Drupal to work properly.
966 // sites/default/default.settings.php contains more runtime settings.
967 // The .htaccess file contains settings that cannot be changed at runtime.
969 // Use session cookies, not transparent sessions that puts the session id in
971 ini_set('session.use_cookies', '1');
972 ini_set('session.use_only_cookies', '1');
973 ini_set('session.use_trans_sid', '0');
974 // Don't send HTTP headers using PHP's session handler.
975 // Send an empty string to disable the cache limiter.
976 ini_set('session.cache_limiter', '');
977 // Use httponly session cookies.
978 ini_set('session.cookie_httponly', '1');
980 // Set sane locale settings, to ensure consistent string, dates, times and
982 setlocale(LC_ALL, 'C');
984 // Detect string handling method.
987 // Indicate that code is operating in a test child site.
988 if (!defined('DRUPAL_TEST_IN_CHILD_SITE')) {
989 if ($test_prefix = drupal_valid_test_ua()) {
990 $test_db = new TestDatabase($test_prefix);
991 // Only code that interfaces directly with tests should rely on this
992 // constant; e.g., the error/exception handler conditionally adds further
993 // error information into HTTP response headers that are consumed by
994 // Simpletest's internal browser.
995 define('DRUPAL_TEST_IN_CHILD_SITE', TRUE);
997 // Web tests are to be conducted with runtime assertions active.
998 assert_options(ASSERT_ACTIVE, TRUE);
999 // Now synchronize PHP 5 and 7's handling of assertions as much as
1003 // Log fatal errors to the test site directory.
1004 ini_set('log_errors', 1);
1005 ini_set('error_log', $app_root . '/' . $test_db->getTestSitePath() . '/error.log');
1007 // Ensure that a rewritten settings.php is used if opcache is on.
1008 ini_set('opcache.validate_timestamps', 'on');
1009 ini_set('opcache.revalidate_freq', 0);
1012 // Ensure that no other code defines this.
1013 define('DRUPAL_TEST_IN_CHILD_SITE', FALSE);
1017 // Set the Drupal custom error handler.
1018 set_error_handler('_drupal_error_handler');
1019 set_exception_handler('_drupal_exception_handler');
1021 static::$isEnvironmentInitialized = TRUE;
1025 * Locate site path and initialize settings singleton.
1027 * @param \Symfony\Component\HttpFoundation\Request $request
1028 * The current request.
1030 * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
1031 * In case the host name in the request is not trusted.
1033 protected function initializeSettings(Request $request) {
1034 $site_path = static::findSitePath($request);
1035 $this->setSitePath($site_path);
1036 $class_loader_class = get_class($this->classLoader);
1037 Settings::initialize($this->root, $site_path, $this->classLoader);
1039 // Initialize our list of trusted HTTP Host headers to protect against
1041 $host_patterns = Settings::get('trusted_host_patterns', []);
1042 if (PHP_SAPI !== 'cli' && !empty($host_patterns)) {
1043 if (static::setupTrustedHosts($request, $host_patterns) === FALSE) {
1044 throw new BadRequestHttpException('The provided host name is not valid for this server.');
1048 // If the class loader is still the same, possibly
1049 // upgrade to an optimized class loader.
1050 if ($class_loader_class == get_class($this->classLoader)
1051 && Settings::get('class_loader_auto_detect', TRUE)) {
1052 $prefix = Settings::getApcuPrefix('class_loader', $this->root);
1055 // We autodetect one of the following three optimized classloaders, if
1056 // their underlying extension exists.
1057 if (function_exists('apcu_fetch')) {
1058 $loader = new ApcClassLoader($prefix, $this->classLoader);
1060 elseif (extension_loaded('wincache')) {
1061 $loader = new WinCacheClassLoader($prefix, $this->classLoader);
1063 elseif (extension_loaded('xcache')) {
1064 $loader = new XcacheClassLoader($prefix, $this->classLoader);
1066 if (!empty($loader)) {
1067 $this->classLoader->unregister();
1068 // The optimized classloader might be persistent and store cache misses.
1069 // For example, once a cache miss is stored in APCu clearing it on a
1070 // specific web-head will not clear any other web-heads. Therefore
1071 // fallback to the composer class loader that only statically caches
1073 $old_loader = $this->classLoader;
1074 $this->classLoader = $loader;
1075 // Our class loaders are preprended to ensure they come first like the
1076 // class loader they are replacing.
1077 $old_loader->register(TRUE);
1078 $loader->register(TRUE);
1084 * Bootstraps the legacy global request variables.
1086 * @param \Symfony\Component\HttpFoundation\Request $request
1087 * The current request.
1089 * @todo D8: Eliminate this entirely in favor of Request object.
1091 protected function initializeRequestGlobals(Request $request) {
1093 // Set and derived from $base_url by this function.
1094 global $base_path, $base_root;
1095 global $base_secure_url, $base_insecure_url;
1098 $base_root = $request->getSchemeAndHttpHost();
1099 $base_url = $base_root;
1101 // For a request URI of '/index.php/foo', $_SERVER['SCRIPT_NAME'] is
1102 // '/index.php', whereas $_SERVER['PHP_SELF'] is '/index.php/foo'.
1103 if ($dir = rtrim(dirname($request->server->get('SCRIPT_NAME')), '\/')) {
1104 // Remove "core" directory if present, allowing install.php,
1105 // authorize.php, and others to auto-detect a base path.
1106 $core_position = strrpos($dir, '/core');
1107 if ($core_position !== FALSE && strlen($dir) - 5 == $core_position) {
1108 $base_path = substr($dir, 0, $core_position);
1113 $base_url .= $base_path;
1119 $base_secure_url = str_replace('http://', 'https://', $base_url);
1120 $base_insecure_url = str_replace('https://', 'http://', $base_url);
1124 * Returns service instances to persist from an old container to a new one.
1126 protected function getServicesToPersist(ContainerInterface $container) {
1128 foreach ($container->getParameter('persist_ids') as $id) {
1129 // It's pointless to persist services not yet initialized.
1130 if ($container->initialized($id)) {
1131 $persist[$id] = $container->get($id);
1138 * Moves persistent service instances into a new container.
1140 protected function persistServices(ContainerInterface $container, array $persist) {
1141 foreach ($persist as $id => $object) {
1142 // Do not override services already set() on the new container, for
1143 // example 'service_container'.
1144 if (!$container->initialized($id)) {
1145 $container->set($id, $object);
1153 public function rebuildContainer() {
1154 // Empty module properties and for them to be reloaded from scratch.
1155 $this->moduleList = NULL;
1156 $this->moduleData = [];
1157 $this->containerNeedsRebuild = TRUE;
1158 return $this->initializeContainer();
1164 public function invalidateContainer() {
1165 // An invalidated container needs a rebuild.
1166 $this->containerNeedsRebuild = TRUE;
1168 // If we have not yet booted, settings or bootstrap services might not yet
1169 // be available. In that case the container will not be loaded from cache
1170 // due to the above setting when the Kernel is booted.
1171 if (!$this->booted) {
1175 // Also remove the container definition from the cache backend.
1176 $this->bootstrapContainer->get('cache.container')->deleteAll();
1180 * Attach synthetic values on to kernel.
1182 * @param ContainerInterface $container
1185 * @return ContainerInterface
1187 protected function attachSynthetic(ContainerInterface $container) {
1189 if (isset($this->container)) {
1190 $persist = $this->getServicesToPersist($this->container);
1192 $this->persistServices($container, $persist);
1194 // All namespaces must be registered before we attempt to use any service
1195 // from the container.
1196 $this->classLoaderAddMultiplePsr4($container->getParameter('container.namespaces'));
1198 $container->set('kernel', $this);
1200 // Set the class loader which was registered as a synthetic service.
1201 $container->set('class_loader', $this->classLoader);
1206 * Compiles a new service container.
1208 * @return ContainerBuilder The compiled service container
1210 protected function compileContainer() {
1211 // We are forcing a container build so it is reasonable to assume that the
1212 // calling method knows something about the system has changed requiring the
1213 // container to be dumped to the filesystem.
1214 if ($this->allowDumping) {
1215 $this->containerNeedsDumping = TRUE;
1218 $this->initializeServiceProviders();
1219 $container = $this->getContainerBuilder();
1220 $container->set('kernel', $this);
1221 $container->setParameter('container.modules', $this->getModulesParameter());
1222 $container->setParameter('install_profile', $this->getInstallProfile());
1224 // Get a list of namespaces and put it onto the container.
1225 $namespaces = $this->getModuleNamespacesPsr4($this->getModuleFileNames());
1226 // Add all components in \Drupal\Core and \Drupal\Component that have one of
1227 // the following directories:
1231 foreach (['Core', 'Component'] as $parent_directory) {
1232 $path = 'core/lib/Drupal/' . $parent_directory;
1233 $parent_namespace = 'Drupal\\' . $parent_directory;
1234 foreach (new \DirectoryIterator($this->root . '/' . $path) as $component) {
1235 /** @var $component \DirectoryIterator */
1236 $pathname = $component->getPathname();
1237 if (!$component->isDot() && $component->isDir() && (
1238 is_dir($pathname . '/Plugin') ||
1239 is_dir($pathname . '/Entity') ||
1240 is_dir($pathname . '/Element')
1242 $namespaces[$parent_namespace . '\\' . $component->getFilename()] = $path . '/' . $component->getFilename();
1246 $container->setParameter('container.namespaces', $namespaces);
1248 // Store the default language values on the container. This is so that the
1249 // default language can be configured using the configuration factory. This
1250 // avoids the circular dependencies that would created by
1251 // \Drupal\language\LanguageServiceProvider::alter() and allows the default
1252 // language to not be English in the installer.
1253 $default_language_values = Language::$defaultValues;
1254 if ($system = $this->getConfigStorage()->read('system.site')) {
1255 if ($default_language_values['id'] != $system['langcode']) {
1256 $default_language_values = ['id' => $system['langcode']];
1259 $container->setParameter('language.default_values', $default_language_values);
1261 // Register synthetic services.
1262 $container->register('class_loader')->setSynthetic(TRUE);
1263 $container->register('kernel', 'Symfony\Component\HttpKernel\KernelInterface')->setSynthetic(TRUE);
1264 $container->register('service_container', 'Symfony\Component\DependencyInjection\ContainerInterface')->setSynthetic(TRUE);
1266 // Register application services.
1267 $yaml_loader = new YamlFileLoader($container);
1268 foreach ($this->serviceYamls['app'] as $filename) {
1269 $yaml_loader->load($filename);
1271 foreach ($this->serviceProviders['app'] as $provider) {
1272 if ($provider instanceof ServiceProviderInterface) {
1273 $provider->register($container);
1276 // Register site-specific service overrides.
1277 foreach ($this->serviceYamls['site'] as $filename) {
1278 $yaml_loader->load($filename);
1280 foreach ($this->serviceProviders['site'] as $provider) {
1281 if ($provider instanceof ServiceProviderInterface) {
1282 $provider->register($container);
1286 // Identify all services whose instances should be persisted when rebuilding
1287 // the container during the lifetime of the kernel (e.g., during a kernel
1288 // reboot). Include synthetic services, because by definition, they cannot
1289 // be automatically reinstantiated. Also include services tagged to persist.
1291 foreach ($container->getDefinitions() as $id => $definition) {
1292 // It does not make sense to persist the container itself, exclude it.
1293 if ($id !== 'service_container' && ($definition->isSynthetic() || $definition->getTag('persist'))) {
1294 $persist_ids[] = $id;
1297 $container->setParameter('persist_ids', $persist_ids);
1299 $container->compile();
1304 * Registers all service providers to the kernel.
1306 * @throws \LogicException
1308 protected function initializeServiceProviders() {
1309 $this->discoverServiceProviders();
1310 $this->serviceProviders = [
1314 foreach ($this->serviceProviderClasses as $origin => $classes) {
1315 foreach ($classes as $name => $class) {
1316 if (!is_object($class)) {
1317 $this->serviceProviders[$origin][$name] = new $class();
1320 $this->serviceProviders[$origin][$name] = $class;
1327 * Gets a new ContainerBuilder instance used to build the service container.
1329 * @return ContainerBuilder
1331 protected function getContainerBuilder() {
1332 return new ContainerBuilder(new ParameterBag($this->getKernelParameters()));
1336 * Stores the container definition in a cache.
1338 * @param array $container_definition
1339 * The container definition to cache.
1342 * TRUE if the container was successfully cached.
1344 protected function cacheDrupalContainer(array $container_definition) {
1347 $this->bootstrapContainer->get('cache.container')->set($this->getContainerCacheKey(), $container_definition);
1349 catch (\Exception $e) {
1350 // There is no way to get from the Cache API if the cache set was
1351 // successful or not, hence an Exception is caught and the caller informed
1352 // about the error condition.
1360 * Gets a http kernel from the container
1362 * @return \Symfony\Component\HttpKernel\HttpKernelInterface
1364 protected function getHttpKernel() {
1365 return $this->container->get('http_kernel');
1369 * Returns the active configuration storage to use during building the container.
1371 * @return \Drupal\Core\Config\StorageInterface
1373 protected function getConfigStorage() {
1374 if (!isset($this->configStorage)) {
1375 // The active configuration storage may not exist yet; e.g., in the early
1376 // installer. Catch the exception thrown by config_get_config_directory().
1378 $this->configStorage = BootstrapConfigStorageFactory::get($this->classLoader);
1380 catch (\Exception $e) {
1381 $this->configStorage = new NullStorage();
1384 return $this->configStorage;
1388 * Returns an array of Extension class parameters for all enabled modules.
1392 protected function getModulesParameter() {
1394 foreach ($this->moduleList as $name => $weight) {
1395 if ($data = $this->moduleData($name)) {
1396 $extensions[$name] = [
1397 'type' => $data->getType(),
1398 'pathname' => $data->getPathname(),
1399 'filename' => $data->getExtensionFilename(),
1407 * Gets the file name for each enabled module.
1410 * Array where each key is a module name, and each value is a path to the
1411 * respective *.info.yml file.
1413 protected function getModuleFileNames() {
1415 foreach ($this->moduleList as $module => $weight) {
1416 if ($data = $this->moduleData($module)) {
1417 $filenames[$module] = $data->getPathname();
1424 * Gets the PSR-4 base directories for module namespaces.
1426 * @param string[] $module_file_names
1427 * Array where each key is a module name, and each value is a path to the
1428 * respective *.info.yml file.
1431 * Array where each key is a module namespace like 'Drupal\system', and each
1432 * value is the PSR-4 base directory associated with the module namespace.
1434 protected function getModuleNamespacesPsr4($module_file_names) {
1436 foreach ($module_file_names as $module => $filename) {
1437 $namespaces["Drupal\\$module"] = dirname($filename) . '/src';
1443 * Registers a list of namespaces with PSR-4 directories for class loading.
1445 * @param array $namespaces
1446 * Array where each key is a namespace like 'Drupal\system', and each value
1447 * is either a PSR-4 base directory, or an array of PSR-4 base directories
1448 * associated with this namespace.
1449 * @param object $class_loader
1450 * The class loader. Normally \Composer\Autoload\ClassLoader, as included by
1451 * the front controller, but may also be decorated; e.g.,
1452 * \Symfony\Component\ClassLoader\ApcClassLoader.
1454 protected function classLoaderAddMultiplePsr4(array $namespaces = [], $class_loader = NULL) {
1455 if ($class_loader === NULL) {
1456 $class_loader = $this->classLoader;
1458 foreach ($namespaces as $prefix => $paths) {
1459 if (is_array($paths)) {
1460 foreach ($paths as $key => $value) {
1461 $paths[$key] = $this->root . '/' . $value;
1464 elseif (is_string($paths)) {
1465 $paths = $this->root . '/' . $paths;
1467 $class_loader->addPsr4($prefix . '\\', $paths);
1472 * Validates a hostname length.
1474 * @param string $host
1478 * TRUE if the length is appropriate, or FALSE otherwise.
1480 protected static function validateHostnameLength($host) {
1481 // Limit the length of the host name to 1000 bytes to prevent DoS attacks
1482 // with long host names.
1483 return strlen($host) <= 1000
1484 // Limit the number of subdomains and port separators to prevent DoS attacks
1485 // in findSitePath().
1486 && substr_count($host, '.') <= 100
1487 && substr_count($host, ':') <= 100;
1491 * Validates the hostname supplied from the HTTP request.
1493 * @param \Symfony\Component\HttpFoundation\Request $request
1494 * The request object
1497 * TRUE if the hostname is valid, or FALSE otherwise.
1499 public static function validateHostname(Request $request) {
1500 // $request->getHost() can throw an UnexpectedValueException if it
1501 // detects a bad hostname, but it does not validate the length.
1503 $http_host = $request->getHost();
1505 catch (\UnexpectedValueException $e) {
1509 if (static::validateHostnameLength($http_host) === FALSE) {
1517 * Sets up the lists of trusted HTTP Host headers.
1519 * Since the HTTP Host header can be set by the user making the request, it
1520 * is possible to create an attack vectors against a site by overriding this.
1521 * Symfony provides a mechanism for creating a list of trusted Host values.
1523 * Host patterns (as regular expressions) can be configured through
1524 * settings.php for multisite installations, sites using ServerAlias without
1525 * canonical redirection, or configurations where the site responds to default
1526 * requests. For example,
1529 * $settings['trusted_host_patterns'] = array(
1531 * '^*.example\.com$',
1535 * @param \Symfony\Component\HttpFoundation\Request $request
1536 * The request object.
1537 * @param array $host_patterns
1538 * The array of trusted host patterns.
1541 * TRUE if the Host header is trusted, FALSE otherwise.
1543 * @see https://www.drupal.org/node/1992030
1544 * @see \Drupal\Core\Http\TrustedHostsRequestFactory
1546 protected static function setupTrustedHosts(Request $request, $host_patterns) {
1547 $request->setTrustedHosts($host_patterns);
1549 // Get the host, which will validate the current request.
1551 $host = $request->getHost();
1553 // Fake requests created through Request::create() without passing in the
1554 // server variables from the main request have a default host of
1555 // 'localhost'. If 'localhost' does not match any of the trusted host
1556 // patterns these fake requests would fail the host verification. Instead,
1557 // TrustedHostsRequestFactory makes sure to pass in the server variables
1558 // from the main request.
1559 $request_factory = new TrustedHostsRequestFactory($host);
1560 Request::setFactory([$request_factory, 'createRequest']);
1563 catch (\UnexpectedValueException $e) {
1571 * Add service files.
1573 * @param string[] $service_yamls
1574 * A list of service files.
1576 protected function addServiceFiles(array $service_yamls) {
1577 $this->serviceYamls['site'] = array_filter($service_yamls, 'file_exists');
1581 * Gets the active install profile.
1583 * @return string|null
1584 * The name of the any active install profile or distribution.
1586 protected function getInstallProfile() {
1587 $config = $this->getConfigStorage()->read('core.extension');
1588 if (!empty($config['profile'])) {
1589 $install_profile = $config['profile'];
1591 // @todo https://www.drupal.org/node/2831065 remove the BC layer.
1593 // If system_update_8300() has not yet run fallback to using settings.
1594 $install_profile = Settings::get('install_profile');
1597 // Normalize an empty string to a NULL value.
1598 return empty($install_profile) ? NULL : $install_profile;