DrupalKernel.php 42.2 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Definition of Drupal\Core\DrupalKernel.
 */

namespace Drupal\Core;

10 11 12 13
use Drupal\Component\Utility\Crypt;
use Drupal\Component\Utility\Timer;
use Drupal\Component\Utility\Unicode;
use Drupal\Component\Utility\UrlHelper;
14
use Drupal\Core\Config\BootstrapConfigStorageFactory;
15
use Drupal\Core\Config\NullStorage;
16
use Drupal\Core\Database\Database;
17
use Drupal\Core\DependencyInjection\ContainerBuilder;
18
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
19
use Drupal\Core\DependencyInjection\YamlFileLoader;
20
use Drupal\Core\Extension\ExtensionDiscovery;
21
use Drupal\Core\Language\Language;
22
use Drupal\Core\PageCache\RequestPolicyInterface;
23 24 25
use Drupal\Core\PhpStorage\PhpStorageFactory;
use Drupal\Core\Site\Settings;
use Symfony\Component\DependencyInjection\ContainerInterface;
26
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
27
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
28
use Symfony\Component\HttpFoundation\RedirectResponse;
29
use Symfony\Component\HttpFoundation\Request;
30
use Symfony\Component\HttpFoundation\RequestStack;
31 32
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\TerminableInterface;
33
use Composer\Autoload\ClassLoader;
34 35 36

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

50
  const CONTAINER_BASE_CLASS = '\Drupal\Core\DependencyInjection\Container';
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

  /**
   * 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
   */
71
  protected $booted = FALSE;
72

73 74 75 76
  /**
   * Holds the list of enabled modules.
   *
   * @var array
77 78
   *   An associative array whose keys are module names and whose values are
   *   ignored.
79 80 81
   */
  protected $moduleList;

82
  /**
83
   * List of available modules and installation profiles.
84
   *
85
   * @var \Drupal\Core\Extension\Extension[]
86
   */
87
  protected $moduleData = array();
88 89 90 91 92 93 94 95

  /**
   * PHP code storage object to use for the compiled container.
   *
   * @var \Drupal\Component\PhpStorage\PhpStorageInterface
   */
  protected $storage;

96 97 98
  /**
   * The classloader object.
   *
99
   * @var \Composer\Autoload\ClassLoader
100 101 102
   */
  protected $classLoader;

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
  /**
   * Config storage object used for reading enabled modules configuration.
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
  protected $configStorage;

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

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

124
  /**
125 126 127 128 129 130
   * 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.
131 132 133 134 135
   *
   * @var array
   */
  protected $serviceYamls;

136
  /**
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
   * List of discovered service provider class names.
   *
   * This is a nested array whose top-level keys are 'app' and 'site', denoting
   * the origin of a service provider. Site-specific providers have to be
   * collected separately, because they need to be processed last, so as to be
   * able to override services from application service providers.
   *
   * @var array
   */
  protected $serviceProviderClasses;

  /**
   * List of instantiated service provider classes.
   *
   * @see \Drupal\Core\DrupalKernel::$serviceProviderClasses
152 153 154 155 156
   *
   * @var array
   */
  protected $serviceProviders;

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
  /**
   * Whether the request globals have been initialized.
   *
   * @var bool
   */
  protected static $isRequestInitialized = FALSE;

  /**
   * 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;

182 183 184 185 186 187 188
  /**
   * The app root.
   *
   * @var string
   */
  protected $root;

189 190 191 192
  /**
   * Create a DrupalKernel object from a request.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
193 194 195 196 197
   *   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.
198 199 200 201 202
   * @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.
203
   *
204 205
   * @return static
   */
206
  public static function createFromRequest(Request $request, $class_loader, $environment, $allow_dumping = TRUE) {
207
    // Include our bootstrap file.
208 209
    $core_root = dirname(dirname(dirname(__DIR__)));
    require_once $core_root . '/includes/bootstrap.inc';
210 211 212 213 214 215 216

    $kernel = new static($environment, $class_loader, $allow_dumping);

    // Ensure sane php environment variables..
    static::bootEnvironment();

    // Get our most basic settings setup.
217 218 219
    $site_path = static::findSitePath($request);
    $kernel->setSitePath($site_path);
    Settings::initialize(dirname($core_root), $site_path, $class_loader);
220 221 222 223

    // 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.
224
    if (!Database::getConnectionInfo() && !drupal_installation_attempted() && PHP_SAPI !== 'cli') {
225 226 227 228 229 230 231
      $response = new RedirectResponse($request->getBasePath() . '/core/install.php');
      $response->prepare($request)->send();
    }

    return $kernel;
  }

