DrupalKernel.php 54.5 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Core;

5
use Composer\Autoload\ClassLoader;
6
use Drupal\Component\Assertion\Handle;
7
use Drupal\Component\FileCache\FileCacheFactory;
8 9
use Drupal\Component\Utility\Unicode;
use Drupal\Component\Utility\UrlHelper;
10
use Drupal\Core\Cache\DatabaseBackend;
11
use Drupal\Core\Config\BootstrapConfigStorageFactory;
12
use Drupal\Core\Config\NullStorage;
13
use Drupal\Core\Database\Database;
14
use Drupal\Core\DependencyInjection\ContainerBuilder;
15
use Drupal\Core\DependencyInjection\ServiceModifierInterface;
16
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
17
use Drupal\Core\DependencyInjection\YamlFileLoader;
18
use Drupal\Core\Extension\ExtensionDiscovery;
19
use Drupal\Core\File\MimeType\MimeTypeGuesser;
20
use Drupal\Core\Http\TrustedHostsRequestFactory;
21
use Drupal\Core\Installer\InstallerRedirectTrait;
22
use Drupal\Core\Language\Language;
23
use Drupal\Core\Security\RequestSanitizer;
24
use Drupal\Core\Site\Settings;
25
use Drupal\Core\Test\TestDatabase;
26
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
27
use Symfony\Component\ClassLoader\ApcClassLoader;
28 29
use Symfony\Component\ClassLoader\WinCacheClassLoader;
use Symfony\Component\ClassLoader\XcacheClassLoader;
30
use Symfony\Component\DependencyInjection\ContainerInterface;
31
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
32
use Symfony\Component\HttpFoundation\RedirectResponse;
33 34
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
35
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
36
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
37
use Symfony\Component\HttpKernel\TerminableInterface;
38
use Symfony\Component\Routing\Route;
39 40 41

/**
 * The DrupalKernel class is the core of Drupal itself.
42 43
 *
 * This class is responsible for building the Dependency Injection Container and
44 45 46 47 48 49 50 51
 * also deals with the registration of service providers. It allows registered
 * service providers to add their services to the container. Core provides the
 * CoreServiceProvider, which, in addition to registering any core services that
 * cannot be registered in the core.services.yaml file, adds any compiler passes
 * needed by core, e.g. for processing tagged services. Each module can add its
 * own service provider, i.e. a class implementing
 * Drupal\Core\DependencyInjection\ServiceProvider, to register services to the
 * container, or modify existing services.
52
 */
53
class DrupalKernel implements DrupalKernelInterface, TerminableInterface {
54
  use InstallerRedirectTrait;
55

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
  /**
   * Holds the class used for dumping the container to a PHP array.
   *
   * In combination with swapping the container class this is useful to e.g.
   * dump to the human-readable PHP array format to debug the container
   * definition in an easier way.
   *
   * @var string
   */
  protected $phpArrayDumperClass = '\Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper';

  /**
   * Holds the default bootstrap container definition.
   *
   * @var array
   */
  protected $defaultBootstrapContainerDefinition = [
    'parameters' => [],
    'services' => [
      'database' => [
        'class' => 'Drupal\Core\Database\Connection',
        'factory' => 'Drupal\Core\Database\Database::getConnection',
        'arguments' => ['default'],
      ],
      'cache.container' => [
        'class' => 'Drupal\Core\Cache\DatabaseBackend',
82
        'arguments' => ['@database', '@cache_tags_provider.container', 'container', DatabaseBackend::MAXIMUM_NONE],
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
      ],
      'cache_tags_provider.container' => [
        'class' => 'Drupal\Core\Cache\DatabaseCacheTagsChecksum',
        'arguments' => ['@database'],
      ],
    ],
  ];

  /**
   * Holds the class used for instantiating the bootstrap container.
   *
   * @var string
   */
  protected $bootstrapContainerClass = '\Drupal\Component\DependencyInjection\PhpArrayContainer';

  /**
   * Holds the bootstrap container.
   *
   * @var \Symfony\Component\DependencyInjection\ContainerInterface
   */
  protected $bootstrapContainer;

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
  /**
   * Holds the container instance.
   *
   * @var \Symfony\Component\DependencyInjection\ContainerInterface
   */
  protected $container;

  /**
   * The environment, e.g. 'testing', 'install'.
   *
   * @var string
   */
  protected $environment;

