DrupalKernel.php 55 KB

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