DrupalKernel.php 51.9 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\Config\BootstrapConfigStorageFactory;
11
use Drupal\Core\Config\NullStorage;
12
use Drupal\Core\Database\Database;
13
use Drupal\Core\DependencyInjection\ContainerBuilder;
14
use Drupal\Core\DependencyInjection\ServiceModifierInterface;
15
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
16
use Drupal\Core\DependencyInjection\YamlFileLoader;
17
use Drupal\Core\Extension\ExtensionDiscovery;
18
use Drupal\Core\File\MimeType\MimeTypeGuesser;
19
use Drupal\Core\Http\TrustedHostsRequestFactory;
20
use Drupal\Core\Installer\InstallerRedirectTrait;
21
use Drupal\Core\Language\Language;
22
use Drupal\Core\Site\Settings;
23
use Drupal\Core\Test\TestDatabase;
24
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
25
use Symfony\Component\ClassLoader\ApcClassLoader;
26 27
use Symfony\Component\ClassLoader\WinCacheClassLoader;
use Symfony\Component\ClassLoader\XcacheClassLoader;
28
use Symfony\Component\DependencyInjection\ContainerInterface;
29
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
30
use Symfony\Component\HttpFoundation\RedirectResponse;
31 32
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
33
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
34
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
35
use Symfony\Component\HttpKernel\TerminableInterface;
36
use Symfony\Component\Routing\Route;
37 38 39

/**
 * The DrupalKernel class is the core of Drupal itself.
40 41
 *
 * This class is responsible for building the Dependency Injection Container and
42 43 44 45 46 47 48 49
 * 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.
50
 */
51
class DrupalKernel implements DrupalKernelInterface, TerminableInterface {
52
  use InstallerRedirectTrait;
53

54 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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
  /**
   * 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',
        'arguments' => ['@database', '@cache_tags_provider.container', 'container'],
      ],
      '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;

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
  /**
   * 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
   */
122
  protected $booted = FALSE;
123

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

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

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

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

154 155 156 157 158 159 160 161 162 163 164 165 166 167
  /**
   * 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;

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

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

182
  /**
183 184 185 186 187 188
   * 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.
189 190 191 192 193
   *
   * @var array
   */
  protected $serviceYamls;

194
  /**
195
   * List of discovered service provider class names or objects.
196 197 198 199 200 201
   *
   * 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.
   *
202 203 204
   * Allowing objects is for example used to allow
   * \Drupal\KernelTests\KernelTestBase to register itself as service provider.
   *
205 206 207 208 209 210 211 212
   * @var array
   */
  protected $serviceProviderClasses;

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

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
  /**
   * 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;

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

243 244 245 246
  /**
   * Create a DrupalKernel object from a request.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
247 248 249 250 251
   *   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.
252 253 254 255 256
   * @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.
257 258 259
   * @param string $app_root
   *   (optional) The path to the application root as a string. If not supplied,
   *   the application root will be computed.
260
   *
261
   * @return static
262 263 264
   *
   * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
   *   In case the host name in the request is not trusted.
265
   */
266 267 268
  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);
269
    $kernel->initializeSettings($request);
270 271 272
    return $kernel;
  }

273 274 275 276
  /**
   * Constructs a DrupalKernel object.
   *
   * @param string $environment
277
   *   String indicating the environment, e.g. 'prod' or 'dev'.
278 279 280 281
   * @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.
282 283 284
   * @param bool $allow_dumping
   *   (optional) FALSE to stop the container from being written to or read
   *   from disk. Defaults to TRUE.
285 286 287
   * @param string $app_root
   *   (optional) The path to the application root as a string. If not supplied,
   *   the application root will be computed.
288
   */
