Newer
Older
<?php
namespace Drupal\Core;
use Composer\Autoload\ClassLoader;
use Drupal\Component\EventDispatcher\Event;
use Drupal\Component\FileCache\FileCacheFactory;
use Drupal\Component\Serialization\PhpSerialize;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Cache\DatabaseBackend;

catch
committed
use Drupal\Core\Config\BootstrapConfigStorageFactory;
use Drupal\Core\Config\NullStorage;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Component\DependencyInjection\ReverseContainer;
use Drupal\Core\DependencyInjection\ServiceModifierInterface;
use Drupal\Core\DependencyInjection\ServiceProviderInterface;

Alex Pott
committed
use Drupal\Core\DependencyInjection\YamlFileLoader;

catch
committed
use Drupal\Core\Extension\Extension;

catch
committed
use Drupal\Core\Extension\ExtensionDiscovery;
use Drupal\Core\File\MimeType\MimeTypeGuesser;

Angie Byron
committed
use Drupal\Core\Http\TrustedHostsRequestFactory;

Lee Rowlands
committed
use Drupal\Core\Installer\InstallerKernel;
use Drupal\Core\Installer\InstallerRedirectTrait;

catch
committed
use Drupal\Core\Language\Language;

Lee Rowlands
committed
use Drupal\Core\Security\RequestSanitizer;
use Drupal\Core\Site\Settings;

catch
committed
use Drupal\Core\Test\TestDatabase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

Lee Rowlands
committed
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;

Alex Pott
committed
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

Alex Pott
committed
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\TerminableInterface;
/**
* The DrupalKernel class is the core of Drupal itself.
*
* This class is responsible for building the Dependency Injection Container and
* also deals with the registration of service providers. It allows registered
* service providers to add their services to the container. Core provides the
* CoreServiceProvider, which, in addition to registering any core services that
* cannot be registered in the core.services.yaml file, adds any compiler passes
* needed by core, e.g. for processing tagged services. Each module can add its
* own service provider, i.e. a class implementing
* Drupal\Core\DependencyInjection\ServiceProvider, to register services to the
* container, or modify existing services.
class DrupalKernel implements DrupalKernelInterface, TerminableInterface {
use InstallerRedirectTrait;
/**
* Holds the class used for dumping the container to a PHP array.
*
* In combination with swapping the container class this is useful to e.g.
* dump to the human-readable PHP array format to debug the container
* definition in an easier way.
*
* @var string
*/
protected $phpArrayDumperClass = '\Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper';
/**
* Holds the default bootstrap container definition.
*
* @var array
*/
protected $defaultBootstrapContainerDefinition = [
'parameters' => [],
'services' => [
'database' => [
'class' => 'Drupal\Core\Database\Connection',
'factory' => 'Drupal\Core\Database\Database::getConnection',
'arguments' => ['default'],
],
'request_stack' => [
'class' => 'Symfony\Component\HttpFoundation\RequestStack',
],
'datetime.time' => [
'class' => 'Drupal\Component\Datetime\Time',
'arguments' => ['@request_stack'],
],
'cache.container' => [
'class' => 'Drupal\Core\Cache\DatabaseBackend',
'arguments' => [
'@database',
'@cache_tags_provider.container',
'container',
'@serialization.phpserialize',
'@datetime.time',
DatabaseBackend::MAXIMUM_NONE,
],
],
'cache_tags_provider.container' => [
'class' => 'Drupal\Core\Cache\DatabaseCacheTagsChecksum',
'arguments' => ['@database'],
],
'serialization.phpserialize' => [
'class' => PhpSerialize::class,
],
],
];
/**
* Holds the class used for instantiating the bootstrap container.
*
* @var string
*/
protected $bootstrapContainerClass = '\Drupal\Component\DependencyInjection\PhpArrayContainer';
/**
* Holds the bootstrap container.
*
* @var \Symfony\Component\DependencyInjection\ContainerInterface
*/
protected $bootstrapContainer;
/**
* Holds the container instance.
*
* @var \Drupal\Component\DependencyInjection\ContainerInterface
*/
protected $container;
/**
* The environment, e.g. 'testing', 'install'.
*
* @var string
*/
protected $environment;
/**
* Whether the kernel has been booted.
*
* @var bool
*/
protected $booted = FALSE;