232 233 234 235
  /**
   * Constructs a DrupalKernel object.
   *
   * @param string $environment
236
   *   String indicating the environment, e.g. 'prod' or 'dev'.
237 238 239 240
   * @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.
241 242 243
   * @param bool $allow_dumping
   *   (optional) FALSE to stop the container from being written to or read
   *   from disk. Defaults to TRUE.
244
   */
245
  public function __construct($environment, $class_loader, $allow_dumping = TRUE) {
246
    $this->environment = $environment;
247
    $this->classLoader = $class_loader;
248
    $this->allowDumping = $allow_dumping;
249
    $this->root = dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 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 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
  }

  /**
   * 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
   * directory alias for http://www.drupal.org:8080/mysite/test whose
   * 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.
   *
   * @return string
   *   The path of the matching directory.
   *
   * @see \Drupal\Core\DrupalKernelInterface::getSitePath()
   * @see \Drupal\Core\DrupalKernelInterface::setSitePath()
   * @see default.settings.php
   * @see example.sites.php
   */
  public static function findSitePath(Request $request, $require_settings = TRUE) {
    // Check for a simpletest override.
    if ($test_prefix = drupal_valid_test_ua()) {
      return 'sites/simpletest/' . substr($test_prefix, 10);
    }

    // Determine whether multi-site functionality is enabled.
    if (!file_exists(DRUPAL_ROOT . '/sites/sites.php')) {
      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');
    }
    $http_host = $request->server->get('HTTP_HOST');

    $sites = array();
    include DRUPAL_ROOT . '/sites/sites.php';

    $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));
        if (isset($sites[$dir]) && file_exists(DRUPAL_ROOT . '/sites/' . $sites[$dir])) {
          $dir = $sites[$dir];
        }
        if (file_exists(DRUPAL_ROOT . '/sites/' . $dir . '/settings.php') || (!$require_settings && file_exists(DRUPAL_ROOT . '/sites/' . $dir))) {
          return "sites/$dir";
        }
      }
    }
    return 'sites/default';
  }

  /**
   * {@inheritdoc}
   */
  public function setSitePath($path) {
    $this->sitePath = $path;
  }

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

351 352 353 354 355 356 357
  /**
   * {@inheritdoc}
   */
  public function getAppRoot() {
    return $this->root;
  }

358
  /**
359
   * {@inheritdoc}
360 361 362
   */
  public function boot() {
    if ($this->booted) {
363 364 365 366 367 368 369
      return $this;
    }

    // Start a page timer:
    Timer::start('page');

    // Load legacy and other functional code.
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    require_once $this->root . '/core/includes/common.inc';
    require_once $this->root . '/core/includes/database.inc';
    require_once $this->root . '/core/includes/path.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/mail.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';
385 386 387 388

    // Ensure that findSitePath is set.
    if (!$this->sitePath) {
      throw new \Exception('Kernel does not have site path set before calling boot()');
389
    }
390
    // Initialize the container.
391
    $this->initializeContainer();
392 393 394 395 396 397

    // Ensure mt_rand() is reseeded to prevent random values from one page load
    // being exploited to predict random values in subsequent page loads.
    $seed = unpack("L", Crypt::randomBytes(4));
    mt_srand($seed[1]);

398
    $this->container->get('stream_wrapper_manager')->register();
399
    $this->booted = TRUE;
400 401

    return $this;
402 403
  }

404
  /**
405
   * {@inheritdoc}
406
   */
407 408 409 410
  public function shutdown() {
    if (FALSE === $this->booted) {
      return;
    }
411
    $this->container->get('stream_wrapper_manager')->unregister();
412
    $this->booted = FALSE;
413
    $this->container = NULL;
414 415
    $this->moduleList = NULL;
    $this->moduleData = array();
416 417 418 419 420 421 422 423 424
  }

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

425
  /**
426
   * {@inheritdoc}
427
   */