289
  public function __construct($environment, $class_loader, $allow_dumping = TRUE, $app_root = NULL) {
290
    $this->environment = $environment;
291
    $this->classLoader = $class_loader;
292
    $this->allowDumping = $allow_dumping;
293 294 295 296 297 298 299 300 301 302 303 304 305 306
    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__))));
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
  }

  /**
   * 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
333
   * directory alias for https://www.drupal.org:8080/mysite/test whose
334 335 336 337 338 339 340 341 342 343 344 345 346 347
   * 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.
348 349 350
   * @param string $app_root
   *   (optional) The path to the application root as a string. If not supplied,
   *   the application root will be computed.
351 352 353 354
   *
   * @return string
   *   The path of the matching directory.
   *
355 356 357
   * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
   *   In case the host name in the request is invalid.
   *
358 359 360 361 362
   * @see \Drupal\Core\DrupalKernelInterface::getSitePath()
   * @see \Drupal\Core\DrupalKernelInterface::setSitePath()
   * @see default.settings.php
   * @see example.sites.php
   */
363
  public static function findSitePath(Request $request, $require_settings = TRUE, $app_root = NULL) {
364 365 366 367
    if (static::validateHostname($request) === FALSE) {
      throw new BadRequestHttpException();
    }

368 369 370 371
    if ($app_root === NULL) {
      $app_root = static::guessApplicationRoot();
    }

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

    // Determine whether multi-site functionality is enabled.
379
    if (!file_exists($app_root . '/sites/sites.php')) {
380 381 382 383 384 385 386 387
      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');
    }
388
    $http_host = $request->getHttpHost();
389 390

    $sites = array();
391
    include $app_root . '/sites/sites.php';
392 393 394 395 396 397

    $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));
398
        if (isset($sites[$dir]) && file_exists($app_root . '/sites/' . $sites[$dir])) {
399 400
          $dir = $sites[$dir];
        }
401
        if (file_exists($app_root . '/sites/' . $dir . '/settings.php') || (!$require_settings && file_exists($app_root . '/sites/' . $dir))) {
402 403 404 405 406 407 408 409 410 411 412
          return "sites/$dir";
        }
      }
    }
    return 'sites/default';
  }

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

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

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

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

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

    // 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.
455
      if (function_exists('apcu_fetch')) {
456 457 458 459 460 461
        $configuration['default']['cache_backend_class'] = '\Drupal\Component\FileCache\ApcuFileCacheBackend';
      }
    }
    FileCacheFactory::setConfiguration($configuration);
    FileCacheFactory::setPrefix(Settings::getApcuPrefix('file_cache', $this->root));

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

464
    // Initialize the container.
465
    $this->initializeContainer();
466

467
    $this->booted = TRUE;
468 469

    return $this;
470 471
  }

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

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

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
  /**
   * {@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;
  }

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

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

    return NULL;
  }

521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
  /**
   * {@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';
  }

540
  /**
541
   * {@inheritdoc}
542
   */
543
  public function preHandle(Request $request) {
544 545 546

    $this->loadLegacyIncludes();

547 548 549
    // Load all enabled modules.
    $this->container->get('module_handler')->loadAll();

550 551 552
    // Register stream wrappers.
    $this->container->get('stream_wrapper_manager')->register();

553 554 555
    // Initialize legacy request globals.
    $this->initializeRequestGlobals($request);

556 557
    // Put the request on the stack.
    $this->container->get('request_stack')->push($request);
558

559 560
    // Set the allowed protocols.
    UrlHelper::setAllowedProtocols($this->container->getParameter('filter_protocols'));
561

562
    // Override of Symfony's MIME type guesser singleton.
563
    MimeTypeGuesser::registerWithSymfonyGuesser($this->container);
564

565
    $this->prepared = TRUE;
566 567
  }

