annotate core/includes/bootstrap.inc @ 17:129ea1e6d783

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