  /**
   * Whether the kernel has been booted.
   *
   * @var bool
   */
124
  protected $booted = FALSE;
125

126 127 128 129 130 131 132
  /**
   * Whether essential services have been set up properly by preHandle().
   *
   * @var bool
   */
  protected $prepared = FALSE;

133 134 135 136
  /**
   * Holds the list of enabled modules.
   *
   * @var array
137 138
   *   An associative array whose keys are module names and whose values are
   *   ignored.
139 140 141
   */
  protected $moduleList;

142
  /**
143
   * List of available modules and installation profiles.
144
   *
145
   * @var \Drupal\Core\Extension\Extension[]
146
   */
147
  protected $moduleData = [];
148

149
  /**
150
   * The class loader object.
151
   *
152
   * @var \Composer\Autoload\ClassLoader
153 154 155
   */
  protected $classLoader;

156 157 158 159 160 161 162 163 164 165 166 167 168 169
  /**
   * Config storage object used for reading enabled modules configuration.
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
  protected $configStorage;

  /**
   * Whether the container can be dumped.
   *
   * @var bool
   */
  protected $allowDumping;

170 171 172 173 174 175 176
  /**
   * Whether the container needs to be rebuilt the next time it is initialized.
   *
   * @var bool
   */
  protected $containerNeedsRebuild = FALSE;

177 178 179 180 181 182 183
  /**
   * Whether the container needs to be dumped once booting is complete.
   *
   * @var bool
   */
  protected $containerNeedsDumping;

184
  /**
185 186 187 188 189 190
   * List of discovered services.yml pathnames.
   *
   * This is a nested array whose top-level keys are 'app' and 'site', denoting
   * the origin of a service provider. Site-specific providers have to be
   * collected separately, because they need to be processed last, so as to be
   * able to override services from application service providers.
191 192 193 194 195
   *
   * @var array
   */
  protected $serviceYamls;

196
  /**
197
   * List of discovered service provider class names or objects.
198 199 200 201 202 203
   *
   * This is a nested array whose top-level keys are 'app' and 'site', denoting
   * the origin of a service provider. Site-specific providers have to be
   * collected separately, because they need to be processed last, so as to be
   * able to override services from application service providers.
   *
204 205 206
   * Allowing objects is for example used to allow
   * \Drupal\KernelTests\KernelTestBase to register itself as service provider.
   *
207 208 209 210 211 212 213 214
   * @var array
   */
  protected $serviceProviderClasses;

  /**
   * List of instantiated service provider classes.
   *
   * @see \Drupal\Core\DrupalKernel::$serviceProviderClasses
215 216 217 218 219
   *
   * @var array
   */
  protected $serviceProviders;

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
  /**
   * Whether the PHP environment has been initialized.
   *
   * This legacy phase can only be booted once because it sets session INI
   * settings. If a session has already been started, re-generating these
   * settings would break the session.
   *
   * @var bool
   */
  protected static $isEnvironmentInitialized = FALSE;

  /**
   * The site directory.
   *
   * @var string
   */
  protected $sitePath;

238 239 240 241 242 243 244
  /**
   * The app root.
   *
   * @var string
   */
  protected $root;

245 246 247 248
  /**
   * Create a DrupalKernel object from a request.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
249 250 251 252 253
   *   The request.
   * @param $class_loader
   *   The class loader. Normally Composer's ClassLoader, as included by the
   *   front controller, but may also be decorated; e.g.,
   *   \Symfony\Component\ClassLoader\ApcClassLoader.
254 255 256 257 258
   * @param string $environment
   *   String indicating the environment, e.g. 'prod' or 'dev'.
   * @param bool $allow_dumping
   *   (optional) FALSE to stop the container from being written to or read
   *   from disk. Defaults to TRUE.
259 260 261
   * @param string $app_root
   *   (optional) The path to the application root as a string. If not supplied,
   *   the application root will be computed.
262
   *
263
   * @return static
264 265 266
   *
   * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
   *   In case the host name in the request is not trusted.
267
   */
268 269 270
  public static function createFromRequest(Request $request, $class_loader, $environment, $allow_dumping = TRUE, $app_root = NULL) {
    $kernel = new static($environment, $class_loader, $allow_dumping, $app_root);
    static::bootEnvironment($app_root);
271
    $kernel->initializeSettings($request);
272 273 274
    return $kernel;
  }

275 276 277 278
  /**
   * Constructs a DrupalKernel object.
   *
   * @param string $environment
279
   *   String indicating the environment, e.g. 'prod' or 'dev'.
280 281 282 283
   * @param $class_loader
   *   The class loader. Normally \Composer\Autoload\ClassLoader, as included by
   *   the front controller, but may also be decorated; e.g.,
   *   \Symfony\Component\ClassLoader\ApcClassLoader.
284 285 286
   * @param bool $allow_dumping
   *   (optional) FALSE to stop the container from being written to or read
   *   from disk. Defaults to TRUE.
287 288 289
   * @param string $app_root
   *   (optional) The path to the application root as a string. If not supplied,
   *   the application root will be computed.
290
   */
291
  public function __construct($environment, $class_loader, $allow_dumping = TRUE, $app_root = NULL) {
292
    $this->environment = $environment;
293
    $this->classLoader = $class_loader;
294
    $this->allowDumping = $allow_dumping;
295 296 297 298 299 300 301 302 303 304 305 306 307 308
    if ($app_root === NULL) {
      $app_root = static::guessApplicationRoot();
    }
    $this->root = $app_root;
  }

