annotate core/lib/Drupal/Core/DrupalKernel.php @ 14:1fec387a4317

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