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