428
  public function preHandle(Request $request) {
429 430 431 432 433 434 435 436 437
    // Load all enabled modules.
    $this->container->get('module_handler')->loadAll();

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

    // Initialize cookie globals.
    $this->initializeCookieGlobals($request);

438 439
    // Put the request on the stack.
    $this->container->get('request_stack')->push($request);
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470

    // Set the allowed protocols once we have the config available.
    $allowed_protocols = $this->container->get('config.factory')->get('system.filter')->get('protocols');
    if (!isset($allowed_protocols)) {
      // \Drupal\Component\Utility\UrlHelper::filterBadProtocol() is called by
      // the installer and update.php, in which case the configuration may not
      // exist (yet). Provide a minimal default set of allowed protocols for
      // these cases.
      $allowed_protocols = array('http', 'https');
    }
    UrlHelper::setAllowedProtocols($allowed_protocols);
  }

  /**
   * {@inheritdoc}
   *
   * @todo Invoke proper request/response/terminate events.
   */
  public function handlePageCache(Request $request) {
    $this->boot();
    $this->initializeCookieGlobals($request);

    // Check for a cache mode force from settings.php.
    if (Settings::get('page_cache_without_database')) {
      $cache_enabled = TRUE;
    }
    else {
      $config = $this->getContainer()->get('config.factory')->get('system.performance');
      $cache_enabled = $config->get('cache.page.use_internal');
    }

471 472
    $request_policy = \Drupal::service('page_cache_request_policy');
    if ($cache_enabled && $request_policy->check($request) === RequestPolicyInterface::ALLOW) {
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
      // Get the page from the cache.
      $response = drupal_page_get_cache($request);
      // If there is a cached page, display it.
      if ($response) {
        $response->headers->set('X-Drupal-Cache', 'HIT');

        drupal_serve_page_from_cache($response, $request);

        // We are done.
        $response->prepare($request);
        $response->send();
        exit;
      }
    }
    return $this;
  }

490 491 492 493
  /**
   * {@inheritdoc}
   */
  public function discoverServiceProviders() {
494
    $this->serviceYamls = array(
495 496
      'app' => array(),
      'site' => array(),
497
    );
498 499 500 501 502 503
    $this->serviceProviderClasses = array(
      'app' => array(),
      'site' => array(),
    );
    $this->serviceYamls['app']['core'] = 'core/core.services.yml';
    $this->serviceProviderClasses['app']['core'] = 'Drupal\Core\CoreServiceProvider';
504

505
    // Retrieve enabled modules and register their namespaces.
506
    if (!isset($this->moduleList)) {
507 508
      $extensions = $this->getConfigStorage()->read('core.extension');
      $this->moduleList = isset($extensions['module']) ? $extensions['module'] : array();
509
    }
510
    $module_filenames = $this->getModuleFileNames();
511
    $this->classLoaderAddMultiplePsr4($this->getModuleNamespacesPsr4($module_filenames));
512

513
    // Load each module's serviceProvider class.
514
    foreach ($module_filenames as $module => $filename) {
katbailey's avatar
katbailey committed
515
      $camelized = ContainerBuilder::camelize($module);
516 517
      $name = "{$camelized}ServiceProvider";
      $class = "Drupal\\{$module}\\{$name}";
518
      if (class_exists($class)) {
519
        $this->serviceProviderClasses['app'][$module] = $class;
520
      }
521
      $filename = dirname($filename) . "/$module.services.yml";
522
      if (file_exists($filename)) {
523
        $this->serviceYamls['app'][$module] = $filename;
524
      }
525
    }
526

527
    // Add site-specific service providers.
528
    if (!empty($GLOBALS['conf']['container_service_providers'])) {
529 530 531 532
      foreach ($GLOBALS['conf']['container_service_providers'] as $class) {
        if (class_exists($class)) {
          $this->serviceProviderClasses['site'][] = $class;
        }
533 534
      }
    }
535 536
    if ($container_yamls = Settings::get('container_yamls')) {
      $this->serviceYamls['site'] = $container_yamls;
537
    }
538 539
    $site_services_yml = $this->getSitePath() . '/services.yml';
    if (file_exists($site_services_yml) && is_readable($site_services_yml)) {
540
      $this->serviceYamls['site'][] = $site_services_yml;
541
    }
542 543 544 545 546
  }

  /**
   * {@inheritdoc}
   */