  /**
   * Determine the application root directory based on assumptions.
   *
   * @return string
   *   The application root.
   */
  protected static function guessApplicationRoot() {
    return dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
  }

  /**
   * Returns the appropriate site directory for a request.
   *
   * Once the kernel has been created DrupalKernelInterface::getSitePath() is
   * preferred since it gets the statically cached result of this method.
   *
   * Site directories contain all site specific code. This includes settings.php
   * for bootstrap level configuration, file configuration stores, public file
   * storage and site specific modules and themes.
   *
   * Finds a matching site directory file by stripping the website's hostname
   * from left to right and pathname from right to left. By default, the
   * directory must contain a 'settings.php' file for it to match. If the
   * parameter $require_settings is set to FALSE, then a directory without a
   * 'settings.php' file will match as well. The first configuration file found
   * will be used and the remaining ones will be ignored. If no configuration
   * file is found, returns a default value 'sites/default'. See
   * default.settings.php for examples on how the URL is converted to a
   * directory.
   *
   * If a file named sites.php is present in the sites directory, it will be
   * loaded prior to scanning for directories. That file can define aliases in
   * an associative array named $sites. The array is written in the format
   * '<port>.<domain>.<path>' => 'directory'. As an example, to create a
335
   * directory alias for https://www.drupal.org:8080/mysite/test whose
336 337 338 339 340 341 342 343 344 345 346 347 348 349
   * configuration file is in sites/example.com, the array should be defined as:
   * @code
   * $sites = array(
   *   '8080.www.drupal.org.mysite.test' => 'example.com',
   * );
   * @endcode
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   * @param bool $require_settings
   *   Only directories with an existing settings.php file will be recognized.
   *   Defaults to TRUE. During initial installation, this is set to FALSE so
   *   that Drupal can detect a matching directory, then create a new
   *   settings.php file in it.
350 351 352
   * @param string $app_root
   *   (optional) The path to the application root as a string. If not supplied,
   *   the application root will be computed.
353 354 355 356
   *
   * @return string
   *   The path of the matching directory.
   *
357 358 359
   * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
   *   In case the host name in the request is invalid.
   *
360 361 362 363 364
   * @see \Drupal\Core\DrupalKernelInterface::getSitePath()
   * @see \Drupal\Core\DrupalKernelInterface::setSitePath()
   * @see default.settings.php
   * @see example.sites.php
   */
365
  public static function findSitePath(Request $request, $require_settings = TRUE, $app_root = NULL) {
366 367 368 369
    if (static::validateHostname($request) === FALSE) {
      throw new BadRequestHttpException();
    }

370 371 372 373
    if ($app_root === NULL) {
      $app_root = static::guessApplicationRoot();
    }

374 375
    // Check for a simpletest override.
    if ($test_prefix = drupal_valid_test_ua()) {
376 377
      $test_db = new TestDatabase($test_prefix);
      return $test_db->getTestSitePath();
378 379 380
    }

    // Determine whether multi-site functionality is enabled.
381
    if (!file_exists($app_root . '/sites/sites.php')) {
382 383 384 385 386 387 388 389
      return 'sites/default';
    }

    // Otherwise, use find the site path using the request.
    $script_name = $request->server->get('SCRIPT_NAME');
    if (!$script_name) {
      $script_name = $request->server->get('SCRIPT_FILENAME');
    }
390
    $http_host = $request->getHttpHost();
391

392
    $sites = [];
393
    include $app_root . '/sites/sites.php';
394 395 396 397 398 399

    $uri = explode('/', $script_name);
    $server = explode('.', implode('.', array_reverse(explode(':', rtrim($http_host, '.')))));
    for ($i = count($uri) - 1; $i > 0; $i--) {
      for ($j = count($server); $j > 0; $j--) {
        $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
400
        if (isset($sites[$dir]) && file_exists($app_root . '/sites/' . $sites[$dir])) {
401 402
          $dir = $sites[$dir];
        }
403
        if (file_exists($app_root . '/sites/' . $dir . '/settings.php') || (!$require_settings && file_exists($app_root . '/sites/' . $dir))) {
404 405 406 407 408 409 410 411 412 413 414
          return "sites/$dir";
        }
      }
    }
    return 'sites/default';
  }