568 569 570 571
  /**
   * {@inheritdoc}
   */
  public function discoverServiceProviders() {
572
    $this->serviceYamls = array(
573 574
      'app' => array(),
      'site' => array(),
575
    );
576 577 578 579 580 581
    $this->serviceProviderClasses = array(
      'app' => array(),
      'site' => array(),
    );
    $this->serviceYamls['app']['core'] = 'core/core.services.yml';
    $this->serviceProviderClasses['app']['core'] = 'Drupal\Core\CoreServiceProvider';
582

583
    // Retrieve enabled modules and register their namespaces.
584
    if (!isset($this->moduleList)) {
585 586
      $extensions = $this->getConfigStorage()->read('core.extension');
      $this->moduleList = isset($extensions['module']) ? $extensions['module'] : array();
587
    }
588
    $module_filenames = $this->getModuleFileNames();
589
    $this->classLoaderAddMultiplePsr4($this->getModuleNamespacesPsr4($module_filenames));
590

591
    // Load each module's serviceProvider class.
592
    foreach ($module_filenames as $module => $filename) {
katbailey's avatar
katbailey committed
593
      $camelized = ContainerBuilder::camelize($module);
594 595
      $name = "{$camelized}ServiceProvider";
      $class = "Drupal\\{$module}\\{$name}";
596
      if (class_exists($class)) {
597
        $this->serviceProviderClasses['app'][$module] = $class;
598
      }
599
      $filename = dirname($filename) . "/$module.services.yml";
600
      if (file_exists($filename)) {
601
        $this->serviceYamls['app'][$module] = $filename;
602
      }
603
    }
604

605
    // Add site-specific service providers.
606
    if (!empty($GLOBALS['conf']['container_service_providers'])) {
607
      foreach ($GLOBALS['conf']['container_service_providers'] as $class) {
608
        if ((is_string($class) && class_exists($class)) || (is_object($class) && ($class instanceof ServiceProviderInterface || $class instanceof ServiceModifierInterface))) {
609 610
          $this->serviceProviderClasses['site'][] = $class;
        }
611 612
      }
    }
613
    $this->addServiceFiles(Settings::get('container_yamls', []));
614 615 616 617 618
  }

  /**
   * {@inheritdoc}
   */
619 620
  public function getServiceProviders($origin) {
    return $this->serviceProviders[$origin];
621 622 623 624 625 626
  }

  /**
   * {@inheritdoc}
   */
  public function terminate(Request $request, Response $response) {
627 628 629
    // Only run terminate() when essential services have been set up properly
    // by preHandle() before.
    if (FALSE === $this->prepared) {
630 631 632 633 634 635 636 637 638 639 640
      return;
    }

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

  /**
   * {@inheritdoc}
   */
641
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
642 643 644 645 646 647 648 649 650 651
    // 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') {
652
        $response = new RedirectResponse($request->getBasePath() . '/core/install.php', 302, ['Cache-Control' => 'no-cache']);
653 654 655 656 657 658 659 660 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
   * @param Request $request
   *   A Request instance
   * @param int $type
   *   The type of the request (one of HttpKernelInterface::MASTER_REQUEST or
   *   HttpKernelInterface::SUB_REQUEST)
   *
   * @return Response
   *   A Response instance
686 687 688
   *
   * @throws \Exception
   *   If the passed in exception cannot be turned into a response.
689 690
   */
  protected function handleException(\Exception $e, $request, $type) {
691 692 693 694
    if ($this->shouldRedirectToInstaller($e, $this->container ? $this->container->get('database') : NULL)) {
      return new RedirectResponse($request->getBasePath() . '/core/install.php', 302, ['Cache-Control' => 'no-cache']);
    }

695 696 697 698 699
    if ($e instanceof HttpExceptionInterface) {
      $response = new Response($e->getMessage(), $e->getStatusCode());
      $response->headers->add($e->getHeaders());
      return $response;
    }
700 701

    throw $e;
702 703
  }

704 705 706 707 708 709
  /**
   * {@inheritdoc}
   */
  public function prepareLegacyRequest(Request $request) {
    $this->boot();
    $this->preHandle($request);
710 711 712 713 714
    // 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'));
    }
715 716
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
717 718 719 720 721
    $this->container->get('request_stack')->push($request);
    $this->container->get('router.request_context')->fromRequest($request);
    return $this;
  }

