annotate core/includes/bootstrap.inc @ 0:4c8ae668cc8c

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