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