547 548
  public function getServiceProviders($origin) {
    return $this->serviceProviders[$origin];
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
  }

  /**
   * {@inheritdoc}
   */
  public function terminate(Request $request, Response $response) {
    if (FALSE === $this->booted) {
      return;
    }

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

  /**
   * {@inheritdoc}
   */
567 568
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
    $this->boot();
569
    return $this->getHttpKernel()->handle($request, $type, $catch);
570 571
  }

572 573 574 575 576 577 578 579 580 581 582 583 584
  /**
   * {@inheritdoc}
   */
  public function prepareLegacyRequest(Request $request) {
    $this->boot();
    $this->preHandle($request);
    // Enter the request scope so that current_user service is available for
    // locale/translation sake.
    $this->container->get('request_stack')->push($request);
    $this->container->get('router.request_context')->fromRequest($request);
    return $this;
  }

585 586 587 588 589 590
  /**
   * Returns module data on the filesystem.
   *
   * @param $module
   *   The name of the module.
   *
591 592
   * @return \Drupal\Core\Extension\Extension|bool
   *   Returns an Extension object if the module is found, FALSE otherwise.
593 594 595
   */
  protected function moduleData($module) {
    if (!$this->moduleData) {
596
      // First, find profiles.
597
      $listing = new ExtensionDiscovery($this->root);
598 599 600 601
      $listing->setProfileDirectories(array());
      $all_profiles = $listing->scan('profile');
      $profiles = array_intersect_key($all_profiles, $this->moduleList);

602 603
      // If a module is within a profile directory but specifies another
      // profile for testing, it needs to be found in the parent profile.
604
      $settings = $this->getConfigStorage()->read('simpletest.settings');
605 606
      $parent_profile = !empty($settings['parent_profile']) ? $settings['parent_profile'] : NULL;
      if ($parent_profile && !isset($profiles[$parent_profile])) {
607 608
        // In case both profile directories contain the same extension, the
        // actual profile always has precedence.
609
        $profiles = array($parent_profile => $all_profiles[$parent_profile]) + $profiles;
610
      }
611 612 613 614 615 616

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

617
      // Now find modules.
618
      $this->moduleData = $profiles + $listing->scan('module');
619 620 621 622
    }
    return isset($this->moduleData[$module]) ? $this->moduleData[$module] : FALSE;
  }

623 624
  /**
   * Implements Drupal\Core\DrupalKernelInterface::updateModules().
625 626 627
   *
   * @todo Remove obsolete $module_list parameter. Only $module_filenames is
   *   needed.
628
   */
629
  public function updateModules(array $module_list, array $module_filenames = array()) {
630
    $this->moduleList = $module_list;
631 632
    foreach ($module_filenames as $name => $extension) {
      $this->moduleData[$name] = $extension;
633
    }
634

635 636
    // If we haven't yet booted, we don't need to do anything: the new module
    // list will take effect when boot() is called. If we have already booted,
637 638
    // then rebuild the container in order to refresh the serviceProvider list
    // and container.
639
    if ($this->booted) {
640
      $this->initializeContainer(TRUE);
641 642
    }
  }
643

644
  /**
645
   * Returns the classname based on environment.
646 647 648 649 650
   *
   * @return string
   *   The class name.
   */
  protected function getClassName() {
651
    $parts = array('service_container', $this->environment);
652 653 654
    return implode('_', $parts);
  }

655 656 657 658 659 660 661 662 663 664 665 666

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

667 668
  /**
   * Initializes the service container.
669 670 671 672
   *
   * @param bool $rebuild
   *   Force a container rebuild.
   * @return \Symfony\Component\DependencyInjection\ContainerInterface
673
   */
