bootstrap.inc 35 KB

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