722 723 724 725 726 727
  /**
   * Returns module data on the filesystem.
   *
   * @param $module
   *   The name of the module.
   *
728 729
   * @return \Drupal\Core\Extension\Extension|bool
   *   Returns an Extension object if the module is found, FALSE otherwise.
730 731 732
   */
  protected function moduleData($module) {
    if (!$this->moduleData) {
733
      // First, find profiles.
734
      $listing = new ExtensionDiscovery($this->root);
735 736 737 738
      $listing->setProfileDirectories(array());
      $all_profiles = $listing->scan('profile');
      $profiles = array_intersect_key($all_profiles, $this->moduleList);

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

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

754
      // Now find modules.
755
      $this->moduleData = $profiles + $listing->scan('module');
756 757 758 759
    }
    return isset($this->moduleData[$module]) ? $this->moduleData[$module] : FALSE;
  }

760 761
  /**
   * Implements Drupal\Core\DrupalKernelInterface::updateModules().
762 763 764
   *
   * @todo Remove obsolete $module_list parameter. Only $module_filenames is
   *   needed.
765
   */
766
  public function updateModules(array $module_list, array $module_filenames = array()) {
767 768 769 770
    $pre_existing_module_namespaces = [];
    if ($this->booted && is_array($this->moduleList)) {
      $pre_existing_module_namespaces = $this->getModuleNamespacesPsr4($this->getModuleFileNames());
    }
771
    $this->moduleList = $module_list;
772 773
    foreach ($module_filenames as $name => $extension) {
      $this->moduleData[$name] = $extension;
774
    }
775

776
    // If we haven't yet booted, we don't need to do anything: the new module
777 778 779 780 781
    // 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;
782
    if ($this->booted) {
783 784 785 786 787 788 789 790 791 792 793 794 795 796
      // 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();
      }

797
      $this->initializeContainer();
798 799
    }
  }
800

801
  /**
802
   * Returns the container cache key based on the environment.
803
   *
804 805 806 807 808 809 810 811 812
   * 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.
   *
813
   * @return string
814
   *   The cache key used for the service container.
815
   */
816
  protected function getContainerCacheKey() {
817
    $parts = array('service_container', $this->environment, \Drupal::VERSION, Settings::get('deployment_identifier'), PHP_OS, serialize(Settings::get('container_yamls')));
818
    return implode(':', $parts);
819
  }
820 821 822 823 824 825 826 827 828 829 830 831

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

832 833
  /**
   * Initializes the service container.
834 835
   *
   * @return \Symfony\Component\DependencyInjection\ContainerInterface
836
   */
837
  protected function initializeContainer() {
838
    $this->containerNeedsDumping = FALSE;
839
    $session_started = FALSE;
840
    if (isset($this->container)) {
841 842 843 844 845
      // Save the id of the currently logged in user.
      if ($this->container->initialized('current_user')) {
        $current_user_id = $this->container->get('current_user')->id();
      }

846 847 848 849 850 851
      // 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();
852
        }
853
        unset($session);
854
      }
855
    }
856

857 858 859 860
    // 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) {
861
      $container = $this->container;
862 863
    }

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

870 871 872
    // If there is no container and no cached container definition, build a new
    // one from scratch.
    if (!isset($container) && !isset($container_definition)) {
873
      $container = $this->compileContainer();
874 875 876 877 878 879 880 881

      // 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();
      }
882 883
    }

884 885 886
    // The container was rebuilt successfully.
    $this->containerNeedsRebuild = FALSE;

887 888 889 890 891 892
    // 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);
    }

893
    $this->attachSynthetic($container);
894 895

    $this->container = $container;
896 897
    if ($session_started) {
      $this->container->get('session')->start();
898
    }