  /**
   * {@inheritdoc}
   */
  public function setSitePath($path) {
415
    if ($this->booted && $path !== $this->sitePath) {
416 417
      throw new \LogicException('Site path cannot be changed after calling boot()');
    }
418 419 420 421 422 423 424 425
    $this->sitePath = $path;
  }

  /**
   * {@inheritdoc}
   */
  public function getSitePath() {
    return $this->sitePath;
426 427
  }

428 429 430 431 432 433 434
  /**
   * {@inheritdoc}
   */
  public function getAppRoot() {
    return $this->root;
  }

435
  /**
436
   * {@inheritdoc}
437 438 439
   */
  public function boot() {
    if ($this->booted) {
440 441 442 443 444 445
      return $this;
    }

    // Ensure that findSitePath is set.
    if (!$this->sitePath) {
      throw new \Exception('Kernel does not have site path set before calling boot()');
446
    }
447 448 449 450 451 452 453 454 455 456

    // Initialize the FileCacheFactory component. We have to do it here instead
    // of in \Drupal\Component\FileCache\FileCacheFactory because we can not use
    // the Settings object in a component.
    $configuration = Settings::get('file_cache');

    // Provide a default configuration, if not set.
    if (!isset($configuration['default'])) {
      // @todo Use extension_loaded('apcu') for non-testbot
      //  https://www.drupal.org/node/2447753.
457
      if (function_exists('apcu_fetch')) {
458 459 460 461 462 463
        $configuration['default']['cache_backend_class'] = '\Drupal\Component\FileCache\ApcuFileCacheBackend';
      }
    }
    FileCacheFactory::setConfiguration($configuration);
    FileCacheFactory::setPrefix(Settings::getApcuPrefix('file_cache', $this->root));

464 465
    $this->bootstrapContainer = new $this->bootstrapContainerClass(Settings::get('bootstrap_container_definition', $this->defaultBootstrapContainerDefinition));

466
    // Initialize the container.
467
    $this->initializeContainer();
468

469
    $this->booted = TRUE;
470 471

    return $this;
472 473
  }

474
  /**
475
   * {@inheritdoc}
476
   */
477 478 479 480
  public function shutdown() {
    if (FALSE === $this->booted) {
      return;
    }
481
    $this->container->get('stream_wrapper_manager')->unregister();
482
    $this->booted = FALSE;
483
    $this->container = NULL;
484
    $this->moduleList = NULL;
485
    $this->moduleData = [];
486 487 488 489 490 491 492 493 494
  }

