annotate core/includes/bootstrap.inc @ 19:fa3358dc1485 tip

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