674
  protected function initializeContainer($rebuild = FALSE) {
675
    $this->containerNeedsDumping = FALSE;
676
    $session_manager_started = FALSE;
677
    if (isset($this->container)) {
678 679 680 681
      // If there is a session manager, close and save the session.
      if ($this->container->initialized('session_manager')) {
        $session_manager = $this->container->get('session_manager');
        if ($session_manager->isStarted()) {
682
          $session_manager_started = TRUE;
683
          $session_manager->save();
684 685 686
        }
        unset($session_manager);
      }
687
    }
688

689 690 691 692 693 694 695
    // If the module list hasn't already been set in updateModules and we are
    // not forcing a rebuild, then try and load the container from the disk.
    if (empty($this->moduleList) && !$rebuild) {
      $class = $this->getClassName();
      $cache_file = $class . '.php';

      // First, try to load from storage.
696
      if (!class_exists($class, FALSE)) {
697
        $this->storage()->load($cache_file);
698 699 700 701
      }
      // If the load succeeded or the class already existed, use it.
      if (class_exists($class, FALSE)) {
        $fully_qualified_class_name = '\\' . $class;
702
        $container = new $fully_qualified_class_name;
703 704
      }
    }
705 706 707 708 709

    if (!isset($container)) {
      $container = $this->compileContainer();
    }

710
    $this->attachSynthetic($container);
711 712

    $this->container = $container;
713
    if ($session_manager_started) {
714 715
      $this->container->get('session_manager')->start();
    }
716
    \Drupal::setContainer($this->container);
717 718 719 720 721 722

    // If needs dumping flag was set, dump the container.
    if ($this->containerNeedsDumping && !$this->dumpDrupalContainer($this->container, static::CONTAINER_BASE_CLASS)) {
      $this->container->get('logger.factory')->get('DrupalKernel')->notice('Container cannot be written to disk');
    }

723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
    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.
   */
  public static function bootEnvironment() {
    if (static::$isEnvironmentInitialized) {
      return;
    }

    // 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()) {
        // 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);

        // Log fatal errors to the test site directory.
        ini_set('log_errors', 1);
        ini_set('error_log', DRUPAL_ROOT . '/sites/simpletest/' . substr($test_prefix, 10) . '/error.log');
      }
      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;
  }

  /**
   * 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) {
    // Provided by settings.php.
    global $base_url;
    // Set and derived from $base_url by this function.
    global $base_path, $base_root, $script_path;
    global $base_secure_url, $base_insecure_url;

    // @todo Refactor with the Symfony Request object.
    _current_path(request_path());

    if (isset($base_url)) {
      // Parse fixed base URL from settings.php.
      $parts = parse_url($base_url);
      if (!isset($parts['path'])) {
        $parts['path'] = '';
      }
      $base_path = $parts['path'] . '/';
      // Build $base_root (everything until first slash after "scheme://").
      $base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
815
    }
816
    else {
817 818 819 820 821 822 823 824 825
      // Create base URL.
      $http_protocol = $request->isSecure() ? 'https' : 'http';
      $base_root = $http_protocol . '://' . $request->server->get('HTTP_HOST');

      $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')), '\/')) {
826 827
        // Remove "core" directory if present, allowing install.php,
        // authorize.php, and others to auto-detect a base path.
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
        $core_position = strrpos($dir, '/core');
        if ($core_position !== FALSE && strlen($dir) - 5 == $core_position) {
          $base_path = substr($dir, 0, $core_position);
        }
        else {
          $base_path = $dir;
        }
        $base_url .= $base_path;
        $base_path .= '/';
      }
      else {
        $base_path = '/';
      }
    }
    $base_secure_url = str_replace('http://', 'https://', $base_url);
    $base_insecure_url = str_replace('https://', 'http://', $base_url);
844

845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
    // Determine the path of the script relative to the base path, and add a
    // trailing slash. This is needed for creating URLs to Drupal pages.
    if (!isset($script_path)) {
      $script_path = '';
      // We don't expect scripts outside of the base path, but sanity check
      // anyway.
      if (strpos($request->server->get('SCRIPT_NAME'), $base_path) === 0) {
        $script_path = substr($request->server->get('SCRIPT_NAME'), strlen($base_path)) . '/';
        // If the request URI does not contain the script name, then clean URLs
        // are in effect and the script path can be similarly dropped from URL
        // generation. For servers that don't provide $_SERVER['REQUEST_URI'],
        // we do not know the actual URI requested by the client, and
        // request_uri() returns a URI with the script name, resulting in
        // non-clean URLs unless
        // there's other code that intervenes.
        if (strpos(request_uri(TRUE) . '/', $base_path . $script_path) !== 0) {
          $script_path = '';
        }
863
        // @todo Temporary BC for install.php, authorize.php, and other scripts.
864 865 866 867 868
        //   - http://drupal.org/node/1547184
        //   - http://drupal.org/node/1546082
        if ($script_path !== 'index.php/') {
          $script_path = '';
        }
869 870 871
      }
    }

872
  }
873

874 875 876 877 878 879 880 881 882 883 884 885 886
  /**
   * Initialize cookie settings.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @todo D8: Eliminate this entirely in favor of a session object.
   */
  protected function initializeCookieGlobals(Request $request) {
    // If we do this more then once per page request we are likely to cause
    // errors.
    if (static::$isRequestInitialized) {
      return;
887
    }
888 889 890 891 892
    global $cookie_domain;

    if ($cookie_domain) {
      // If the user specifies the cookie domain, also use it for session name.
      $session_name = $cookie_domain;
893
    }
894 895 896 897 898
    else {
      // Otherwise use $base_url as session name, without the protocol
      // to use the same session identifiers across HTTP and HTTPS.
      $session_name = $request->getHost() . $request->getBasePath();
      // Replace "core" out of session_name so core scripts redirect properly,
899
      // specifically install.php.
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
      $session_name = preg_replace('/\/core$/', '', $session_name);
      // HTTP_HOST can be modified by a visitor, but has been sanitized already
      // in DrupalKernel::bootEnvironment().
      if ($cookie_domain = $request->server->get('HTTP_HOST')) {
        // Strip leading periods, www., and port numbers from cookie domain.
        $cookie_domain = ltrim($cookie_domain, '.');
        if (strpos($cookie_domain, 'www.') === 0) {
          $cookie_domain = substr($cookie_domain, 4);
        }
        $cookie_domain = explode(':', $cookie_domain);
        $cookie_domain = '.' . $cookie_domain[0];
      }
    }
    // Per RFC 2109, cookie domains must contain at least one dot other than the
    // first. For hosts such as 'localhost' or IP Addresses we don't set a
    // cookie domain.
    if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
      ini_set('session.cookie_domain', $cookie_domain);
    }
    // To prevent session cookies from being hijacked, a user can configure the
    // SSL version of their website to only transfer session cookies via SSL by
    // using PHP's session.cookie_secure setting. The browser will then use two
    // separate session cookies for the HTTPS and HTTP versions of the site. So
    // we must use different session identifiers for HTTPS and HTTP to prevent a
    // cookie collision.
    if ($request->isSecure()) {
      ini_set('session.cookie_secure', TRUE);
    }
    $prefix = ini_get('session.cookie_secure') ? 'SSESS' : 'SESS';

    session_name($prefix . substr(hash('sha256', $session_name), 0, 32));

    static::$isRequestInitialized = TRUE;
