bootstrap.inc 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. <?php
  2. /**
  3. * @file
  4. * Functions that need to be loaded on every Drupal request.
  5. */
  6. use Drupal\Component\Utility\Crypt;
  7. use Drupal\Component\Utility\Html;
  8. use Drupal\Component\Utility\SafeMarkup;
  9. use Drupal\Component\Utility\Unicode;
  10. use Drupal\Core\Config\BootstrapConfigStorageFactory;
  11. use Drupal\Core\Logger\RfcLogLevel;
  12. use Drupal\Core\Test\TestDatabase;
  13. use Drupal\Core\Session\AccountInterface;
  14. use Drupal\Core\Site\Settings;
  15. use Drupal\Core\Utility\Error;
  16. use Drupal\Core\StringTranslation\TranslatableMarkup;
  17. /**
  18. * Minimum supported version of PHP.
  19. *
  20. * Drupal cannot be installed on versions of PHP older than this version.
  21. *
  22. * @todo Move this to an appropriate autoloadable class. See
  23. * https://www.drupal.org/project/drupal/issues/2908079
  24. */
  25. const DRUPAL_MINIMUM_PHP = '5.5.9';
  26. /**
  27. * Minimum recommended version of PHP.
  28. *
  29. * Sites installing Drupal on PHP versions lower than this will see a warning
  30. * message, but Drupal can still be installed. Used for (e.g.) PHP versions
  31. * that have reached their EOL or will in the near future.
  32. *
  33. * @todo Move this to an appropriate autoloadable class. See
  34. * https://www.drupal.org/project/drupal/issues/2908079
  35. */
  36. const DRUPAL_RECOMMENDED_PHP = '7.1';
  37. /**
  38. * Minimum recommended value of PHP memory_limit.
  39. *
  40. * 64M was chosen as a minimum requirement in order to allow for additional
  41. * contributed modules to be installed prior to hitting the limit. However,
  42. * 40M is the target for the Standard installation profile.
  43. *
  44. * @todo Move this to an appropriate autoloadable class. See
  45. * https://www.drupal.org/project/drupal/issues/2908079
  46. */
  47. const DRUPAL_MINIMUM_PHP_MEMORY_LIMIT = '64M';
  48. /**
  49. * Error reporting level: display no errors.
  50. */
  51. const ERROR_REPORTING_HIDE = 'hide';
  52. /**
  53. * Error reporting level: display errors and warnings.
  54. */
  55. const ERROR_REPORTING_DISPLAY_SOME = 'some';
  56. /**
  57. * Error reporting level: display all messages.
  58. */
  59. const ERROR_REPORTING_DISPLAY_ALL = 'all';
  60. /**
  61. * Error reporting level: display all messages, plus backtrace information.
  62. */
  63. const ERROR_REPORTING_DISPLAY_VERBOSE = 'verbose';
  64. /**
  65. * Role ID for anonymous users; should match what's in the "role" table.
  66. *
  67. * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
  68. * Use Drupal\Core\Session\AccountInterface::ANONYMOUS_ROLE or
  69. * \Drupal\user\RoleInterface::ANONYMOUS_ID instead.
  70. *
  71. * @see https://www.drupal.org/node/1619504
  72. */
  73. const DRUPAL_ANONYMOUS_RID = AccountInterface::ANONYMOUS_ROLE;
  74. /**
  75. * Role ID for authenticated users; should match what's in the "role" table.
  76. *
  77. * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
  78. * Use Drupal\Core\Session\AccountInterface::AUTHENTICATED_ROLE or
  79. * \Drupal\user\RoleInterface::AUTHENTICATED_ID instead.
  80. *
  81. * @see https://www.drupal.org/node/1619504
  82. */
  83. const DRUPAL_AUTHENTICATED_RID = AccountInterface::AUTHENTICATED_ROLE;
  84. /**
  85. * The maximum number of characters in a module or theme name.
  86. */
  87. const DRUPAL_EXTENSION_NAME_MAX_LENGTH = 50;
  88. /**
  89. * Time of the current request in seconds elapsed since the Unix Epoch.
  90. *
  91. * This differs from $_SERVER['REQUEST_TIME'], which is stored as a float
  92. * since PHP 5.4.0. Float timestamps confuse most PHP functions
  93. * (including date_create()).
  94. *
  95. * @see http://php.net/manual/reserved.variables.server.php
  96. * @see http://php.net/manual/function.time.php
  97. *
  98. * @deprecated in Drupal 8.3.0, will be removed before Drupal 9.0.0.
  99. * Use \Drupal::time()->getRequestTime();
  100. *
  101. * @see https://www.drupal.org/node/2785211
  102. */
  103. define('REQUEST_TIME', (int) $_SERVER['REQUEST_TIME']);
  104. /**
  105. * Regular expression to match PHP function names.
  106. *
  107. * @see http://php.net/manual/language.functions.php
  108. */
  109. const DRUPAL_PHP_FUNCTION_PATTERN = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*';
  110. /**
  111. * $config_directories key for active directory.
  112. *
  113. * @see config_get_config_directory()
  114. *
  115. * @deprecated in Drupal 8.0.x and will be removed before 9.0.0. Drupal core no
  116. * longer creates an active directory.
  117. *
  118. * @see https://www.drupal.org/node/2501187
  119. */
  120. const CONFIG_ACTIVE_DIRECTORY = 'active';
  121. /**
  122. * $config_directories key for sync directory.
  123. *
  124. * @see config_get_config_directory()
  125. */
  126. const CONFIG_SYNC_DIRECTORY = 'sync';
  127. /**
  128. * $config_directories key for staging directory.
  129. *
  130. * @see config_get_config_directory()
  131. * @see CONFIG_SYNC_DIRECTORY
  132. *
  133. * @deprecated in Drupal 8.0.x and will be removed before 9.0.0. The staging
  134. * directory was renamed to sync.
  135. *
  136. * @see https://www.drupal.org/node/2574957
  137. */
  138. const CONFIG_STAGING_DIRECTORY = 'staging';
  139. /**
  140. * Defines the root directory of the Drupal installation.
  141. *
  142. * This strips two levels of directories off the current directory.
  143. */
  144. define('DRUPAL_ROOT', dirname(dirname(__DIR__)));
  145. /**
  146. * Returns the path of a configuration directory.
  147. *
  148. * Configuration directories are configured using $config_directories in
  149. * settings.php.
  150. *
  151. * @param string $type
  152. * The type of config directory to return. Drupal core provides the
  153. * CONFIG_SYNC_DIRECTORY constant to access the sync directory.
  154. *
  155. * @return string
  156. * The configuration directory path.
  157. *
  158. * @throws \Exception
  159. */
  160. function config_get_config_directory($type) {
  161. global $config_directories;
  162. // @todo Remove fallback in Drupal 9. https://www.drupal.org/node/2574943
  163. if ($type == CONFIG_SYNC_DIRECTORY && !isset($config_directories[CONFIG_SYNC_DIRECTORY]) && isset($config_directories[CONFIG_STAGING_DIRECTORY])) {
  164. $type = CONFIG_STAGING_DIRECTORY;
  165. }
  166. if (!empty($config_directories[$type])) {
  167. return $config_directories[$type];
  168. }
  169. // @todo https://www.drupal.org/node/2696103 Throw a more specific exception.
  170. throw new \Exception("The configuration directory type '$type' does not exist");
  171. }
  172. /**
  173. * Returns and optionally sets the filename for a system resource.
  174. *
  175. * The filename, whether provided, cached, or retrieved from the database, is
  176. * only returned if the file exists.
  177. *
  178. * This function plays a key role in allowing Drupal's resources (modules
  179. * and themes) to be located in different places depending on a site's
  180. * configuration. For example, a module 'foo' may legally be located
  181. * in any of these three places:
  182. *
  183. * core/modules/foo/foo.info.yml
  184. * modules/foo/foo.info.yml
  185. * sites/example.com/modules/foo/foo.info.yml
  186. *
  187. * Calling drupal_get_filename('module', 'foo') will give you one of
  188. * the above, depending on where the module is located.
  189. *
  190. * @param $type
  191. * The type of the item; one of 'core', 'profile', 'module', 'theme', or
  192. * 'theme_engine'.
  193. * @param $name
  194. * The name of the item for which the filename is requested. Ignored for
  195. * $type 'core'.
  196. * @param $filename
  197. * The filename of the item if it is to be set explicitly rather
  198. * than by consulting the database.
  199. *
  200. * @return string
  201. * The filename of the requested item or NULL if the item is not found.
  202. */
  203. function drupal_get_filename($type, $name, $filename = NULL) {
  204. // The location of files will not change during the request, so do not use
  205. // drupal_static().
  206. static $files = [];
  207. // Type 'core' only exists to simplify application-level logic; it always maps
  208. // to the /core directory, whereas $name is ignored. It is only requested via
  209. // drupal_get_path(). /core/core.info.yml does not exist, but is required
  210. // since drupal_get_path() returns the dirname() of the returned pathname.
  211. if ($type === 'core') {
  212. return 'core/core.info.yml';
  213. }
  214. // Profiles are converted into modules in system_rebuild_module_data().
  215. // @todo Remove false-exposure of profiles as modules.
  216. if ($type == 'profile') {
  217. $type = 'module';
  218. }
  219. if (!isset($files[$type])) {
  220. $files[$type] = [];
  221. }
  222. if (isset($filename)) {
  223. $files[$type][$name] = $filename;
  224. }
  225. elseif (!isset($files[$type][$name])) {
  226. // If the pathname of the requested extension is not known, try to retrieve
  227. // the list of extension pathnames from various providers, checking faster
  228. // providers first.
  229. // Retrieve the current module list (derived from the service container).
  230. if ($type == 'module' && \Drupal::hasService('module_handler')) {
  231. foreach (\Drupal::moduleHandler()->getModuleList() as $module_name => $module) {
  232. $files[$type][$module_name] = $module->getPathname();
  233. }
  234. }
  235. // If still unknown, retrieve the file list prepared in state by
  236. // system_rebuild_module_data() and
  237. // \Drupal\Core\Extension\ThemeHandlerInterface::rebuildThemeData().
  238. if (!isset($files[$type][$name]) && \Drupal::hasService('state')) {
  239. $files[$type] += \Drupal::state()->get('system.' . $type . '.files', []);
  240. }
  241. // If still unknown, create a user-level error message.
  242. if (!isset($files[$type][$name])) {
  243. trigger_error(SafeMarkup::format('The following @type is missing from the file system: @name', ['@type' => $type, '@name' => $name]), E_USER_WARNING);
  244. }
  245. }
  246. if (isset($files[$type][$name])) {
  247. return $files[$type][$name];
  248. }
  249. }
  250. /**
  251. * Returns the path to a system item (module, theme, etc.).
  252. *
  253. * @param $type
  254. * The type of the item; one of 'core', 'profile', 'module', 'theme', or
  255. * 'theme_engine'.
  256. * @param $name
  257. * The name of the item for which the path is requested. Ignored for
  258. * $type 'core'.
  259. *
  260. * @return string
  261. * The path to the requested item or an empty string if the item is not found.
  262. */
  263. function drupal_get_path($type, $name) {
  264. return dirname(drupal_get_filename($type, $name));
  265. }
  266. /**
  267. * Translates a string to the current language or to a given language.
  268. *
  269. * In order for strings to be localized, make them available in one of the ways
  270. * supported by the @link i18n Localization API. @endlink When possible, use
  271. * the \Drupal\Core\StringTranslation\StringTranslationTrait $this->t().
  272. * Otherwise create a new \Drupal\Core\StringTranslation\TranslatableMarkup
  273. * object directly.
  274. *
  275. * See \Drupal\Core\StringTranslation\TranslatableMarkup::__construct() for
  276. * important security information and usage guidelines.
  277. *
  278. * @param string $string
  279. * A string containing the English text to translate.
  280. * @param array $args
  281. * (optional) An associative array of replacements to make after translation.
  282. * Based on the first character of the key, the value is escaped and/or
  283. * themed. See
  284. * \Drupal\Component\Render\FormattableMarkup::placeholderFormat() for
  285. * details.
  286. * @param array $options
  287. * (optional) An associative array of additional options, with the following
  288. * elements:
  289. * - 'langcode' (defaults to the current language): A language code, to
  290. * translate to a language other than what is used to display the page.
  291. * - 'context' (defaults to the empty context): The context the source string
  292. * belongs to. See the @link i18n Internationalization topic @endlink for
  293. * more information about string contexts.
  294. *
  295. * @return \Drupal\Core\StringTranslation\TranslatableMarkup
  296. * An object that, when cast to a string, returns the translated string.
  297. *
  298. * @see \Drupal\Component\Render\FormattableMarkup::placeholderFormat()
  299. * @see \Drupal\Core\StringTranslation\StringTranslationTrait::t()
  300. * @see \Drupal\Core\StringTranslation\TranslatableMarkup::__construct()
  301. *
  302. * @ingroup sanitization
  303. */
  304. function t($string, array $args = [], array $options = []) {
  305. return new TranslatableMarkup($string, $args, $options);
  306. }
  307. /**
  308. * Formats a string for HTML display by replacing variable placeholders.
  309. *
  310. * @see \Drupal\Component\Render\FormattableMarkup::placeholderFormat()
  311. * @see \Drupal\Component\Render\FormattableMarkup
  312. * @see t()
  313. * @ingroup sanitization
  314. *
  315. * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
  316. * Use \Drupal\Component\Render\FormattableMarkup.
  317. *
  318. * @see https://www.drupal.org/node/2302363
  319. */
  320. function format_string($string, array $args) {
  321. return SafeMarkup::format($string, $args);
  322. }
  323. /**
  324. * Checks whether a string is valid UTF-8.
  325. *
  326. * All functions designed to filter input should use drupal_validate_utf8
  327. * to ensure they operate on valid UTF-8 strings to prevent bypass of the
  328. * filter.
  329. *
  330. * When text containing an invalid UTF-8 lead byte (0xC0 - 0xFF) is presented
  331. * as UTF-8 to Internet Explorer 6, the program may misinterpret subsequent
  332. * bytes. When these subsequent bytes are HTML control characters such as
  333. * quotes or angle brackets, parts of the text that were deemed safe by filters
  334. * end up in locations that are potentially unsafe; An onerror attribute that
  335. * is outside of a tag, and thus deemed safe by a filter, can be interpreted
  336. * by the browser as if it were inside the tag.
  337. *
  338. * The function does not return FALSE for strings containing character codes
  339. * above U+10FFFF, even though these are prohibited by RFC 3629.
  340. *
  341. * @param $text
  342. * The text to check.
  343. *
  344. * @return bool
  345. * TRUE if the text is valid UTF-8, FALSE if not.
  346. *
  347. * @see \Drupal\Component\Utility\Unicode::validateUtf8()
  348. *
  349. * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
  350. * Use \Drupal\Component\Utility\Unicode::validateUtf8().
  351. *
  352. * @see https://www.drupal.org/node/1992584
  353. */
  354. function drupal_validate_utf8($text) {
  355. return Unicode::validateUtf8($text);
  356. }
  357. /**
  358. * Logs an exception.
  359. *
  360. * This is a wrapper logging function which automatically decodes an exception.
  361. *
  362. * @param $type
  363. * The category to which this message belongs.
  364. * @param $exception
  365. * The exception that is going to be logged.
  366. * @param $message
  367. * The message to store in the log. If empty, a text that contains all useful
  368. * information about the passed-in exception is used.
  369. * @param $variables
  370. * Array of variables to replace in the message on display or
  371. * NULL if message is already translated or not possible to
  372. * translate.
  373. * @param $severity
  374. * The severity of the message, as per RFC 3164.
  375. * @param $link
  376. * A link to associate with the message.
  377. *
  378. * @see \Drupal\Core\Utility\Error::decodeException()
  379. */
  380. function watchdog_exception($type, Exception $exception, $message = NULL, $variables = [], $severity = RfcLogLevel::ERROR, $link = NULL) {
  381. // Use a default value if $message is not set.
  382. if (empty($message)) {
  383. $message = '%type: @message in %function (line %line of %file).';
  384. }
  385. if ($link) {
  386. $variables['link'] = $link;
  387. }
  388. $variables += Error::decodeException($exception);
  389. \Drupal::logger($type)->log($severity, $message, $variables);
  390. }
  391. /**
  392. * Sets a message to display to the user.
  393. *
  394. * Messages are stored in a session variable and displayed in the page template
  395. * via the $messages theme variable.
  396. *
  397. * Example usage:
  398. * @code
  399. * drupal_set_message(t('An error occurred and processing did not complete.'), 'error');
  400. * @endcode
  401. *
  402. * @param string|\Drupal\Component\Render\MarkupInterface $message
  403. * (optional) The translated message to be displayed to the user. For
  404. * consistency with other messages, it should begin with a capital letter and
  405. * end with a period.
  406. * @param string $type
  407. * (optional) The message's type. Defaults to 'status'. These values are
  408. * supported:
  409. * - 'status'
  410. * - 'warning'
  411. * - 'error'
  412. * @param bool $repeat
  413. * (optional) If this is FALSE and the message is already set, then the
  414. * message won't be repeated. Defaults to FALSE.
  415. *
  416. * @return array|null
  417. * A multidimensional array with keys corresponding to the set message types.
  418. * The indexed array values of each contain the set messages for that type,
  419. * and each message is an associative array with the following format:
  420. * - safe: Boolean indicating whether the message string has been marked as
  421. * safe. Non-safe strings will be escaped automatically.
  422. * - message: The message string.
  423. * So, the following is an example of the full return array structure:
  424. * @code
  425. * array(
  426. * 'status' => array(
  427. * array(
  428. * 'safe' => TRUE,
  429. * 'message' => 'A <em>safe</em> markup string.',
  430. * ),
  431. * array(
  432. * 'safe' => FALSE,
  433. * 'message' => "$arbitrary_user_input to escape.",
  434. * ),
  435. * ),
  436. * );
  437. * @endcode
  438. * If there are no messages set, the function returns NULL.
  439. *
  440. * @see drupal_get_messages()
  441. * @see status-messages.html.twig
  442. * @see https://www.drupal.org/node/2774931
  443. *
  444. * @deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0.
  445. * Use \Drupal\Core\Messenger\MessengerInterface::addMessage() instead.
  446. */
  447. function drupal_set_message($message = NULL, $type = 'status', $repeat = FALSE) {
  448. @trigger_error('drupal_set_message() is deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\Messenger\MessengerInterface::addMessage() instead. See https://www.drupal.org/node/2774931', E_USER_DEPRECATED);
  449. $messenger = \Drupal::messenger();
  450. if (isset($message)) {
  451. $messenger->addMessage($message, $type, $repeat);
  452. }
  453. return $messenger->all();
  454. }
  455. /**
  456. * Returns all messages that have been set with drupal_set_message().
  457. *
  458. * @param string $type
  459. * (optional) Limit the messages returned by type. Defaults to NULL, meaning
  460. * all types. These values are supported:
  461. * - NULL
  462. * - 'status'
  463. * - 'warning'
  464. * - 'error'
  465. * @param bool $clear_queue
  466. * (optional) If this is TRUE, the queue will be cleared of messages of the
  467. * type specified in the $type parameter. Otherwise the queue will be left
  468. * intact. Defaults to TRUE.
  469. *
  470. * @return array
  471. * An associative, nested array of messages grouped by message type, with
  472. * the top-level keys as the message type. The messages returned are
  473. * limited to the type specified in the $type parameter, if any. If there
  474. * are no messages of the specified type, an empty array is returned. See
  475. * drupal_set_message() for the array structure of individual messages.
  476. *
  477. * @see drupal_set_message()
  478. * @see status-messages.html.twig
  479. * @see https://www.drupal.org/node/2774931
  480. *
  481. * @deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0.
  482. * Use \Drupal\Core\Messenger\MessengerInterface::all() or
  483. * \Drupal\Core\Messenger\MessengerInterface::messagesByType() instead.
  484. */
  485. function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
  486. @trigger_error('drupal_get_message() is deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\Messenger\MessengerInterface::all() or \Drupal\Core\Messenger\MessengerInterface::messagesByType() instead. See https://www.drupal.org/node/2774931', E_USER_DEPRECATED);
  487. $messenger = \Drupal::messenger();
  488. if ($messages = $messenger->all()) {
  489. if ($type) {
  490. if ($clear_queue) {
  491. $messenger->deleteByType($type);
  492. }
  493. if (isset($messages[$type])) {
  494. return [$type => $messages[$type]];
  495. }
  496. }
  497. else {
  498. if ($clear_queue) {
  499. $messenger->deleteAll();
  500. }
  501. return $messages;
  502. }
  503. }
  504. return [];
  505. }
  506. /**
  507. * Returns the time zone of the current user.
  508. *
  509. * @return string
  510. * The name of the current user's timezone or the name of the default timezone.
  511. */
  512. function drupal_get_user_timezone() {
  513. $user = \Drupal::currentUser();
  514. $config = \Drupal::config('system.date');
  515. if ($user && $config->get('timezone.user.configurable') && $user->isAuthenticated() && $user->getTimezone()) {
  516. return $user->getTimezone();
  517. }
  518. else {
  519. // Ignore PHP strict notice if time zone has not yet been set in the php.ini
  520. // configuration.
  521. $config_data_default_timezone = $config->get('timezone.default');
  522. return !empty($config_data_default_timezone) ? $config_data_default_timezone : @date_default_timezone_get();
  523. }
  524. }
  525. /**
  526. * Provides custom PHP error handling.
  527. *
  528. * @param $error_level
  529. * The level of the error raised.
  530. * @param $message
  531. * The error message.
  532. * @param $filename
  533. * The filename that the error was raised in.
  534. * @param $line
  535. * The line number the error was raised at.
  536. * @param $context
  537. * An array that points to the active symbol table at the point the error
  538. * occurred.
  539. */
  540. function _drupal_error_handler($error_level, $message, $filename, $line, $context) {
  541. require_once __DIR__ . '/errors.inc';
  542. _drupal_error_handler_real($error_level, $message, $filename, $line, $context);
  543. }
  544. /**
  545. * Provides custom PHP exception handling.
  546. *
  547. * Uncaught exceptions are those not enclosed in a try/catch block. They are
  548. * always fatal: the execution of the script will stop as soon as the exception
  549. * handler exits.
  550. *
  551. * @param \Exception|\Throwable $exception
  552. * The exception object that was thrown.
  553. */
  554. function _drupal_exception_handler($exception) {
  555. require_once __DIR__ . '/errors.inc';
  556. try {
  557. // Log the message to the watchdog and return an error page to the user.
  558. _drupal_log_error(Error::decodeException($exception), TRUE);
  559. }
  560. // PHP 7 introduces Throwable, which covers both Error and
  561. // Exception throwables.
  562. catch (\Throwable $error) {
  563. _drupal_exception_handler_additional($exception, $error);
  564. }
  565. // In order to be compatible with PHP 5 we also catch regular Exceptions.
  566. catch (\Exception $exception2) {
  567. _drupal_exception_handler_additional($exception, $exception2);
  568. }
  569. }
  570. /**
  571. * Displays any additional errors caught while handling an exception.
  572. *
  573. * @param \Exception|\Throwable $exception
  574. * The first exception object that was thrown.
  575. * @param \Exception|\Throwable $exception2
  576. * The second exception object that was thrown.
  577. */
  578. function _drupal_exception_handler_additional($exception, $exception2) {
  579. // Another uncaught exception was thrown while handling the first one.
  580. // If we are displaying errors, then do so with no possibility of a further
  581. // uncaught exception being thrown.
  582. if (error_displayable()) {
  583. print '<h1>Additional uncaught exception thrown while handling exception.</h1>';
  584. print '<h2>Original</h2><p>' . Error::renderExceptionSafe($exception) . '</p>';
  585. print '<h2>Additional</h2><p>' . Error::renderExceptionSafe($exception2) . '</p><hr />';
  586. }
  587. }
  588. /**
  589. * Returns the test prefix if this is an internal request from SimpleTest.
  590. *
  591. * @param string $new_prefix
  592. * Internal use only. A new prefix to be stored.
  593. *
  594. * @return string|false
  595. * Either the simpletest prefix (the string "simpletest" followed by any
  596. * number of digits) or FALSE if the user agent does not contain a valid
  597. * HMAC and timestamp.
  598. */
  599. function drupal_valid_test_ua($new_prefix = NULL) {
  600. static $test_prefix;
  601. if (isset($new_prefix)) {
  602. $test_prefix = $new_prefix;
  603. }
  604. if (isset($test_prefix)) {
  605. return $test_prefix;
  606. }
  607. // Unless the below User-Agent and HMAC validation succeeds, we are not in
  608. // a test environment.
  609. $test_prefix = FALSE;
  610. // A valid Simpletest request will contain a hashed and salted authentication
  611. // code. Check if this code is present in a cookie or custom user agent
  612. // string.
  613. $http_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : NULL;
  614. $user_agent = isset($_COOKIE['SIMPLETEST_USER_AGENT']) ? $_COOKIE['SIMPLETEST_USER_AGENT'] : $http_user_agent;
  615. if (isset($user_agent) && preg_match("/^simple(\w+\d+):(.+):(.+):(.+)$/", $user_agent, $matches)) {
  616. list(, $prefix, $time, $salt, $hmac) = $matches;
  617. $check_string = $prefix . ':' . $time . ':' . $salt;
  618. // Read the hash salt prepared by drupal_generate_test_ua().
  619. // This function is called before settings.php is read and Drupal's error
  620. // handlers are set up. While Drupal's error handling may be properly
  621. // configured on production sites, the server's PHP error_reporting may not.
  622. // Ensure that no information leaks on production sites.
  623. $test_db = new TestDatabase($prefix);
  624. $key_file = DRUPAL_ROOT . '/' . $test_db->getTestSitePath() . '/.htkey';
  625. if (!is_readable($key_file)) {
  626. header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
  627. exit;
  628. }
  629. $private_key = file_get_contents($key_file);
  630. // The file properties add more entropy not easily accessible to others.
  631. $key = $private_key . filectime(__FILE__) . fileinode(__FILE__);
  632. $time_diff = REQUEST_TIME - $time;
  633. $test_hmac = Crypt::hmacBase64($check_string, $key);
  634. // Since we are making a local request a 600 second time window is allowed,
  635. // and the HMAC must match.
  636. if ($time_diff >= 0 && $time_diff <= 600 && $hmac === $test_hmac) {
  637. $test_prefix = $prefix;
  638. }
  639. else {
  640. header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden (SIMPLETEST_USER_AGENT invalid)');
  641. exit;
  642. }
  643. }
  644. return $test_prefix;
  645. }
  646. /**
  647. * Generates a user agent string with a HMAC and timestamp for simpletest.
  648. */
  649. function drupal_generate_test_ua($prefix) {
  650. static $key, $last_prefix;
  651. if (!isset($key) || $last_prefix != $prefix) {
  652. $last_prefix = $prefix;
  653. $test_db = new TestDatabase($prefix);
  654. $key_file = DRUPAL_ROOT . '/' . $test_db->getTestSitePath() . '/.htkey';
  655. // When issuing an outbound HTTP client request from within an inbound test
  656. // request, then the outbound request has to use the same User-Agent header
  657. // as the inbound request. A newly generated private key for the same test
  658. // prefix would invalidate all subsequent inbound requests.
  659. // @see \Drupal\Core\Http\Plugin\SimpletestHttpRequestSubscriber
  660. if (DRUPAL_TEST_IN_CHILD_SITE && $parent_prefix = drupal_valid_test_ua()) {
  661. if ($parent_prefix != $prefix) {
  662. throw new \RuntimeException("Malformed User-Agent: Expected '$parent_prefix' but got '$prefix'.");
  663. }
  664. // If the file is not readable, a PHP warning is expected in this case.
  665. $private_key = file_get_contents($key_file);
  666. }
  667. else {
  668. // Generate and save a new hash salt for a test run.
  669. // Consumed by drupal_valid_test_ua() before settings.php is loaded.
  670. $private_key = Crypt::randomBytesBase64(55);
  671. file_put_contents($key_file, $private_key);
  672. }
  673. // The file properties add more entropy not easily accessible to others.
  674. $key = $private_key . filectime(__FILE__) . fileinode(__FILE__);
  675. }
  676. // Generate a moderately secure HMAC based on the database credentials.
  677. $salt = uniqid('', TRUE);
  678. $check_string = $prefix . ':' . time() . ':' . $salt;
  679. return 'simple' . $check_string . ':' . Crypt::hmacBase64($check_string, $key);
  680. }
  681. /**
  682. * Enables use of the theme system without requiring database access.
  683. *
  684. * Loads and initializes the theme system for site installs, updates and when
  685. * the site is in maintenance mode. This also applies when the database fails.
  686. *
  687. * @see _drupal_maintenance_theme()
  688. */
  689. function drupal_maintenance_theme() {
  690. require_once __DIR__ . '/theme.maintenance.inc';
  691. _drupal_maintenance_theme();
  692. }
  693. /**
  694. * Returns TRUE if a Drupal installation is currently being attempted.
  695. */
  696. function drupal_installation_attempted() {
  697. // This cannot rely on the MAINTENANCE_MODE constant, since that would prevent
  698. // tests from using the non-interactive installer, in which case Drupal
  699. // only happens to be installed within the same request, but subsequently
  700. // executed code does not involve the installer at all.
  701. // @see install_drupal()
  702. return isset($GLOBALS['install_state']) && empty($GLOBALS['install_state']['installation_finished']);
  703. }
  704. /**
  705. * Gets the name of the currently active installation profile.
  706. *
  707. * When this function is called during Drupal's initial installation process,
  708. * the name of the profile that's about to be installed is stored in the global
  709. * installation state. At all other times, the "install_profile" setting will be
  710. * available in container as a parameter.
  711. *
  712. * @return string|null
  713. * The name of the installation profile or NULL if no installation profile is
  714. * currently active. This is the case for example during the first steps of
  715. * the installer or during unit tests.
  716. *
  717. * @deprecated in Drupal 8.3.0, will be removed before Drupal 9.0.0.
  718. * Use the install_profile container parameter or \Drupal::installProfile()
  719. * instead. If you are accessing the value before it is written to
  720. * configuration during the installer use the $install_state global. If you
  721. * need to access the value before container is available you can use
  722. * BootstrapConfigStorageFactory to load the value directly from
  723. * configuration.
  724. *
  725. * @see https://www.drupal.org/node/2538996
  726. */
  727. function drupal_get_profile() {
  728. global $install_state;
  729. if (drupal_installation_attempted()) {
  730. // If the profile has been selected return it.
  731. if (isset($install_state['parameters']['profile'])) {
  732. $profile = $install_state['parameters']['profile'];
  733. }
  734. else {
  735. $profile = NULL;
  736. }
  737. }
  738. else {
  739. if (\Drupal::hasContainer()) {
  740. $profile = \Drupal::installProfile();
  741. }
  742. else {
  743. $profile = BootstrapConfigStorageFactory::getDatabaseStorage()->read('core.extension')['profile'];
  744. }
  745. // A BC layer just in in case this only exists in Settings. Introduced in
  746. // Drupal 8.3.x and will be removed before Drupal 9.0.0.
  747. if (empty($profile)) {
  748. $profile = Settings::get('install_profile');
  749. }
  750. }
  751. return $profile;
  752. }
  753. /**
  754. * Registers an additional namespace.
  755. *
  756. * @param string $name
  757. * The namespace component to register; e.g., 'node'.
  758. * @param string $path
  759. * The relative path to the Drupal component in the filesystem.
  760. */
  761. function drupal_classloader_register($name, $path) {
  762. $loader = \Drupal::service('class_loader');
  763. $loader->addPsr4('Drupal\\' . $name . '\\', \Drupal::root() . '/' . $path . '/src');
  764. }
  765. /**
  766. * Provides central static variable storage.
  767. *
  768. * All functions requiring a static variable to persist or cache data within
  769. * a single page request are encouraged to use this function unless it is
  770. * absolutely certain that the static variable will not need to be reset during
  771. * the page request. By centralizing static variable storage through this
  772. * function, other functions can rely on a consistent API for resetting any
  773. * other function's static variables.
  774. *
  775. * Example:
  776. * @code
  777. * function example_list($field = 'default') {
  778. * $examples = &drupal_static(__FUNCTION__);
  779. * if (!isset($examples)) {
  780. * // If this function is being called for the first time after a reset,
  781. * // query the database and execute any other code needed to retrieve
  782. * // information.
  783. * ...
  784. * }
  785. * if (!isset($examples[$field])) {
  786. * // If this function is being called for the first time for a particular
  787. * // index field, then execute code needed to index the information already
  788. * // available in $examples by the desired field.
  789. * ...
  790. * }
  791. * // Subsequent invocations of this function for a particular index field
  792. * // skip the above two code blocks and quickly return the already indexed
  793. * // information.
  794. * return $examples[$field];
  795. * }
  796. * function examples_admin_overview() {
  797. * // When building the content for the overview page, make sure to get
  798. * // completely fresh information.
  799. * drupal_static_reset('example_list');
  800. * ...
  801. * }
  802. * @endcode
  803. *
  804. * In a few cases, a function can have certainty that there is no legitimate
  805. * use-case for resetting that function's static variable. This is rare,
  806. * because when writing a function, it's hard to forecast all the situations in
  807. * which it will be used. A guideline is that if a function's static variable
  808. * does not depend on any information outside of the function that might change
  809. * during a single page request, then it's ok to use the "static" keyword
  810. * instead of the drupal_static() function.
  811. *
  812. * Example:
  813. * @code
  814. * function mymodule_log_stream_handle($new_handle = NULL) {
  815. * static $handle;
  816. * if (isset($new_handle)) {
  817. * $handle = $new_handle;
  818. * }
  819. * return $handle;
  820. * }
  821. * @endcode
  822. *
  823. * In a few cases, a function needs a resettable static variable, but the
  824. * function is called many times (100+) during a single page request, so
  825. * every microsecond of execution time that can be removed from the function
  826. * counts. These functions can use a more cumbersome, but faster variant of
  827. * calling drupal_static(). It works by storing the reference returned by
  828. * drupal_static() in the calling function's own static variable, thereby
  829. * removing the need to call drupal_static() for each iteration of the function.
  830. * Conceptually, it replaces:
  831. * @code
  832. * $foo = &drupal_static(__FUNCTION__);
  833. * @endcode
  834. * with:
  835. * @code
  836. * // Unfortunately, this does not work.
  837. * static $foo = &drupal_static(__FUNCTION__);
  838. * @endcode
  839. * However, the above line of code does not work, because PHP only allows static
  840. * variables to be initialized by literal values, and does not allow static
  841. * variables to be assigned to references.
  842. * - http://php.net/manual/language.variables.scope.php#language.variables.scope.static
  843. * - http://php.net/manual/language.variables.scope.php#language.variables.scope.references
  844. * The example below shows the syntax needed to work around both limitations.
  845. * For benchmarks and more information, see https://www.drupal.org/node/619666.
  846. *
  847. * Example:
  848. * @code
  849. * function example_default_format_type() {
  850. * // Use the advanced drupal_static() pattern, since this is called very often.
  851. * static $drupal_static_fast;
  852. * if (!isset($drupal_static_fast)) {
  853. * $drupal_static_fast['format_type'] = &drupal_static(__FUNCTION__);
  854. * }
  855. * $format_type = &$drupal_static_fast['format_type'];
  856. * ...
  857. * }
  858. * @endcode
  859. *
  860. * @param $name
  861. * Globally unique name for the variable. For a function with only one static,
  862. * variable, the function name (e.g. via the PHP magic __FUNCTION__ constant)
  863. * is recommended. For a function with multiple static variables add a
  864. * distinguishing suffix to the function name for each one.
  865. * @param $default_value
  866. * Optional default value.
  867. * @param $reset
  868. * TRUE to reset one or all variables(s). This parameter is only used
  869. * internally and should not be passed in; use drupal_static_reset() instead.
  870. * (This function's return value should not be used when TRUE is passed in.)
  871. *
  872. * @return array
  873. * Returns a variable by reference.
  874. *
  875. * @see drupal_static_reset()
  876. */
  877. function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
  878. static $data = [], $default = [];
  879. // First check if dealing with a previously defined static variable.
  880. if (isset($data[$name]) || array_key_exists($name, $data)) {
  881. // Non-NULL $name and both $data[$name] and $default[$name] statics exist.
  882. if ($reset) {
  883. // Reset pre-existing static variable to its default value.
  884. $data[$name] = $default[$name];
  885. }
  886. return $data[$name];
  887. }
  888. // Neither $data[$name] nor $default[$name] static variables exist.
  889. if (isset($name)) {
  890. if ($reset) {
  891. // Reset was called before a default is set and yet a variable must be
  892. // returned.
  893. return $data;
  894. }
  895. // First call with new non-NULL $name. Initialize a new static variable.
  896. $default[$name] = $data[$name] = $default_value;
  897. return $data[$name];
  898. }
  899. // Reset all: ($name == NULL). This needs to be done one at a time so that
  900. // references returned by earlier invocations of drupal_static() also get
  901. // reset.
  902. foreach ($default as $name => $value) {
  903. $data[$name] = $value;
  904. }
  905. // As the function returns a reference, the return should always be a
  906. // variable.
  907. return $data;
  908. }
  909. /**
  910. * Resets one or all centrally stored static variable(s).
  911. *
  912. * @param $name
  913. * Name of the static variable to reset. Omit to reset all variables.
  914. * Resetting all variables should only be used, for example, for running
  915. * unit tests with a clean environment.
  916. */
  917. function drupal_static_reset($name = NULL) {
  918. drupal_static($name, NULL, TRUE);
  919. }
  920. /**
  921. * Formats text for emphasized display in a placeholder inside a sentence.
  922. *
  923. * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0. Use
  924. * \Drupal\Component\Utility\SafeMarkup::format() or Twig's "placeholder"
  925. * filter instead. Note this method should not be used to simply emphasize a
  926. * string and therefore has few valid use-cases. Note also, that this method
  927. * does not mark the string as safe.
  928. *
  929. * @see https://www.drupal.org/node/2302363
  930. */
  931. function drupal_placeholder($text) {
  932. return '<em class="placeholder">' . Html::escape($text) . '</em>';
  933. }
  934. /**
  935. * Registers a function for execution on shutdown.
  936. *
  937. * Wrapper for register_shutdown_function() that catches thrown exceptions to
  938. * avoid "Exception thrown without a stack frame in Unknown".
  939. *
  940. * @param callable $callback
  941. * The shutdown function to register.
  942. * @param ...
  943. * Additional arguments to pass to the shutdown function.
  944. *
  945. * @return array
  946. * Array of shutdown functions to be executed.
  947. *
  948. * @see register_shutdown_function()
  949. * @ingroup php_wrappers
  950. */
  951. function &drupal_register_shutdown_function($callback = NULL) {
  952. // We cannot use drupal_static() here because the static cache is reset during
  953. // batch processing, which breaks batch handling.
  954. static $callbacks = [];
  955. if (isset($callback)) {
  956. // Only register the internal shutdown function once.
  957. if (empty($callbacks)) {
  958. register_shutdown_function('_drupal_shutdown_function');
  959. }
  960. $args = func_get_args();
  961. // Remove $callback from the arguments.
  962. unset($args[0]);
  963. // Save callback and arguments
  964. $callbacks[] = ['callback' => $callback, 'arguments' => $args];
  965. }
  966. return $callbacks;
  967. }
  968. /**
  969. * Executes registered shutdown functions.
  970. */
  971. function _drupal_shutdown_function() {
  972. $callbacks = &drupal_register_shutdown_function();
  973. // Set the CWD to DRUPAL_ROOT as it is not guaranteed to be the same as it
  974. // was in the normal context of execution.
  975. chdir(DRUPAL_ROOT);
  976. try {
  977. foreach ($callbacks as &$callback) {
  978. call_user_func_array($callback['callback'], $callback['arguments']);
  979. }
  980. }
  981. // PHP 7 introduces Throwable, which covers both Error and
  982. // Exception throwables.
  983. catch (\Throwable $error) {
  984. _drupal_shutdown_function_handle_exception($error);
  985. }
  986. // In order to be compatible with PHP 5 we also catch regular Exceptions.
  987. catch (\Exception $exception) {
  988. _drupal_shutdown_function_handle_exception($exception);
  989. }
  990. }
  991. /**
  992. * Displays and logs any errors that may happen during shutdown.
  993. *
  994. * @param \Exception|\Throwable $exception
  995. * The exception object that was thrown.
  996. *
  997. * @see _drupal_shutdown_function()
  998. */
  999. function _drupal_shutdown_function_handle_exception($exception) {
  1000. // If using PHP-FPM then fastcgi_finish_request() will have been fired
  1001. // preventing further output to the browser.
  1002. if (!function_exists('fastcgi_finish_request')) {
  1003. // If we are displaying errors, then do so with no possibility of a
  1004. // further uncaught exception being thrown.
  1005. require_once __DIR__ . '/errors.inc';
  1006. if (error_displayable()) {
  1007. print '<h1>Uncaught exception thrown in shutdown function.</h1>';
  1008. print '<p>' . Error::renderExceptionSafe($exception) . '</p><hr />';
  1009. }
  1010. }
  1011. error_log($exception);
  1012. }