899 900 901 902 903 904 905 906 907 908

    // 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()) {
        if ($request->hasSession()) {
          $request->setSession($this->container->get('session'));
        }
      }
    }
909 910 911 912 913

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

914
    \Drupal::setContainer($this->container);
915 916

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

921 922 923 924 925 926 927 928
    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.
929 930 931 932
   *
   * @param string $app_root
   *   (optional) The path to the application root as a string. If not supplied,
   *   the application root will be computed.
933
   */
934
  public static function bootEnvironment($app_root = NULL) {
935 936 937 938
    if (static::$isEnvironmentInitialized) {
      return;
    }

939 940 941 942 943
    // Determine the application root if it's not supplied.
    if ($app_root === NULL) {
      $app_root = static::guessApplicationRoot();
    }

944
    // Include our bootstrap file.
945
    require_once $app_root . '/core/includes/bootstrap.inc';
946

947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
    // 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.

    // 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');

    // 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()) {
975
        $test_db = new TestDatabase($test_prefix);
976 977 978 979 980 981
        // 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);

982 983 984 985
        // 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.
986
        Handle::register();
987

988 989
        // Log fatal errors to the test site directory.
        ini_set('log_errors', 1);
990
        ini_set('error_log', $app_root . '/' . $test_db->getTestSitePath() . '/error.log');
991 992 993 994

        // Ensure that a rewritten settings.php is used if opcache is on.
        ini_set('opcache.validate_timestamps', 'on');
        ini_set('opcache.revalidate_freq', 0);
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
      }
      else {
        // Ensure that no other code defines this.
        define('DRUPAL_TEST_IN_CHILD_SITE', FALSE);
      }
    }

    // Set the Drupal custom error handler.
    set_error_handler('_drupal_error_handler');
    set_exception_handler('_drupal_exception_handler');

    static::$isEnvironmentInitialized = TRUE;
  }

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
  /**
   * Locate site path and initialize settings singleton.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
   *   In case the host name in the request is not trusted.
   */
  protected function initializeSettings(Request $request) {
    $site_path = static::findSitePath($request);
    $this->setSitePath($site_path);
1021
    $class_loader_class = get_class($this->classLoader);
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
    Settings::initialize($this->root, $site_path, $this->classLoader);

    // Initialize our list of trusted HTTP Host headers to protect against
    // header attacks.
    $host_patterns = Settings::get('trusted_host_patterns', array());
    if (PHP_SAPI !== 'cli' && !empty($host_patterns)) {
      if (static::setupTrustedHosts($request, $host_patterns) === FALSE) {
        throw new BadRequestHttpException('The provided host name is not valid for this server.');
      }
    }
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056

    // If the class loader is still the same, possibly
    // upgrade to an optimized class loader.
    if ($class_loader_class == get_class($this->classLoader)
        && Settings::get('class_loader_auto_detect', TRUE)) {
      $prefix = Settings::getApcuPrefix('class_loader', $this->root);
      $loader = NULL;

      // We autodetect one of the following three optimized classloaders, if
      // their underlying extension exists.
      if (function_exists('apcu_fetch')) {
        $loader = new ApcClassLoader($prefix, $this->classLoader);
      }
      elseif (extension_loaded('wincache')) {
        $loader = new WinCacheClassLoader($prefix, $this->classLoader);
      }
      elseif (extension_loaded('xcache')) {
        $loader = new XcacheClassLoader($prefix, $this->classLoader);
      }
      if (!empty($loader)) {
        $this->classLoader->unregister();
        $loader->register();
        $this->classLoader = $loader;
      }
    }
1057 1058
  }

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
  /**
   * Bootstraps the legacy global request variables.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @todo D8: Eliminate this entirely in favor of Request object.
   */
  protected function initializeRequestGlobals(Request $request) {
    global $base_url;
    // Set and derived from $base_url by this function.
1070
    global $base_path, $base_root;
1071 1072
    global $base_secure_url, $base_insecure_url;

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
    // Create base URL.
    $base_root = $request->getSchemeAndHttpHost();
    $base_url = $base_root;

    // For a request URI of '/index.php/foo', $_SERVER['SCRIPT_NAME'] is
    // '/index.php', whereas $_SERVER['PHP_SELF'] is '/index.php/foo'.
    if ($dir = rtrim(dirname($request->server->get('SCRIPT_NAME')), '\/')) {
      // Remove "core" directory if present, allowing install.php,
      // authorize.php, and others to auto-detect a base path.
      $core_position = strrpos($dir, '/core');
      if ($core_position !== FALSE && strlen($dir) - 5 == $core_position) {
        $base_path = substr($dir, 0, $core_position);
1085 1086
      }
      else {
1087
        $base_path = $dir;
1088
      }
1089 1090 1091 1092 1093
      $base_url .= $base_path;
      $base_path .= '/';
    }
    else {
      $base_path = '/';
1094 1095 1096 1097
    }
    $base_secure_url = str_replace('http://', 'https://', $base_url);
    $base_insecure_url = str_replace('https://', 'http://', $base_url);
  }
