DrupalKernel.php 55 KB

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