Drupal investigation

bootstrap.inc 37KB

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