Alex Pott
committed
/**
* Whether essential services have been set up properly by preHandle().
*
* @var bool
*/
protected $prepared = FALSE;
/**
* Holds the list of enabled modules.
*
* @var array

catch
committed
* An associative array whose keys are module names and whose values are
* ignored.
*/
protected $moduleList;

catch
committed
/**
* List of available modules and installation profiles.

catch
committed
*
* @var \Drupal\Core\Extension\Extension[]
*/
protected $moduleData = [];

catch
committed
/**

catch
committed
* The class loader object.

catch
committed
*
* @var \Composer\Autoload\ClassLoader

catch
committed
*/
protected $classLoader;

catch
committed
/**
* Config storage object used for reading enabled modules configuration.
*
* @var \Drupal\Core\Config\StorageInterface
*/
protected $configStorage;
/**
* Whether the container can be dumped.
*
* @var bool
*/
protected $allowDumping;
/**
* Whether the container needs to be rebuilt the next time it is initialized.
*
* @var bool
*/
protected $containerNeedsRebuild = FALSE;

catch
committed
/**
* Whether the container needs to be dumped once booting is complete.
*
* @var bool
*/
protected $containerNeedsDumping;

Alex Pott
committed
/**

Dave Long
committed
* List of discovered services.yml path names.
*
* This is a nested array whose top-level keys are 'app' and 'site', denoting
* the origin of a service provider. Site-specific providers have to be
* collected separately, because they need to be processed last, so as to be
* able to override services from application service providers.

Alex Pott
committed
*
* @var array
*/
protected $serviceYamls;
/**
* List of discovered service provider class names or objects.
*
* This is a nested array whose top-level keys are 'app' and 'site', denoting
* the origin of a service provider. Site-specific providers have to be
* collected separately, because they need to be processed last, so as to be
* able to override services from application service providers.
*
* Allowing objects is for example used to allow
* \Drupal\KernelTests\KernelTestBase to register itself as service provider.
*
* @var array
*/
protected $serviceProviderClasses;
/**
* List of instantiated service provider classes.
*
* @var array
*
* @see \Drupal\Core\DrupalKernel::$serviceProviderClasses
*/
protected $serviceProviders;
/**
* Whether the PHP environment has been initialized.
*
* This legacy phase can only be booted once because it sets session INI
* settings. If a session has already been started, re-generating these
* settings would break the session.
*
* @var bool
*/
protected static $isEnvironmentInitialized = FALSE;
/**
* The site path directory.
*
* Site path is relative to the app root directory.
* Usually defined as "sites/default".
*
* By default, Drupal uses sites/default.
*
* @var string
*/
protected $sitePath;
/**
* The app root.
*
* @var string
*/
protected $root;
/**
* Create a DrupalKernel object from a request.
*
* @param \Symfony\Component\HttpFoundation\Request $request

Lee Rowlands
committed
* @param \Composer\Autoload\ClassLoader $class_loader
* The class loader. Normally Composer's ClassLoader, as included by the
* front controller, but may also be decorated.
* @param string $environment
* String indicating the environment, e.g. 'prod' or 'dev'.
* @param bool $allow_dumping
* (optional) FALSE to stop the container from being written to or read
* from disk. Defaults to TRUE.
* @param string $app_root
* (optional) The path to the application root as a string. If not supplied,
* the application root will be computed.
* @return static
*
* @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
* In case the host name in the request is not trusted.
*/
public static function createFromRequest(Request $request, $class_loader, $environment, $allow_dumping = TRUE, $app_root = NULL) {
$kernel = new static($environment, $class_loader, $allow_dumping, $app_root);
static::bootEnvironment($app_root);

Alex Pott
committed
$kernel->initializeSettings($request);
return $kernel;
}
/**
* Constructs a DrupalKernel object.
*
* @param string $environment
* String indicating the environment, e.g. 'prod' or 'dev'.

Lee Rowlands
committed
* @param \Composer\Autoload\ClassLoader $class_loader
* The class loader. Normally \Composer\Autoload\ClassLoader, as included by
* the front controller, but may also be decorated.

catch
committed
* @param bool $allow_dumping
* (optional) FALSE to stop the container from being written to or read
* from disk. Defaults to TRUE.
* @param string $app_root
* (optional) The path to the application root as a string. If not supplied,
* the application root will be computed.

catch
committed
*/
public function __construct($environment, $class_loader, $allow_dumping = TRUE, $app_root = NULL) {
$this->environment = $environment;

catch
committed
$this->classLoader = $class_loader;

catch
committed
$this->allowDumping = $allow_dumping;
if ($app_root === NULL) {
$app_root = static::guessApplicationRoot();
}
$this->root = $app_root;
}
/**

Alex Pott
committed
* Determine the application root directory based on this file's location.
*
* @return string
* The application root.
*/
protected static function guessApplicationRoot() {

Alex Pott
committed
// Determine the application root by:
// - Removing the namespace directories from the path.
// - Getting the path to the directory two levels up from the path
// determined in the previous step.
return dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__)), 2);
}
/**
* Returns the appropriate site directory for a request.
*
* Once the kernel has been created DrupalKernelInterface::getSitePath() is
* preferred since it gets the statically cached result of this method.
*
* Site directories contain all site specific code. This includes settings.php
* for bootstrap level configuration, file configuration stores, public file
* storage and site specific modules and themes.
*

Alex Pott
committed
* A file named sites.php must be present in the sites directory for
* multisite. If it doesn't exist, then 'sites/default' will be used.
*
* Finds a matching site directory file by stripping the website's hostname
* from left to right and pathname from right to left. By default, the
* directory must contain a 'settings.php' file for it to match. If the
* parameter $require_settings is set to FALSE, then a directory without a
* 'settings.php' file will match as well. The first configuration file found
* will be used and the remaining ones will be ignored. If no configuration
* file is found, returns a default value 'sites/default'. See
* default.settings.php for examples on how the URL is converted to a
* directory.
*

Alex Pott
committed
* The sites.php file in the sites directory can define aliases in an
* associative array named $sites. The array is written in the format
* '<port>.<domain>.<path>' => 'directory'. As an example, to create a

Dave Long
committed
* directory alias for https://www.drupal.org:8080/my-site/test whose
* configuration file is in sites/example.com, the array should be defined as:
* @code
* $sites = [

Dave Long
committed
* '8080.www.drupal.org.my-site.test' => 'example.com',
* ];
* @endcode
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request.
* @param bool $require_settings
* Only directories with an existing settings.php file will be recognized.
* Defaults to TRUE. During initial installation, this is set to FALSE so
* that Drupal can detect a matching directory, then create a new
* settings.php file in it.
* @param string $app_root
* (optional) The path to the application root as a string. If not supplied,
* the application root will be computed.
*
* @return string
* The path of the matching directory.
*

Alex Pott
committed
* @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
* In case the host name in the request is invalid.
*
* @see \Drupal\Core\DrupalKernelInterface::getSitePath()
* @see \Drupal\Core\DrupalKernelInterface::setSitePath()
* @see default.settings.php
* @see example.sites.php
*/
public static function findSitePath(Request $request, $require_settings = TRUE, $app_root = NULL) {

Alex Pott
committed
if (static::validateHostname($request) === FALSE) {
throw new BadRequestHttpException();
}
if ($app_root === NULL) {
$app_root = static::guessApplicationRoot();
}

catch
committed
// Check for a test override.
if ($test_prefix = drupal_valid_test_ua()) {

catch
committed
$test_db = new TestDatabase($test_prefix);
return $test_db->getTestSitePath();
}

catch
committed
// Determine whether multi-site functionality is enabled. If not, return
// the default directory.
if (!is_file($app_root . '/sites/sites.php')) {
return 'sites/default';
}

catch
committed
// Pre-populate host and script variables, then include sites.php which may
// populate $sites with a site-directory mapping.
$script_name = $request->server->get('SCRIPT_NAME');
if (!$script_name) {
$script_name = $request->server->get('SCRIPT_FILENAME');
}
$http_host = $request->getHttpHost();
$sites = [];
include $app_root . '/sites/sites.php';

catch
committed
// Construct an identifier from pieces of the (port plus) host plus script
// path (excluding the filename). Loop over all possibilities starting from
// most specific, then dropping pieces from the start of the port/hostname
// while keeping the full path, then gradually dropping pieces from the end
// of the path... until we find a directory corresponding to the identifier.
$path_parts = explode('/', $script_name);
$host_parts = explode('.', implode('.', array_reverse(explode(':', rtrim($http_host, '.')))));
for ($i = count($path_parts) - 1; $i > 0; $i--) {
for ($j = count($host_parts); $j > 0; $j--) {
// Assume the path has a leading slash, so the imploded path parts are
// either a path identifier with leading dot, or an empty string.
$site_id = implode('.', array_slice($host_parts, -$j)) . implode('.', array_slice($path_parts, 0, $i));
// If the identifier is a key in $sites, check for a directory matching
// the corresponding value. Otherwise, check for a directory matching
// the identifier.
if (isset($sites[$site_id]) && is_dir($app_root . '/sites/' . $sites[$site_id])) {

catch
committed
$site_id = $sites[$site_id];
if (is_file($app_root . '/sites/' . $site_id . '/settings.php') || (!$require_settings && is_file($app_root . '/sites/' . $site_id))) {

catch
committed
return "sites/$site_id";
}
}
}
return 'sites/default';
}
/**
* {@inheritdoc}
*/
public function setSitePath($path) {

Alex Pott
committed
if ($this->booted && $path !== $this->sitePath) {

Alex Pott
committed
throw new \LogicException('Site path cannot be changed after calling boot()');
}
$this->sitePath = $path;
}
/**
* {@inheritdoc}
*/
public function getSitePath() {
return $this->sitePath;
}
/**
* {@inheritdoc}
*/
public function getAppRoot() {
return $this->root;
}

catch
committed
/**
* {@inheritdoc}

catch
committed
*/
public function boot() {
if ($this->booted) {
return $this;
}
// Ensure that findSitePath is set.
if (!$this->sitePath) {
throw new \Exception('Kernel does not have site path set before calling boot()');
// Initialize the FileCacheFactory component. We have to do it here instead
// of in \Drupal\Component\FileCache\FileCacheFactory because we can not use
// the Settings object in a component.
$configuration = Settings::get('file_cache');
// Provide a default configuration, if not set.
if (!isset($configuration['default'])) {
// @todo Use extension_loaded('apcu') for non-testbot
// https://www.drupal.org/node/2447753.

Alex Pott
committed
if (function_exists('apcu_fetch')) {
$configuration['default']['cache_backend_class'] = '\Drupal\Component\FileCache\ApcuFileCacheBackend';
}
}
FileCacheFactory::setConfiguration($configuration);
FileCacheFactory::setPrefix(Settings::getApcuPrefix('file_cache', $this->root));
$this->bootstrapContainer = new $this->bootstrapContainerClass(Settings::get('bootstrap_container_definition', $this->defaultBootstrapContainerDefinition));
// Initialize the container.

catch
committed
$this->initializeContainer();
// Add the APCu prefix to use to cache found/not-found classes.
if (Settings::get('class_loader_auto_detect', TRUE) && method_exists($this->classLoader, 'setApcuPrefix')) {
// Vary the APCu key by which modules are installed to allow
// class_exists() checks to determine functionality.

Alex Pott
committed
$id = 'class_loader:' . crc32(implode(':', array_keys($this->container->getParameter('container.modules'))));
$prefix = Settings::getApcuPrefix($id, $this->root);
$this->classLoader->setApcuPrefix($prefix);
}

catch
committed
$this->booted = TRUE;
return $this;

catch
committed
}
* {@inheritdoc}
public function shutdown() {
if (FALSE === $this->booted) {
return;
}
$this->container->get('stream_wrapper_manager')->unregister();
$this->booted = FALSE;

Lee Rowlands
committed
$this->configStorage = NULL;
$this->container = NULL;
$this->moduleList = NULL;
$this->moduleData = [];
}
/**
* {@inheritdoc}
*/
public function getContainer() {
return $this->container;
}
/**
* {@inheritdoc}
*/
public function getCachedContainerDefinition() {
$cache = $this->bootstrapContainer->get('cache.container')->get($this->getContainerCacheKey());
if ($cache) {
return $cache->data;
}
return NULL;
}
/**
* {@inheritdoc}
*/
public function loadLegacyIncludes() {
require_once $this->root . '/core/includes/common.inc';
require_once $this->root . '/core/includes/module.inc';
require_once $this->root . '/core/includes/theme.inc';
require_once $this->root . '/core/includes/form.inc';
require_once $this->root . '/core/includes/errors.inc';
}
/**

Dries Buytaert
committed
* {@inheritdoc}
*/

Dries Buytaert
committed
public function preHandle(Request $request) {

Lee Rowlands
committed
// Sanitize the request.
$request = RequestSanitizer::sanitize(
$request,
(array) Settings::get(RequestSanitizer::SANITIZE_INPUT_SAFE_KEYS, []),

Lee Rowlands
committed
(bool) Settings::get(RequestSanitizer::SANITIZE_LOG, FALSE)
);

Lee Rowlands
committed
// Ensure that there is a session on every request.
if (!$request->hasSession()) {
$this->initializeEphemeralSession($request);
}
$this->loadLegacyIncludes();
// Load all enabled modules.
$this->container->get('module_handler')->loadAll();
// Register stream wrappers.
$this->container->get('stream_wrapper_manager')->register();
// Initialize legacy request globals.
$this->initializeRequestGlobals($request);
// Put the request on the stack.
$this->container->get('request_stack')->push($request);

Alex Pott
committed
// Set the allowed protocols.
UrlHelper::setAllowedProtocols($this->container->getParameter('filter_protocols'));
// Override of Symfony's MIME type guesser singleton.
MimeTypeGuesser::registerWithSymfonyGuesser($this->container);

Alex Pott
committed
$this->prepared = TRUE;
}
/**
* {@inheritdoc}
*/
public function discoverServiceProviders() {
$this->serviceYamls = [
'app' => [],
'site' => [],
];
$this->serviceProviderClasses = [
'app' => [],
'site' => [],
];
$this->serviceYamls['app']['core'] = 'core/core.services.yml';
$this->serviceProviderClasses['app']['core'] = 'Drupal\Core\CoreServiceProvider';
// Retrieve enabled modules and register their namespaces.

catch
committed
if (!isset($this->moduleList)) {
$extensions = $this->getConfigStorage()->read('core.extension');
// If core.extension configuration does not exist and we're not in the
// installer itself, then we need to put the kernel into a pre-installer
// mode. The container should not be dumped because Drupal is yet to be
// installed. The installer service provider is registered to ensure that
// cache and other automatically created tables are not created if
// database settings are available. None of this is required when the
// installer is running because the installer has its own kernel and
// manages the addition of its own service providers.
// @see install_begin_request()
if ($extensions === FALSE && !InstallerKernel::installationAttempted()) {
$this->allowDumping = FALSE;
$this->containerNeedsDumping = FALSE;
$GLOBALS['conf']['container_service_providers']['InstallerServiceProvider'] = 'Drupal\Core\Installer\InstallerServiceProvider';
}
$this->moduleList = $extensions['module'] ?? [];

catch
committed
}

Alex Pott
committed
$module_filenames = $this->getModuleFileNames();
$this->classLoaderAddMultiplePsr4($this->getModuleNamespacesPsr4($module_filenames));
// Load each module's serviceProvider class.
foreach ($module_filenames as $module => $filename) {
$name = "{$camelized}ServiceProvider";
$class = "Drupal\\{$module}\\{$name}";
if (class_exists($class)) {
$this->serviceProviderClasses['app'][$module] = $class;
$filename = dirname($filename) . "/$module.services.yml";
if (is_file($filename)) {
$this->serviceYamls['app'][$module] = $filename;

Alex Pott
committed
}
// Add site-specific service providers.
if (!empty($GLOBALS['conf']['container_service_providers'])) {
foreach ($GLOBALS['conf']['container_service_providers'] as $class) {
if ((is_string($class) && class_exists($class)) || (is_object($class) && ($class instanceof ServiceProviderInterface || $class instanceof ServiceModifierInterface))) {
$this->serviceProviderClasses['site'][] = $class;
}

catch
committed
}
}
$this->addServiceFiles(Settings::get('container_yamls', []));
}
/**
* {@inheritdoc}
*/
public function getServiceProviders($origin) {
return $this->serviceProviders[$origin];
}
/**
* {@inheritdoc}
*/
public function terminate(Request $request, Response $response): void {
if ($this->booted && $this->getHttpKernel() instanceof TerminableInterface) {
// Only run terminate() when essential services have been set up properly
// by preHandle() before.
if ($this->prepared === TRUE) {
$this->getHttpKernel()->terminate($request, $response);
}
// For destructable services, always call the destruct method if they were
// initialized during the request. Destruction is not necessary if the
// service was not used.
foreach ($this->container->getParameter('kernel.destructable_services') as $id) {
if ($this->container->initialized($id)) {
$service = $this->container->get($id);
$service->destruct();
}
}
}
}
/**
* {@inheritdoc}
*/
public function handle(Request $request, $type = self::MAIN_REQUEST, $catch = TRUE): Response {

Alex Pott
committed
// Ensure sane PHP environment variables.
static::bootEnvironment();
try {
if (!$this->booted) {
$this->initializeSettings($request);

Alex Pott
committed
$this->boot();
}
$response = $this->getHttpKernel()->handle($request, $type, $catch);

Alex Pott
committed
}
catch (\Exception $e) {
if ($catch === FALSE) {
throw $e;
}
$response = $this->handleException($e, $request, $type);
}
// Adapt response headers to the current request.
$response->prepare($request);
return $response;
}
/**
* Converts an exception into a response.
*
* @param \Exception $e
* An exception

catch
committed
* @param \Symfony\Component\HttpFoundation\Request $request

Alex Pott
committed
* A Request instance
* @param int $type
* The type of the request (one of HttpKernelInterface::MAIN_REQUEST or

Alex Pott
committed
* HttpKernelInterface::SUB_REQUEST)
*

catch
committed
* @return \Symfony\Component\HttpFoundation\Response

Alex Pott
committed
* A Response instance

Alex Pott
committed
*
* @throws \Exception
* If the passed in exception cannot be turned into a response.

Alex Pott
committed
*/
protected function handleException(\Exception $e, $request, $type) {
if ($this->shouldRedirectToInstaller($e, $this->container ? $this->container->get('database') : NULL)) {
return new RedirectResponse($request->getBasePath() . '/core/install.php', 302, ['Cache-Control' => 'no-cache']);
}

Alex Pott
committed
if ($e instanceof HttpExceptionInterface) {
$response = new Response($e->getMessage(), $e->getStatusCode());
$response->headers->add($e->getHeaders());
return $response;
}
throw $e;
}

catch
committed
/**
* Returns module data on the filesystem.
*

Lee Rowlands
committed
* @param string $module

catch
committed
* The name of the module.
*
* @return \Drupal\Core\Extension\Extension|bool
* Returns an Extension object if the module is found, FALSE otherwise.

catch
committed
*/
protected function moduleData($module) {
if (!$this->moduleData) {
// First, find profiles.
$listing = new ExtensionDiscovery($this->root);
$listing->setProfileDirectories([]);

catch
committed
$all_profiles = $listing->scan('profile');
$profiles = array_intersect_key($all_profiles, $this->moduleList);

catch
committed
$profile_directories = array_map(function (Extension $profile) {

catch
committed
return $profile->getPath();
}, $profiles);
$listing->setProfileDirectories($profile_directories);

catch
committed
// Now find modules.

catch
committed
$this->moduleData = $profiles + $listing->scan('module');

catch
committed
}
return $this->moduleData[$module] ?? FALSE;

catch
committed
}

Angie Byron
committed
/**
* Implements Drupal\Core\DrupalKernelInterface::updateModules().
*
* @todo Remove obsolete $module_list parameter. Only $module_filenames is
* needed.

Angie Byron
committed
*/
public function updateModules(array $module_list, array $module_filenames = []) {
$pre_existing_module_namespaces = [];
if ($this->booted && is_array($this->moduleList)) {
$pre_existing_module_namespaces = $this->getModuleNamespacesPsr4($this->getModuleFileNames());
}
$this->moduleList = $module_list;
foreach ($module_filenames as $name => $extension) {
$this->moduleData[$name] = $extension;

catch
committed
}

Angie Byron
committed
// If we haven't yet booted, we don't need to do anything: the new module
// list will take effect when boot() is called. However we set a
// flag that the container needs a rebuild, so that a potentially cached
// container is not used. If we have already booted, then rebuild the
// container in order to refresh the serviceProvider list and container.
$this->containerNeedsRebuild = TRUE;

Angie Byron
committed
if ($this->booted) {
// We need to register any new namespaces to a new class loader because
// the current class loader might have stored a negative result for a
// class that is now available.
// @see \Composer\Autoload\ClassLoader::findFile()
$new_namespaces = array_diff_key(
$this->getModuleNamespacesPsr4($this->getModuleFileNames()),
$pre_existing_module_namespaces
);
if (!empty($new_namespaces)) {
$additional_class_loader = new ClassLoader();
$this->classLoaderAddMultiplePsr4($new_namespaces, $additional_class_loader);
$additional_class_loader->register();
}
$this->initializeContainer();

Angie Byron
committed
}
}

catch
committed
/**
* Returns the container cache key based on the environment.

catch
committed
*
* The 'environment' consists of:
* - The kernel environment string.
* - The Drupal version constant.
* - The deployment identifier from settings.php. This allows custom
* deployments to force a container rebuild.
* - The operating system running PHP. This allows compiler passes to optimize
* services for different operating systems.
* - The paths to any additional container YAMLs from settings.php.
*

catch
committed
* @return string
* The cache key used for the service container.

catch
committed
*/
protected function getContainerCacheKey() {
$parts = ['service_container', $this->environment, \Drupal::VERSION, Settings::get('deployment_identifier'), PHP_OS, serialize(Settings::get('container_yamls'))];
return implode(':', $parts);

Alex Pott
committed
}
/**
* Returns the kernel parameters.
*
* @return array
* An associative array of kernel parameters
*/
protected function getKernelParameters() {
return [
'kernel.environment' => $this->environment,
];
}
/**
* Initializes the service container.
*
* @return \Symfony\Component\DependencyInjection\ContainerInterface
* An initialized container object.
protected function initializeContainer() {
$this->containerNeedsDumping = FALSE;

Alex Pott
committed
$session_started = FALSE;
$all_messages = [];
if (isset($this->container)) {
// Save the id of the currently logged in user.
if ($this->container->initialized('current_user')) {
$current_user_id = $this->container->get('current_user')->id();
}
// After rebuilding the container some objects will have stale services.
// Record a map of objects to service IDs prior to rebuilding the
// container in order to ensure
// \Drupal\Core\DependencyInjection\DependencySerializationTrait works as
// expected.
$this->container->get(ReverseContainer::class)->recordContainer();

Alex Pott
committed
// If there is a session, close and save it.
if ($this->container->initialized('session')) {
$session = $this->container->get('session');
if ($session->isStarted()) {
$session_started = TRUE;
$session->save();

Alex Pott
committed
unset($session);
$all_messages = $this->container->get('messenger')->all();
}

catch
committed
// If the module list hasn't already been set in updateModules and we are
// not forcing a rebuild, then try and load the container from the cache.
if (empty($this->moduleList) && !$this->containerNeedsRebuild) {
$container_definition = $this->getCachedContainerDefinition();

catch
committed
// If there is no cached container definition, build a new container from
// scratch.
if (!isset($container_definition)) {
$container = $this->compileContainer();
// Only dump the container if dumping is allowed. This is useful for
// KernelTestBase, which never wants to use the real container, but always
// the container builder.
if ($this->allowDumping) {
$dumper = new $this->phpArrayDumperClass($container);
$container_definition = $dumper->getArray();
}
}
// The container was rebuilt successfully.
$this->containerNeedsRebuild = FALSE;
// Only create a new class if we have a container definition.
if (isset($container_definition)) {
// Drupal provides two dynamic parameters to access specific paths that
// are determined from the request.
$container_definition['parameters']['app.root'] = $this->getAppRoot();
$container_definition['parameters']['site.path'] = $this->getSitePath();
$class = Settings::get('container_base_class', '\Drupal\Core\DependencyInjection\Container');
$container = new $class($container_definition);
}
$this->attachSynthetic($container);
$this->container = $container;

Alex Pott
committed
if ($session_started) {
$this->container->get('session')->start();

Alex Pott
committed
// The request stack is preserved across container rebuilds. Re-inject the
// new session into the main request if one was present before.

Alex Pott
committed
if (($request_stack = $this->container->get('request_stack', ContainerInterface::NULL_ON_INVALID_REFERENCE))) {
if ($request = $request_stack->getMainRequest()) {
$subrequest = TRUE;
$request->setSession($this->container->get('session'));

Alex Pott
committed
}
}
if (!empty($current_user_id)) {
$this->container->get('current_user')->setInitialAccountId($current_user_id);
}
// Re-add messages.
foreach ($all_messages as $type => $messages) {
foreach ($messages as $message) {
$this->container->get('messenger')->addMessage($message, $type);
}
}
\Drupal::setContainer($this->container);
// Allow other parts of the codebase to react on container initialization in
// subrequest.
if (!empty($subrequest)) {
$this->container->get('event_dispatcher')->dispatch(new Event(), self::CONTAINER_INITIALIZE_SUBREQUEST_FINISHED);
}
// If needs dumping flag was set, dump the container.
if ($this->containerNeedsDumping && !$this->cacheDrupalContainer($container_definition)) {
$this->container->get('logger.factory')->get('DrupalKernel')->error('Container cannot be saved to cache.');
return $this->container;
}
/**
* Setup a consistent PHP environment.
*
* This method sets PHP environment options we want to be sure are set
* correctly for security or just saneness.
*
* @param string $app_root
* (optional) The path to the application root as a string. If not supplied,
* the application root will be computed.
*/
public static function bootEnvironment($app_root = NULL) {
if (static::$isEnvironmentInitialized) {
return;
}
// Determine the application root if it's not supplied.
if ($app_root === NULL) {
$app_root = static::guessApplicationRoot();
}

catch
committed
error_reporting(E_ALL);
// Override PHP settings required for Drupal to work properly.
// sites/default/default.settings.php contains more runtime settings.
// The .htaccess file contains settings that cannot be changed at runtime.

catch
committed
if (PHP_SAPI !== 'cli') {
// Use session cookies, not transparent sessions that puts the session id
// in the query string.
ini_set('session.use_cookies', '1');
if (\PHP_VERSION_ID < 80400) {
ini_set('session.use_only_cookies', '1');
ini_set('session.use_trans_sid', '0');