annotate core/includes/bootstrap.inc @ 0:c75dbcec494b

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