  /**
   * {@inheritdoc}
   */
  public function getContainer() {
    return $this->container;
  }

495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
  /**
   * {@inheritdoc}
   */
  public function setContainer(ContainerInterface $container = NULL) {
    if (isset($this->container)) {
      throw new \Exception('The container should not override an existing container.');
    }
    if ($this->booted) {
      throw new \Exception('The container cannot be set after a booted kernel.');
    }

    $this->container = $container;
    return $this;
  }

510 511 512 513 514 515 516 517 518 519 520 521 522
  /**
   * {@inheritdoc}
   */
  public function getCachedContainerDefinition() {
    $cache = $this->bootstrapContainer->get('cache.container')->get($this->getContainerCacheKey());

    if ($cache) {
      return $cache->data;
    }

    return NULL;
  }

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
  /**
   * {@inheritdoc}
   */
  public function loadLegacyIncludes() {
    require_once $this->root . '/core/includes/common.inc';
    require_once $this->root . '/core/includes/database.inc';
    require_once $this->root . '/core/includes/module.inc';
    require_once $this->root . '/core/includes/theme.inc';
    require_once $this->root . '/core/includes/pager.inc';
    require_once $this->root . '/core/includes/menu.inc';
    require_once $this->root . '/core/includes/tablesort.inc';
    require_once $this->root . '/core/includes/file.inc';
    require_once $this->root . '/core/includes/unicode.inc';
    require_once $this->root . '/core/includes/form.inc';
    require_once $this->root . '/core/includes/errors.inc';
    require_once $this->root . '/core/includes/schema.inc';
    require_once $this->root . '/core/includes/entity.inc';
  }

542
  /**
543
   * {@inheritdoc}
544
   */
545
  public function preHandle(Request $request) {
546 547 548 549 550 551
    // Sanitize the request.
    $request = RequestSanitizer::sanitize(
      $request,
      (array) Settings::get(RequestSanitizer::SANITIZE_WHITELIST, []),
      (bool) Settings::get(RequestSanitizer::SANITIZE_LOG, FALSE)
    );
552 553 554

    $this->loadLegacyIncludes();

555 556 557
    // Load all enabled modules.
    $this->container->get('module_handler')->loadAll();

558 559 560
    // Register stream wrappers.
    $this->container->get('stream_wrapper_manager')->register();

561 562 563
    // Initialize legacy request globals.
    $this->initializeRequestGlobals($request);

564 565
    // Put the request on the stack.
    $this->container->get('request_stack')->push($request);
566

567 568
    // Set the allowed protocols.
    UrlHelper::setAllowedProtocols($this->container->getParameter('filter_protocols'));
569

570
    // Override of Symfony's MIME type guesser singleton.
571
    MimeTypeGuesser::registerWithSymfonyGuesser($this->container);
572

573
    $this->prepared = TRUE;
574 575
  }

576 577 578 579
  /**
   * {@inheritdoc}
   */
  public function discoverServiceProviders() {
580 581 582 583 584 585 586 587
    $this->serviceYamls = [
      'app' => [],
      'site' => [],
    ];
    $this->serviceProviderClasses = [
      'app' => [],
      'site' => [],
    ];
588 589
    $this->serviceYamls['app']['core'] = 'core/core.services.yml';
    $this->serviceProviderClasses['app']['core'] = 'Drupal\Core\CoreServiceProvider';
590

591
    // Retrieve enabled modules and register their namespaces.
592
    if (!isset($this->moduleList)) {
593
      $extensions = $this->getConfigStorage()->read('core.extension');
594
      $this->moduleList = isset($extensions['module']) ? $extensions['module'] : [];
595
    }
596
    $module_filenames = $this->getModuleFileNames();
597
    $this->classLoaderAddMultiplePsr4($this->getModuleNamespacesPsr4($module_filenames));
598

599
    // Load each module's serviceProvider class.
600
    foreach ($module_filenames as $module => $filename) {
katbailey's avatar
katbailey committed
601
      $camelized = ContainerBuilder::camelize($module);
602 603
      $name = "{$camelized}ServiceProvider";
      $class = "Drupal\\{$module}\\{$name}";
604
      if (class_exists($class)) {
605
        $this->serviceProviderClasses['app'][$module] = $class;
606
      }
607
      $filename = dirname($filename) . "/$module.services.yml";
608
      if (file_exists($filename)) {
609
        $this->serviceYamls['app'][$module] = $filename;
610
      }
611
    }
612

613
    // Add site-specific service providers.
614
    if (!empty($GLOBALS['conf']['container_service_providers'])) {
615
      foreach ($GLOBALS['conf']['container_service_providers'] as $class) {
616
        if ((is_string($class) && class_exists($class)) || (is_object($class) && ($class instanceof ServiceProviderInterface || $class instanceof ServiceModifierInterface))) {
617 618
          $this->serviceProviderClasses['site'][] = $class;
        }
619 620
      }
    }
621
    $this->addServiceFiles(Settings::get('container_yamls', []));
622 623 624 625 626
  }

  /**
   * {@inheritdoc}
   */
627 628
  public function getServiceProviders($origin) {
    return $this->serviceProviders[$origin];
629 630 631 632 633 634
  }

  /**
   * {@inheritdoc}
   */
  public function terminate(Request $request, Response $response) {
635 636 637
    // Only run terminate() when essential services have been set up properly
    // by preHandle() before.
    if (FALSE === $this->prepared) {
638 639 640 641 642 643 644 645 646 647 648
      return;
    }

    if ($this->getHttpKernel() instanceof TerminableInterface) {
      $this->getHttpKernel()->terminate($request, $response);
    }
  }

  /**
   * {@inheritdoc}
   */
649
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
650 651 652 653 654 655 656 657 658 659
    // Ensure sane PHP environment variables.
    static::bootEnvironment();

    try {
      $this->initializeSettings($request);

      // Redirect the user to the installation script if Drupal has not been
      // installed yet (i.e., if no $databases array has been defined in the
      // settings.php file) and we are not already installing.
      if (!Database::getConnectionInfo() && !drupal_installation_attempted() && PHP_SAPI !== 'cli') {
660
        $response = new RedirectResponse($request->getBasePath() . '/core/install.php', 302, ['Cache-Control' => 'no-cache']);
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
      }
      else {
        $this->boot();
        $response = $this->getHttpKernel()->handle($request, $type, $catch);
      }
    }
    catch (\Exception $e) {
      if ($catch === FALSE) {
        throw $e;
      }

      $response = $this->handleException($e, $request, $type);
    }