933
  }
934

935 936 937
  /**
   * Returns service instances to persist from an old container to a new one.
   */
938
  protected function getServicesToPersist(ContainerInterface $container) {
939
    $persist = array();
940 941 942 943
    foreach ($container->getParameter('persistIds') as $id) {
      // It's pointless to persist services not yet initialized.
      if ($container->initialized($id)) {
        $persist[$id] = $container->get($id);
944 945 946 947 948 949 950 951
      }
    }
    return $persist;
  }

  /**
   * Moves persistent service instances into a new container.
   */
952
  protected function persistServices(ContainerInterface $container, array $persist) {
953 954 955
    foreach ($persist as $id => $object) {
      // Do not override services already set() on the new container, for
      // example 'service_container'.
956 957
      if (!$container->initialized($id)) {
        $container->set($id, $object);
958 959 960 961
      }
    }
  }

962
  /**
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
   * Force a container rebuild.
   *
   * @return \Symfony\Component\DependencyInjection\ContainerInterface
   */
  public function rebuildContainer() {
    // Empty module properties and for them to be reloaded from scratch.
    $this->moduleList = NULL;
    $this->moduleData = array();
    return $this->initializeContainer(TRUE);
  }

  /**
   * Attach synthetic values on to kernel.
   *
   * @param ContainerInterface $container
   *   Container object
979
   *
980 981
   * @return ContainerInterface
   */
982
  protected function attachSynthetic(ContainerInterface $container) {
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
    $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.
1002 1003 1004
   *
   * @return ContainerBuilder The compiled service container
   */
1005 1006 1007 1008 1009 1010 1011 1012
  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;
    }

1013
    $this->initializeServiceProviders();
1014
    $container = $this->getContainerBuilder();
1015
    $container->set('kernel', $this);
1016
    $container->setParameter('container.modules', $this->getModulesParameter());
1017 1018

    // Get a list of namespaces and put it onto the container.
1019
    $namespaces = $this->getModuleNamespacesPsr4($this->getModuleFileNames());
1020 1021 1022 1023 1024
    // Add all components in \Drupal\Core and \Drupal\Component that have one of
    // the following directories:
    // - Element
    // - Entity
    // - Plugin
