bootstrap.inc 38 KB

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