    // Adapt response headers to the current request.
    $response->prepare($request);

    return $response;
  }

  /**
   * Converts an exception into a response.
   *
   * @param \Exception $e
   *   An exception
686
   * @param \Symfony\Component\HttpFoundation\Request $request
687 688 689 690 691
   *   A Request instance
   * @param int $type
   *   The type of the request (one of HttpKernelInterface::MASTER_REQUEST or
   *   HttpKernelInterface::SUB_REQUEST)
   *
692
   * @return \Symfony\Component\HttpFoundation\Response
693
   *   A Response instance
694 695 696
   *
   * @throws \Exception
   *   If the passed in exception cannot be turned into a response.
697 698
   */
  protected function handleException(\Exception $e, $request, $type) {
699 700 701 702
    if ($this->shouldRedirectToInstaller($e, $this->container ? $this->container->get('database') : NULL)) {
      return new RedirectResponse($request->getBasePath() . '/core/install.php', 302, ['Cache-Control' => 'no-cache']);
    }

703 704 705 706 707
    if ($e instanceof HttpExceptionInterface) {
      $response = new Response($e->getMessage(), $e->getStatusCode());
      $response->headers->add($e->getHeaders());
      return $response;
    }
708 709

    throw $e;
710 711
  }

712 713 714 715 716 717
  /**
   * {@inheritdoc}
   */
  public function prepareLegacyRequest(Request $request) {
    $this->boot();
    $this->preHandle($request);
718 719 720 721 722
    // Setup services which are normally initialized from within stack
    // middleware or during the request kernel event.
    if (PHP_SAPI !== 'cli') {
      $request->setSession($this->container->get('session'));
    }
723 724
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
725 726 727 728 729
    $this->container->get('request_stack')->push($request);
    $this->container->get('router.request_context')->fromRequest($request);
    return $this;
  }

730 731 732 733 734 735
  /**
   * Returns module data on the filesystem.
   *
   * @param $module
   *   The name of the module.
   *
736 737
   * @return \Drupal\Core\Extension\Extension|bool
   *   Returns an Extension object if the module is found, FALSE otherwise.
738 739 740
   */
  protected function moduleData($module) {
    if (!$this->moduleData) {
741
      // First, find profiles.
742
      $listing = new ExtensionDiscovery($this->root);
743
      $listing->setProfileDirectories([]);
744 745 746
      $all_profiles = $listing->scan('profile');
      $profiles = array_intersect_key($all_profiles, $this->moduleList);

747 748
      // If a module is within a profile directory but specifies another
      // profile for testing, it needs to be found in the parent profile.
749
      $settings = $this->getConfigStorage()->read('simpletest.settings');
750 751
      $parent_profile = !empty($settings['parent_profile']) ? $settings['parent_profile'] : NULL;
      if ($parent_profile && !isset($profiles[$parent_profile])) {
752 753
        // In case both profile directories contain the same extension, the
        // actual profile always has precedence.
754
        $profiles = [$parent_profile => $all_profiles[$parent_profile]] + $profiles;
755
      }
756 757 758 759 760 761

      $profile_directories = array_map(function ($profile) {
        return $profile->getPath();
      }, $profiles);
      $listing->setProfileDirectories($profile_directories);

762
      // Now find modules.
763
      $this->moduleData = $profiles + $listing->scan('module');
764 765 766 767
    }
    return isset($this->moduleData[$module]) ? $this->moduleData[$module] : FALSE;
  }

768 769
  /**
   * Implements Drupal\Core\DrupalKernelInterface::updateModules().
770 771 772
   *
   * @todo Remove obsolete $module_list parameter. Only $module_filenames is
   *   needed.
773
   */