1098

1099 1100 1101
  /**
   * Returns service instances to persist from an old container to a new one.
   */
1102
  protected function getServicesToPersist(ContainerInterface $container) {
1103
    $persist = array();
1104
    foreach ($container->getParameter('persist_ids') as $id) {
1105 1106 1107
      // It's pointless to persist services not yet initialized.
      if ($container->initialized($id)) {
        $persist[$id] = $container->get($id);
1108 1109 1110 1111 1112 1113 1114 1115
      }
    }
    return $persist;
  }

  /**
   * Moves persistent service instances into a new container.
   */
1116
  protected function persistServices(ContainerInterface $container, array $persist) {
1117 1118 1119
    foreach ($persist as $id => $object) {
      // Do not override services already set() on the new container, for
      // example 'service_container'.
1120 1121
      if (!$container->initialized($id)) {
        $container->set($id, $object);
1122 1123 1124 1125
      }
    }
  }

1126
  /**
1127
   * {@inheritdoc}
1128 1129 1130 1131 1132
   */
  public function rebuildContainer() {
    // Empty module properties and for them to be reloaded from scratch.
    $this->moduleList = NULL;
    $this->moduleData = array();
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
    $this->containerNeedsRebuild = TRUE;
    return $this->initializeContainer();
  }

  /**
   * {@inheritdoc}
   */
  public function invalidateContainer() {
    // An invalidated container needs a rebuild.
    $this->containerNeedsRebuild = TRUE;

    // If we have not yet booted, settings or bootstrap services might not yet
    // be available. In that case the container will not be loaded from cache
    // due to the above setting when the Kernel is booted.
    if (!$this->booted) {
      return;
    }

1151 1152
    // Also remove the container definition from the cache backend.
    $this->bootstrapContainer->get('cache.container')->deleteAll();
1153 1154 1155 1156 1157 1158 1159
  }

  /**
   * Attach synthetic values on to kernel.
   *
   * @param ContainerInterface $container
   *   Container object
1160
   *
1161 1162
   * @return ContainerInterface
   */
1163
  protected function attachSynthetic(ContainerInterface $container) {
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    $persist = array();
    if (isset($this->container)) {
      $persist = $this->getServicesToPersist($this->container);
    }
    $this->persistServices($container, $persist);

    // All namespaces must be registered before we attempt to use any service
    // from the container.
    $this->classLoaderAddMultiplePsr4($container->getParameter('container.namespaces'));

    $container->set('kernel', $this);

    // Set the class loader which was registered as a synthetic service.
    $container->set('class_loader', $this->classLoader);
    return $container;
  }

  /**
   * Compiles a new service container.
1183 1184 1185
   *
   * @return ContainerBuilder The compiled service container
   */
