annotate core/lib/Drupal/Core/DrupalKernel.php @ 12:7a779792577d

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