bootstrap.inc 37 KB

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