DrupalKernel.php 54 KB

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