774
  public function updateModules(array $module_list, array $module_filenames = []) {
775 776 777 778
    $pre_existing_module_namespaces = [];
    if ($this->booted && is_array($this->moduleList)) {
      $pre_existing_module_namespaces = $this->getModuleNamespacesPsr4($this->getModuleFileNames());
    }
779
    $this->moduleList = $module_list;
780 781
    foreach ($module_filenames as $name => $extension) {
      $this->moduleData[$name] = $extension;
782
    }
783

784
    // If we haven't yet booted, we don't need to do anything: the new module
785 786 787 788 789
    // list will take effect when boot() is called. However we set a
    // flag that the container needs a rebuild, so that a potentially cached
    // container is not used. If we have already booted, then rebuild the
    // container in order to refresh the serviceProvider list and container.
    $this->containerNeedsRebuild = TRUE;
790
    if ($this->booted) {
791 792 793 794 795 796 797 798 799 800 801 802 803 804
      // We need to register any new namespaces to a new class loader because
      // the current class loader might have stored a negative result for a
      // class that is now available.
      // @see \Composer\Autoload\ClassLoader::findFile()
      $new_namespaces = array_diff_key(
        $this->getModuleNamespacesPsr4($this->getModuleFileNames()),
        $pre_existing_module_namespaces
      );
      if (!empty($new_namespaces)) {
        $additional_class_loader = new ClassLoader();
        $this->classLoaderAddMultiplePsr4($new_namespaces, $additional_class_loader);
        $additional_class_loader->register();
      }

805
      $this->initializeContainer();
806 807
    }
  }
808

809
  /**
810
   * Returns the container cache key based on the environment.
811
   *
812 813 814 815 816 817 818 819 820
   * The 'environment' consists of:
   * - The kernel environment string.
   * - The Drupal version constant.
   * - The deployment identifier from settings.php. This allows custom
   *   deployments to force a container rebuild.
   * - The operating system running PHP. This allows compiler passes to optimize
   *   services for different operating systems.
   * - The paths to any additional container YAMLs from settings.php.
   *
821
   * @return string
822
   *   The cache key used for the service container.
823
   */
824
  protected function getContainerCacheKey() {
825
    $parts = ['service_container', $this->environment, \Drupal::VERSION, Settings::get('deployment_identifier'), PHP_OS, serialize(Settings::get('container_yamls'))];
826
    return implode(':', $parts);
827
  }
828 829 830 831 832 833 834

  /**
   * Returns the kernel parameters.
   *
   * @return array An array of kernel parameters
   */
  protected function getKernelParameters() {
835
    return [
836
      'kernel.environment' => $this->environment,
837
    ];
838 839
  }

840 841
  /**
   * Initializes the service container.
842 843
   *
   * @return \Symfony\Component\DependencyInjection\ContainerInterface
844
   */
845
  protected function initializeContainer() {
846
    $this->containerNeedsDumping = FALSE;
847
    $session_started = FALSE;
848
    if (isset($this->container)) {
849 850 851 852 853
      // Save the id of the currently logged in user.
      if ($this->container->initialized('current_user')) {
        $current_user_id = $this->container->get('current_user')->id();
      }

854 855 856 857 858 859
      // If there is a session, close and save it.
      if ($this->container->initialized('session')) {
        $session = $this->container->get('session');
        if ($session->isStarted()) {
          $session_started = TRUE;
          $session->save();
860
        }
861
        unset($session);
862
      }
863
    }
864

865 866 867 868
    // If we haven't booted yet but there is a container, then we're asked to
    // boot the container injected via setContainer().
    // @see \Drupal\KernelTests\KernelTestBase::setUp()
    if (isset($this->container) && !$this->booted) {
869
      $container = $this->container;
870 871
    }

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

878 879 880
    // If there is no container and no cached container definition, build a new
    // one from scratch.
    if (!isset($container) && !isset($container_definition)) {
881 882 883 884 885 886 887 888 889 890
      // Building the container creates 1000s of objects. Garbage collection of
      // these objects is expensive. This appears to be causing random
      // segmentation faults in PHP 5.6 due to
      // https://bugs.php.net/bug.php?id=72286. Once the container is rebuilt,
      // garbage collection is re-enabled.
      $disable_gc = version_compare(PHP_VERSION, '7', '<') && gc_enabled();
      if ($disable_gc) {
        gc_collect_cycles();
        gc_disable();
      }
891
      $container = $this->compileContainer();
892 893 894 895 896 897 898 899

      // Only dump the container if dumping is allowed. This is useful for
      // KernelTestBase, which never wants to use the real container, but always
      // the container builder.
      if ($this->allowDumping) {
        $dumper = new $this->phpArrayDumperClass($container);
        $container_definition = $dumper->getArray();
      }
900 901 902 903 904
      // If garbage collection was disabled prior to rebuilding container,
      // re-enable it.
      if ($disable_gc) {
        gc_enable();
      }
905 906
    }

907 908 909
    // The container was rebuilt successfully.
    $this->containerNeedsRebuild = FALSE;

910 911 912 913 914 915
    // Only create a new class if we have a container definition.
    if (isset($container_definition)) {
      $class = Settings::get('container_base_class', '\Drupal\Core\DependencyInjection\Container');
      $container = new $class($container_definition);
    }

916
    $this->attachSynthetic($container);
917 918

    $this->container = $container;
919 920
    if ($session_started) {
      $this->container->get('session')->start();
921
    }
922 923 924 925 926

    // The request stack is preserved across container rebuilds. Reinject the
    // new session into the master request if one was present before.
    if (($request_stack = $this->container->get('request_stack', ContainerInterface::NULL_ON_INVALID_REFERENCE))) {
      if ($request = $request_stack->getMasterRequest()) {
927
        $subrequest = TRUE;
928 929 930 931 932
        if ($request->hasSession()) {
          $request->setSession($this->container->get('session'));
        }
      }
    }
933 934 935 936 937

    if (!empty($current_user_id)) {
      $this->container->get('current_user')->setInitialAccountId($current_user_id);
    }

938
    \Drupal::setContainer($this->container);
939

940 941 942 943 944 945
    // Allow other parts of the codebase to react on container initialization in
    // subrequest.
    if (!empty($subrequest)) {
      $this->container->get('event_dispatcher')->dispatch(self::CONTAINER_INITIALIZE_SUBREQUEST_FINISHED);
    }

946
    // If needs dumping flag was set, dump the container.
947
    if ($this->containerNeedsDumping && !$this->cacheDrupalContainer($container_definition)) {
948
      $this->container->get('logger.factory')->get('DrupalKernel')->error('Container cannot be saved to cache.');
949 950
    }

951 952 953 954 955 956 957 958
    return $this->container;
  }

  /**
   * Setup a consistent PHP environment.
   *
   * This method sets PHP environment options we want to be sure are set
   * correctly for security or just saneness.
959 960 961 962
   *
   * @param string $app_root
   *   (optional) The path to the application root as a string. If not supplied,
   *   the application root will be computed.
963
   */