1025
    foreach (array('Core', 'Component') as $parent_directory) {
1026
      $path = $this->root . '/core/lib/Drupal/' . $parent_directory;
1027
      $parent_namespace = 'Drupal\\' . $parent_directory;
1028
      foreach (new \DirectoryIterator($path) as $component) {
1029 1030 1031 1032 1033 1034 1035
        /** @var $component \DirectoryIterator */
        $pathname = $component->getPathname();
        if (!$component->isDot() && $component->isDir() && (
          is_dir($pathname . '/Plugin') ||
          is_dir($pathname . '/Entity') ||
          is_dir($pathname . '/Element')
        )) {
1036
          $namespaces[$parent_namespace . '\\' . $component->getFilename()] = $path . '/' . $component->getFilename();
1037 1038 1039
        }
      }
    }
1040 1041
    $container->setParameter('container.namespaces', $namespaces);

1042 1043 1044 1045 1046 1047
    // 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;
1048 1049
    if ($system = $this->getConfigStorage()->read('system.site')) {
      if ($default_language_values['id'] != $system['langcode']) {
1050
        $default_language_values = array('id' => $system['langcode']);
1051
      }
1052 1053 1054
    }
    $container->setParameter('language.default_values', $default_language_values);

1055
    // Register synthetic services.
1056
    $container->register('class_loader')->setSynthetic(TRUE);
1057 1058
    $container->register('kernel', 'Symfony\Component\HttpKernel\KernelInterface')->setSynthetic(TRUE);
    $container->register('service_container', 'Symfony\Component\DependencyInjection\ContainerInterface')->setSynthetic(TRUE);
1059 1060

    // Register application services.
1061
    $yaml_loader = new YamlFileLoader($container);
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    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) {
1072 1073
      $yaml_loader->load($filename);
    }
1074
    foreach ($this->serviceProviders['site'] as $provider) {
1075 1076 1077
      if ($provider instanceof ServiceProviderInterface) {
        $provider->register($container);
      }
1078
    }
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091

    // 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) {
      if ($definition->isSynthetic() || $definition->getTag('persist')) {
        $persist_ids[] = $id;
      }
    }
    $container->setParameter('persistIds', $persist_ids);

1092
    $container->compile();
1093 1094
    return $container;
  }
1095

1096 1097 1098 1099 1100 1101
  /**
   * Registers all service providers to the kernel.
   *
   * @throws \LogicException
   */
  protected function initializeServiceProviders() {
1102 1103 1104 1105 1106 1107 1108 1109
    $this->discoverServiceProviders();
    $this->serviceProviders = array(
      'app' => array(),
      'site' => array(),
    );
    foreach ($this->serviceProviderClasses as $origin => $classes) {
      foreach ($classes as $name => $class) {
        $this->serviceProviders[$origin][$name] = new $class;
1110 1111 1112 1113
      }
    }
  }

1114 1115 1116 1117 1118
  /**
   * Gets a new ContainerBuilder instance used to build the service container.
   *
   * @return ContainerBuilder
   */
1119
  protected function getContainerBuilder() {
1120 1121 1122
    return new ContainerBuilder(new ParameterBag($this->getKernelParameters()));
  }

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
  /**
   * Dumps the service container to PHP code in the config directory.
   *
   * This method is based on the dumpContainer method in the parent class, but
   * that method is reliant on the Config component which we do not use here.
   *
   * @param ContainerBuilder $container
   *   The service container.
   * @param string $baseClass
   *   The name of the container's base class
   *
   * @return bool
   *   TRUE if the container was successfully dumped to disk.
   */
  protected function dumpDrupalContainer(ContainerBuilder $container, $baseClass) {
1138
    if (!$this->storage()->writeable()) {
1139 1140 1141 1142
      return FALSE;
    }
    // Cache the container.
    $dumper = new PhpDumper($container);
1143 1144
    $class = $this->getClassName();
    $content = $dumper->dump(array('class' => $class, 'base_class' => $baseClass));
1145
    return $this->storage()->save($class . '.php', $content);
1146 1147
  }

1148 1149 1150 1151

  /**
   * Gets a http kernel from the container
   *
1152
   * @return \Symfony\Component\HttpKernel\HttpKernelInterface
1153 1154 1155 1156 1157
   */
  protected function getHttpKernel() {
    return $this->container->get('http_kernel');
  }