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