1186 1187 1188 1189 1190 1191 1192 1193
  protected function compileContainer() {
    // We are forcing a container build so it is reasonable to assume that the
    // calling method knows something about the system has changed requiring the
    // container to be dumped to the filesystem.
    if ($this->allowDumping) {
      $this->containerNeedsDumping = TRUE;
    }

1194
    $this->initializeServiceProviders();
1195
    $container = $this->getContainerBuilder();
1196
    $container->set('kernel', $this);
1197
    $container->setParameter('container.modules', $this->getModulesParameter());
1198 1199

    // Get a list of namespaces and put it onto the container.
1200
    $namespaces = $this->getModuleNamespacesPsr4($this->getModuleFileNames());
1201 1202 1203 1204 1205
    // Add all components in \Drupal\Core and \Drupal\Component that have one of
    // the following directories:
    // - Element
    // - Entity
    // - Plugin
1206
    foreach (array('Core', 'Component') as $parent_directory) {
1207
      $path = 'core/lib/Drupal/' . $parent_directory;
1208
      $parent_namespace = 'Drupal\\' . $parent_directory;
1209
      foreach (new \DirectoryIterator($this->root . '/' . $path) as $component) {
1210 1211 1212 1213 1214 1215 1216
        /** @var $component \DirectoryIterator */
        $pathname = $component->getPathname();
        if (!$component->isDot() && $component->isDir() && (
          is_dir($pathname . '/Plugin') ||
          is_dir($pathname . '/Entity') ||
          is_dir($pathname . '/Element')
        )) {
1217
          $namespaces[$parent_namespace . '\\' . $component->getFilename()] = $path . '/' . $component->getFilename();
1218 1219 1220
        }
      }
    }
1221 1222
    $container->setParameter('container.namespaces', $namespaces);

1223 1224 1225 1226 1227 1228
    // Store the default language values on the container. This is so that the
    // default language can be configured using the configuration factory. This
    // avoids the circular dependencies that would created by
    // \Drupal\language\LanguageServiceProvider::alter() and allows the default
    // language to not be English in the installer.
    $default_language_values = Language::$defaultValues;
1229 1230
    if ($system = $this->getConfigStorage()->read('system.site')) {
      if ($default_language_values['id'] != $system['langcode']) {
1231
        $default_language_values = array('id' => $system['langcode']);
1232
      }
1233 1234 1235
    }
    $container->setParameter('language.default_values', $default_language_values);

1236
    // Register synthetic services.
1237
    $container->register('class_loader')->setSynthetic(TRUE);
1238 1239
    $container->register('kernel', 'Symfony\Component\HttpKernel\KernelInterface')->setSynthetic(TRUE);
    $container->register('service_container', 'Symfony\Component\DependencyInjection\ContainerInterface')->setSynthetic(TRUE);
1240 1241

    // Register application services.
1242
    $yaml_loader = new YamlFileLoader($container);
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
    foreach ($this->serviceYamls['app'] as $filename) {
      $yaml_loader->load($filename);
    }
    foreach ($this->serviceProviders['app'] as $provider) {
      if ($provider instanceof ServiceProviderInterface) {
        $provider->register($container);
      }
    }
    // Register site-specific service overrides.
    foreach ($this->serviceYamls['site'] as $filename) {
1253 1254
      $yaml_loader->load($filename);
    }
1255
    foreach ($this->serviceProviders['site'] as $provider) {
1256 1257 1258
      if ($provider instanceof ServiceProviderInterface) {
        $provider->register($container);
      }
1259
    }
1260 1261 1262 1263 1264 1265 1266

    // Identify all services whose instances should be persisted when rebuilding
    // the container during the lifetime of the kernel (e.g., during a kernel
    // reboot). Include synthetic services, because by definition, they cannot
    // be automatically reinstantiated. Also include services tagged to persist.
    $persist_ids = array();
    foreach ($container->getDefinitions() as $id => $definition) {