964
  public static function bootEnvironment($app_root = NULL) {
965 966 967 968
    if (static::$isEnvironmentInitialized) {
      return;
    }

969 970 971 972 973
    // Determine the application root if it's not supplied.
    if ($app_root === NULL) {
      $app_root = static::guessApplicationRoot();
    }

974
    // Include our bootstrap file.
975
    require_once $app_root . '/core/includes/bootstrap.inc';
976

977 978 979 980 981 982 983
    // Enforce E_STRICT, but allow users to set levels not part of E_STRICT.
    error_reporting(E_STRICT | E_ALL);

    // Override PHP settings required for Drupal to work properly.
    // sites/default/default.settings.php contains more runtime settings.
    // The .htaccess file contains settings that cannot be changed at runtime.

984 985 986 987 988 989 990 991 992 993 994 995
    if (PHP_SAPI !== 'cli') {
      // Use session cookies, not transparent sessions that puts the session id
      // in the query string.
      ini_set('session.use_cookies', '1');
      ini_set('session.use_only_cookies', '1');
      ini_set('session.use_trans_sid', '0');
      // Don't send HTTP headers using PHP's session handler.
      // Send an empty string to disable the cache limiter.
      ini_set('session.cache_limiter', '');
      // Use httponly session cookies.
      ini_set('session.cookie_httponly', '1');
    }
996 997 998 999 1000 1001 1002 1003 1004 1005 1006

    // Set sane locale settings, to ensure consistent string, dates, times and
    // numbers handling.
    setlocale(LC_ALL, 'C');

    // Detect string handling method.
    Unicode::check();

    // Indicate that code is operating in a test child site.
    if (!defined('DRUPAL_TEST_IN_CHILD_SITE')) {
      if ($test_prefix = drupal_valid_test_ua()) {
1007
        $test_db = new TestDatabase($test_prefix);
1008 1009 1010 1011 1012 1013
        // Only code that interfaces directly with tests should rely on this
        // constant; e.g., the error/exception handler conditionally adds further
        // error information into HTTP response headers that are consumed by
        // Simpletest's internal browser.
        define('DRUPAL_TEST_IN_CHILD_SITE', TRUE);

1014 1015 1016 1017
        // Web tests are to be conducted with runtime assertions active.
        assert_options(ASSERT_ACTIVE, TRUE);
        // Now synchronize PHP 5 and 7's handling of assertions as much as
        // possible.
1018
        Handle::register();
1019

1020 1021
        // Log fatal errors to the test site directory.
        ini_set('log_errors', 1);
1022
        ini_set('error_log', $app_root . '/' . $test_db->getTestSitePath() . '/error.log');
1023 1024 1025 1026

        // Ensure that a rewritten settings.php is used if opcache is on.
        ini_set('opcache.validate_timestamps', 'on');
        ini_set('opcache.revalidate_freq', 0);