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

Update, including to Drupal core 8.6.10
author Chris Cannam
date Thu, 28 Feb 2019 13:21:36 +0000
parents c2387f117808
children af1871eacc83
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /**
Chris@0 4 * @file
Chris@0 5 * Common functions that many Drupal modules will need to reference.
Chris@0 6 *
Chris@0 7 * The functions that are critical and need to be available even when serving
Chris@0 8 * a cached page are instead located in bootstrap.inc.
Chris@0 9 */
Chris@0 10
Chris@0 11 use Drupal\Component\Serialization\Json;
Chris@0 12 use Drupal\Component\Utility\Bytes;
Chris@0 13 use Drupal\Component\Utility\Html;
Chris@0 14 use Drupal\Component\Utility\SortArray;
Chris@0 15 use Drupal\Component\Utility\UrlHelper;
Chris@0 16 use Drupal\Core\Cache\Cache;
Chris@0 17 use Drupal\Core\Render\Element\Link;
Chris@0 18 use Drupal\Core\Render\Markup;
Chris@0 19 use Drupal\Core\StringTranslation\TranslatableMarkup;
Chris@0 20 use Drupal\Core\StringTranslation\PluralTranslatableMarkup;
Chris@0 21 use Drupal\Core\Render\BubbleableMetadata;
Chris@0 22 use Drupal\Core\Render\Element;
Chris@0 23
Chris@0 24 /**
Chris@0 25 * @defgroup php_wrappers PHP wrapper functions
Chris@0 26 * @{
Chris@0 27 * Functions that are wrappers or custom implementations of PHP functions.
Chris@0 28 *
Chris@0 29 * Certain PHP functions should not be used in Drupal. Instead, Drupal's
Chris@0 30 * replacement functions should be used.
Chris@0 31 *
Chris@0 32 * For example, for improved or more secure UTF8-handling, or RFC-compliant
Chris@0 33 * handling of URLs in Drupal.
Chris@0 34 *
Chris@0 35 * For ease of use and memorizing, all these wrapper functions use the same name
Chris@0 36 * as the original PHP function, but prefixed with "drupal_". Beware, however,
Chris@0 37 * that not all wrapper functions support the same arguments as the original
Chris@0 38 * functions.
Chris@0 39 *
Chris@0 40 * You should always use these wrapper functions in your code.
Chris@0 41 *
Chris@0 42 * Wrong:
Chris@0 43 * @code
Chris@0 44 * $my_substring = substr($original_string, 0, 5);
Chris@0 45 * @endcode
Chris@0 46 *
Chris@0 47 * Correct:
Chris@0 48 * @code
Chris@17 49 * $my_substring = mb_substr($original_string, 0, 5);
Chris@0 50 * @endcode
Chris@0 51 *
Chris@0 52 * @}
Chris@0 53 */
Chris@0 54
Chris@0 55 /**
Chris@0 56 * Return status for saving which involved creating a new item.
Chris@0 57 */
Chris@0 58 const SAVED_NEW = 1;
Chris@0 59
Chris@0 60 /**
Chris@0 61 * Return status for saving which involved an update to an existing item.
Chris@0 62 */
Chris@0 63 const SAVED_UPDATED = 2;
Chris@0 64
Chris@0 65 /**
Chris@0 66 * Return status for saving which deleted an existing item.
Chris@0 67 */
Chris@0 68 const SAVED_DELETED = 3;
Chris@0 69
Chris@0 70 /**
Chris@0 71 * The default aggregation group for CSS files added to the page.
Chris@0 72 */
Chris@0 73 const CSS_AGGREGATE_DEFAULT = 0;
Chris@0 74
Chris@0 75 /**
Chris@0 76 * The default aggregation group for theme CSS files added to the page.
Chris@0 77 */
Chris@0 78 const CSS_AGGREGATE_THEME = 100;
Chris@0 79
Chris@0 80 /**
Chris@0 81 * The default weight for CSS rules that style HTML elements ("base" styles).
Chris@0 82 */
Chris@0 83 const CSS_BASE = -200;
Chris@0 84
Chris@0 85 /**
Chris@0 86 * The default weight for CSS rules that layout a page.
Chris@0 87 */
Chris@0 88 const CSS_LAYOUT = -100;
Chris@0 89
Chris@0 90 /**
Chris@0 91 * The default weight for CSS rules that style design components (and their associated states and themes.)
Chris@0 92 */
Chris@0 93 const CSS_COMPONENT = 0;
Chris@0 94
Chris@0 95 /**
Chris@0 96 * The default weight for CSS rules that style states and are not included with components.
Chris@0 97 */
Chris@0 98 const CSS_STATE = 100;
Chris@0 99
Chris@0 100 /**
Chris@0 101 * The default weight for CSS rules that style themes and are not included with components.
Chris@0 102 */
Chris@0 103 const CSS_THEME = 200;
Chris@0 104
Chris@0 105 /**
Chris@0 106 * The default group for JavaScript settings added to the page.
Chris@0 107 */
Chris@0 108 const JS_SETTING = -200;
Chris@0 109
Chris@0 110 /**
Chris@0 111 * The default group for JavaScript and jQuery libraries added to the page.
Chris@0 112 */
Chris@0 113 const JS_LIBRARY = -100;
Chris@0 114
Chris@0 115 /**
Chris@0 116 * The default group for module JavaScript code added to the page.
Chris@0 117 */
Chris@0 118 const JS_DEFAULT = 0;
Chris@0 119
Chris@0 120 /**
Chris@0 121 * The default group for theme JavaScript code added to the page.
Chris@0 122 */
Chris@0 123 const JS_THEME = 100;
Chris@0 124
Chris@0 125 /**
Chris@0 126 * The delimiter used to split plural strings.
Chris@0 127 *
Chris@0 128 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
Chris@0 129 * Use \Drupal\Core\StringTranslation\PluralTranslatableMarkup::DELIMITER
Chris@0 130 * instead.
Chris@0 131 */
Chris@0 132 const LOCALE_PLURAL_DELIMITER = PluralTranslatableMarkup::DELIMITER;
Chris@0 133
Chris@0 134 /**
Chris@0 135 * Prepares a 'destination' URL query parameter.
Chris@0 136 *
Chris@0 137 * Used to direct the user back to the referring page after completing a form.
Chris@0 138 * By default the current URL is returned. If a destination exists in the
Chris@0 139 * previous request, that destination is returned. As such, a destination can
Chris@0 140 * persist across multiple pages.
Chris@0 141 *
Chris@0 142 * @return array
Chris@0 143 * An associative array containing the key:
Chris@0 144 * - destination: The value of the current request's 'destination' query
Chris@0 145 * parameter, if present. This can be either a relative or absolute URL.
Chris@0 146 * However, for security, redirection to external URLs is not performed.
Chris@0 147 * If the query parameter isn't present, then the URL of the current
Chris@0 148 * request is returned.
Chris@0 149 *
Chris@0 150 * @ingroup form_api
Chris@0 151 *
Chris@0 152 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
Chris@0 153 * Use the redirect.destination service.
Chris@12 154 *
Chris@12 155 * @see \Drupal\Core\EventSubscriber\RedirectResponseSubscriber::checkRedirectUrl()
Chris@12 156 * @see https://www.drupal.org/node/2448603
Chris@0 157 */
Chris@0 158 function drupal_get_destination() {
Chris@0 159 return \Drupal::destination()->getAsArray();
Chris@0 160 }
Chris@0 161
Chris@0 162 /**
Chris@0 163 * @defgroup validation Input validation
Chris@0 164 * @{
Chris@0 165 * Functions to validate user input.
Chris@0 166 */
Chris@0 167
Chris@0 168 /**
Chris@0 169 * Verifies the syntax of the given email address.
Chris@0 170 *
Chris@0 171 * @param string $mail
Chris@0 172 * A string containing an email address.
Chris@0 173 *
Chris@0 174 * @return bool
Chris@0 175 * TRUE if the address is in a valid format.
Chris@0 176 *
Chris@0 177 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
Chris@0 178 * Use \Drupal::service('email.validator')->isValid().
Chris@12 179 *
Chris@12 180 * @see https://www.drupal.org/node/2912661
Chris@0 181 */
Chris@0 182 function valid_email_address($mail) {
Chris@0 183 return \Drupal::service('email.validator')->isValid($mail);
Chris@0 184 }
Chris@0 185
Chris@0 186 /**
Chris@0 187 * @} End of "defgroup validation".
Chris@0 188 */
Chris@0 189
Chris@0 190 /**
Chris@0 191 * @defgroup sanitization Sanitization functions
Chris@0 192 * @{
Chris@0 193 * Functions to sanitize values.
Chris@0 194 *
Chris@0 195 * See https://www.drupal.org/writing-secure-code for information
Chris@0 196 * on writing secure code.
Chris@0 197 */
Chris@0 198
Chris@0 199 /**
Chris@0 200 * Strips dangerous protocols from a URI and encodes it for output to HTML.
Chris@0 201 *
Chris@0 202 * @param $uri
Chris@0 203 * A plain-text URI that might contain dangerous protocols.
Chris@0 204 *
Chris@0 205 * @return string
Chris@0 206 * A URI stripped of dangerous protocols and encoded for output to an HTML
Chris@0 207 * attribute value. Because it is already encoded, it should not be set as a
Chris@0 208 * value within a $attributes array passed to Drupal\Core\Template\Attribute,
Chris@0 209 * because Drupal\Core\Template\Attribute expects those values to be
Chris@0 210 * plain-text strings. To pass a filtered URI to
Chris@0 211 * Drupal\Core\Template\Attribute, call
Chris@0 212 * \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() instead.
Chris@0 213 *
Chris@0 214 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
Chris@0 215 * Use UrlHelper::stripDangerousProtocols() or UrlHelper::filterBadProtocol()
Chris@0 216 * instead. UrlHelper::stripDangerousProtocols() can be used in conjunction
Chris@17 217 * with \Drupal\Component\Render\FormattableMarkup and an @variable
Chris@0 218 * placeholder which will perform the necessary escaping.
Chris@0 219 * UrlHelper::filterBadProtocol() is functionality equivalent to check_url()
Chris@0 220 * apart from the fact it is protected from double escaping bugs. Note that
Chris@0 221 * this method no longer marks its output as safe.
Chris@12 222 *
Chris@12 223 * @see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols()
Chris@12 224 * @see \Drupal\Component\Utility\UrlHelper::filterBadProtocol()
Chris@12 225 * @see https://www.drupal.org/node/2560027
Chris@0 226 */
Chris@0 227 function check_url($uri) {
Chris@0 228 return Html::escape(UrlHelper::stripDangerousProtocols($uri));
Chris@0 229 }
Chris@0 230
Chris@0 231 /**
Chris@0 232 * @} End of "defgroup sanitization".
Chris@0 233 */
Chris@0 234
Chris@0 235 /**
Chris@0 236 * @defgroup format Formatting
Chris@0 237 * @{
Chris@0 238 * Functions to format numbers, strings, dates, etc.
Chris@0 239 */
Chris@0 240
Chris@0 241 /**
Chris@0 242 * Generates a string representation for the given byte count.
Chris@0 243 *
Chris@0 244 * @param $size
Chris@0 245 * A size in bytes.
Chris@0 246 * @param $langcode
Chris@0 247 * Optional language code to translate to a language other than what is used
Chris@0 248 * to display the page.
Chris@0 249 *
Chris@0 250 * @return \Drupal\Core\StringTranslation\TranslatableMarkup
Chris@0 251 * A translated string representation of the size.
Chris@0 252 */
Chris@0 253 function format_size($size, $langcode = NULL) {
Chris@17 254 $absolute_size = abs($size);
Chris@17 255 if ($absolute_size < Bytes::KILOBYTE) {
Chris@0 256 return \Drupal::translation()->formatPlural($size, '1 byte', '@count bytes', [], ['langcode' => $langcode]);
Chris@0 257 }
Chris@17 258 // Create a multiplier to preserve the sign of $size.
Chris@17 259 $sign = $absolute_size / $size;
Chris@17 260 foreach (['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] as $unit) {
Chris@17 261 $absolute_size /= Bytes::KILOBYTE;
Chris@17 262 $rounded_size = round($absolute_size, 2);
Chris@17 263 if ($rounded_size < Bytes::KILOBYTE) {
Chris@17 264 break;
Chris@0 265 }
Chris@17 266 }
Chris@17 267 $args = ['@size' => $rounded_size * $sign];
Chris@17 268 $options = ['langcode' => $langcode];
Chris@17 269 switch ($unit) {
Chris@17 270 case 'KB':
Chris@17 271 return new TranslatableMarkup('@size KB', $args, $options);
Chris@17 272
Chris@17 273 case 'MB':
Chris@17 274 return new TranslatableMarkup('@size MB', $args, $options);
Chris@17 275
Chris@17 276 case 'GB':
Chris@17 277 return new TranslatableMarkup('@size GB', $args, $options);
Chris@17 278
Chris@17 279 case 'TB':
Chris@17 280 return new TranslatableMarkup('@size TB', $args, $options);
Chris@17 281
Chris@17 282 case 'PB':
Chris@17 283 return new TranslatableMarkup('@size PB', $args, $options);
Chris@17 284
Chris@17 285 case 'EB':
Chris@17 286 return new TranslatableMarkup('@size EB', $args, $options);
Chris@17 287
Chris@17 288 case 'ZB':
Chris@17 289 return new TranslatableMarkup('@size ZB', $args, $options);
Chris@17 290
Chris@17 291 case 'YB':
Chris@17 292 return new TranslatableMarkup('@size YB', $args, $options);
Chris@0 293 }
Chris@0 294 }
Chris@0 295
Chris@0 296 /**
Chris@0 297 * Formats a date, using a date type or a custom date format string.
Chris@0 298 *
Chris@0 299 * @param $timestamp
Chris@0 300 * A UNIX timestamp to format.
Chris@0 301 * @param $type
Chris@0 302 * (optional) The format to use, one of:
Chris@0 303 * - One of the built-in formats: 'short', 'medium',
Chris@0 304 * 'long', 'html_datetime', 'html_date', 'html_time',
Chris@0 305 * 'html_yearless_date', 'html_week', 'html_month', 'html_year'.
Chris@0 306 * - The name of a date type defined by a date format config entity.
Chris@0 307 * - The machine name of an administrator-defined date format.
Chris@0 308 * - 'custom', to use $format.
Chris@0 309 * Defaults to 'medium'.
Chris@0 310 * @param $format
Chris@0 311 * (optional) If $type is 'custom', a PHP date format string suitable for
Chris@0 312 * input to date(). Use a backslash to escape ordinary text, so it does not
Chris@0 313 * get interpreted as date format characters.
Chris@0 314 * @param $timezone
Chris@0 315 * (optional) Time zone identifier, as described at
Chris@0 316 * http://php.net/manual/timezones.php Defaults to the time zone used to
Chris@0 317 * display the page.
Chris@0 318 * @param $langcode
Chris@0 319 * (optional) Language code to translate to. Defaults to the language used to
Chris@0 320 * display the page.
Chris@0 321 *
Chris@0 322 * @return
Chris@0 323 * A translated date string in the requested format.
Chris@0 324 *
Chris@0 325 * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
Chris@0 326 * Use \Drupal::service('date.formatter')->format().
Chris@12 327 *
Chris@12 328 * @see \Drupal\Core\Datetime\DateFormatter::format()
Chris@12 329 * @see https://www.drupal.org/node/1876852
Chris@0 330 */
Chris@0 331 function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
Chris@0 332 return \Drupal::service('date.formatter')->format($timestamp, $type, $format, $timezone, $langcode);
Chris@0 333 }
Chris@0 334
Chris@0 335 /**
Chris@0 336 * Returns an ISO8601 formatted date based on the given date.
Chris@0 337 *
Chris@0 338 * @param $date
Chris@0 339 * A UNIX timestamp.
Chris@0 340 *
Chris@0 341 * @return string
Chris@0 342 * An ISO8601 formatted date.
Chris@0 343 */
Chris@0 344 function date_iso8601($date) {
Chris@0 345 // The DATE_ISO8601 constant cannot be used here because it does not match
Chris@0 346 // date('c') and produces invalid RDF markup.
Chris@0 347 return date('c', $date);
Chris@0 348 }
Chris@0 349
Chris@0 350 /**
Chris@0 351 * @} End of "defgroup format".
Chris@0 352 */
Chris@0 353
Chris@0 354 /**
Chris@0 355 * Formats an attribute string for an HTTP header.
Chris@0 356 *
Chris@0 357 * @param $attributes
Chris@0 358 * An associative array of attributes such as 'rel'.
Chris@0 359 *
Chris@0 360 * @return
Chris@0 361 * A ; separated string ready for insertion in a HTTP header. No escaping is
Chris@0 362 * performed for HTML entities, so this string is not safe to be printed.
Chris@0 363 */
Chris@0 364 function drupal_http_header_attributes(array $attributes = []) {
Chris@0 365 foreach ($attributes as $attribute => &$data) {
Chris@0 366 if (is_array($data)) {
Chris@0 367 $data = implode(' ', $data);
Chris@0 368 }
Chris@0 369 $data = $attribute . '="' . $data . '"';
Chris@0 370 }
Chris@0 371 return $attributes ? ' ' . implode('; ', $attributes) : '';
Chris@0 372 }
Chris@0 373
Chris@0 374 /**
Chris@0 375 * Attempts to set the PHP maximum execution time.
Chris@0 376 *
Chris@0 377 * This function is a wrapper around the PHP function set_time_limit().
Chris@0 378 * When called, set_time_limit() restarts the timeout counter from zero.
Chris@0 379 * In other words, if the timeout is the default 30 seconds, and 25 seconds
Chris@0 380 * into script execution a call such as set_time_limit(20) is made, the
Chris@0 381 * script will run for a total of 45 seconds before timing out.
Chris@0 382 *
Chris@0 383 * If the current time limit is not unlimited it is possible to decrease the
Chris@0 384 * total time limit if the sum of the new time limit and the current time spent
Chris@0 385 * running the script is inferior to the original time limit. It is inherent to
Chris@0 386 * the way set_time_limit() works, it should rather be called with an
Chris@0 387 * appropriate value every time you need to allocate a certain amount of time
Chris@0 388 * to execute a task than only once at the beginning of the script.
Chris@0 389 *
Chris@0 390 * Before calling set_time_limit(), we check if this function is available
Chris@0 391 * because it could be disabled by the server administrator. We also hide all
Chris@0 392 * the errors that could occur when calling set_time_limit(), because it is
Chris@0 393 * not possible to reliably ensure that PHP or a security extension will
Chris@0 394 * not issue a warning/error if they prevent the use of this function.
Chris@0 395 *
Chris@0 396 * @param $time_limit
Chris@0 397 * An integer specifying the new time limit, in seconds. A value of 0
Chris@0 398 * indicates unlimited execution time.
Chris@0 399 *
Chris@0 400 * @ingroup php_wrappers
Chris@0 401 */
Chris@0 402 function drupal_set_time_limit($time_limit) {
Chris@0 403 if (function_exists('set_time_limit')) {
Chris@0 404 $current = ini_get('max_execution_time');
Chris@0 405 // Do not set time limit if it is currently unlimited.
Chris@0 406 if ($current != 0) {
Chris@0 407 @set_time_limit($time_limit);
Chris@0 408 }
Chris@0 409 }
Chris@0 410 }
Chris@0 411
Chris@0 412 /**
Chris@0 413 * Returns the base URL path (i.e., directory) of the Drupal installation.
Chris@0 414 *
Chris@17 415 * Function base_path() adds a "/" to the beginning and end of the returned path
Chris@17 416 * if the path is not empty. At the very least, this will return "/".
Chris@0 417 *
Chris@0 418 * Examples:
Chris@0 419 * - http://example.com returns "/" because the path is empty.
Chris@0 420 * - http://example.com/drupal/folder returns "/drupal/folder/".
Chris@0 421 */
Chris@0 422 function base_path() {
Chris@0 423 return $GLOBALS['base_path'];
Chris@0 424 }
Chris@0 425
Chris@0 426 /**
Chris@0 427 * Deletes old cached CSS files.
Chris@0 428 *
Chris@0 429 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
Chris@0 430 * Use \Drupal\Core\Asset\AssetCollectionOptimizerInterface::deleteAll().
Chris@12 431 *
Chris@12 432 * @see https://www.drupal.org/node/2317841
Chris@0 433 */
Chris@0 434 function drupal_clear_css_cache() {
Chris@0 435 \Drupal::service('asset.css.collection_optimizer')->deleteAll();
Chris@0 436 }
Chris@0 437
Chris@0 438 /**
Chris@0 439 * Constructs an array of the defaults that are used for JavaScript assets.
Chris@0 440 *
Chris@0 441 * @param $data
Chris@0 442 * (optional) The default data parameter for the JavaScript asset array.
Chris@0 443 *
Chris@0 444 * @see hook_js_alter()
Chris@0 445 */
Chris@0 446 function drupal_js_defaults($data = NULL) {
Chris@0 447 return [
Chris@0 448 'type' => 'file',
Chris@0 449 'group' => JS_DEFAULT,
Chris@0 450 'weight' => 0,
Chris@0 451 'scope' => 'header',
Chris@0 452 'cache' => TRUE,
Chris@0 453 'preprocess' => TRUE,
Chris@0 454 'attributes' => [],
Chris@0 455 'version' => NULL,
Chris@0 456 'data' => $data,
Chris@0 457 'browsers' => [],
Chris@0 458 ];
Chris@0 459 }
Chris@0 460
Chris@0 461 /**
Chris@0 462 * Adds JavaScript to change the state of an element based on another element.
Chris@0 463 *
Chris@0 464 * A "state" means a certain property on a DOM element, such as "visible" or
Chris@0 465 * "checked". A state can be applied to an element, depending on the state of
Chris@0 466 * another element on the page. In general, states depend on HTML attributes and
Chris@0 467 * DOM element properties, which change due to user interaction.
Chris@0 468 *
Chris@0 469 * Since states are driven by JavaScript only, it is important to understand
Chris@0 470 * that all states are applied on presentation only, none of the states force
Chris@0 471 * any server-side logic, and that they will not be applied for site visitors
Chris@0 472 * without JavaScript support. All modules implementing states have to make
Chris@0 473 * sure that the intended logic also works without JavaScript being enabled.
Chris@0 474 *
Chris@0 475 * #states is an associative array in the form of:
Chris@0 476 * @code
Chris@0 477 * array(
Chris@0 478 * STATE1 => CONDITIONS_ARRAY1,
Chris@0 479 * STATE2 => CONDITIONS_ARRAY2,
Chris@0 480 * ...
Chris@0 481 * )
Chris@0 482 * @endcode
Chris@0 483 * Each key is the name of a state to apply to the element, such as 'visible'.
Chris@0 484 * Each value is a list of conditions that denote when the state should be
Chris@0 485 * applied.
Chris@0 486 *
Chris@0 487 * Multiple different states may be specified to act on complex conditions:
Chris@0 488 * @code
Chris@0 489 * array(
Chris@0 490 * 'visible' => CONDITIONS,
Chris@0 491 * 'checked' => OTHER_CONDITIONS,
Chris@0 492 * )
Chris@0 493 * @endcode
Chris@0 494 *
Chris@0 495 * Every condition is a key/value pair, whose key is a jQuery selector that
Chris@0 496 * denotes another element on the page, and whose value is an array of
Chris@17 497 * conditions, which must be met on that element:
Chris@0 498 * @code
Chris@0 499 * array(
Chris@0 500 * 'visible' => array(
Chris@0 501 * JQUERY_SELECTOR => REMOTE_CONDITIONS,
Chris@0 502 * JQUERY_SELECTOR => REMOTE_CONDITIONS,
Chris@0 503 * ...
Chris@0 504 * ),
Chris@0 505 * )
Chris@0 506 * @endcode
Chris@0 507 * All conditions must be met for the state to be applied.
Chris@0 508 *
Chris@0 509 * Each remote condition is a key/value pair specifying conditions on the other
Chris@0 510 * element that need to be met to apply the state to the element:
Chris@0 511 * @code
Chris@0 512 * array(
Chris@0 513 * 'visible' => array(
Chris@0 514 * ':input[name="remote_checkbox"]' => array('checked' => TRUE),
Chris@0 515 * ),
Chris@0 516 * )
Chris@0 517 * @endcode
Chris@0 518 *
Chris@0 519 * For example, to show a textfield only when a checkbox is checked:
Chris@0 520 * @code
Chris@0 521 * $form['toggle_me'] = array(
Chris@0 522 * '#type' => 'checkbox',
Chris@0 523 * '#title' => t('Tick this box to type'),
Chris@0 524 * );
Chris@0 525 * $form['settings'] = array(
Chris@0 526 * '#type' => 'textfield',
Chris@0 527 * '#states' => array(
Chris@0 528 * // Only show this field when the 'toggle_me' checkbox is enabled.
Chris@0 529 * 'visible' => array(
Chris@0 530 * ':input[name="toggle_me"]' => array('checked' => TRUE),
Chris@0 531 * ),
Chris@0 532 * ),
Chris@0 533 * );
Chris@0 534 * @endcode
Chris@0 535 *
Chris@0 536 * The following states may be applied to an element:
Chris@0 537 * - enabled
Chris@0 538 * - disabled
Chris@0 539 * - required
Chris@0 540 * - optional
Chris@0 541 * - visible
Chris@0 542 * - invisible
Chris@0 543 * - checked
Chris@0 544 * - unchecked
Chris@0 545 * - expanded
Chris@0 546 * - collapsed
Chris@0 547 *
Chris@0 548 * The following states may be used in remote conditions:
Chris@0 549 * - empty
Chris@0 550 * - filled
Chris@0 551 * - checked
Chris@0 552 * - unchecked
Chris@0 553 * - expanded
Chris@0 554 * - collapsed
Chris@0 555 * - value
Chris@0 556 *
Chris@0 557 * The following states exist for both elements and remote conditions, but are
Chris@0 558 * not fully implemented and may not change anything on the element:
Chris@0 559 * - relevant
Chris@0 560 * - irrelevant
Chris@0 561 * - valid
Chris@0 562 * - invalid
Chris@0 563 * - touched
Chris@0 564 * - untouched
Chris@0 565 * - readwrite
Chris@0 566 * - readonly
Chris@0 567 *
Chris@0 568 * When referencing select lists and radio buttons in remote conditions, a
Chris@0 569 * 'value' condition must be used:
Chris@0 570 * @code
Chris@0 571 * '#states' => array(
Chris@0 572 * // Show the settings if 'bar' has been selected for 'foo'.
Chris@0 573 * 'visible' => array(
Chris@0 574 * ':input[name="foo"]' => array('value' => 'bar'),
Chris@0 575 * ),
Chris@0 576 * ),
Chris@0 577 * @endcode
Chris@0 578 *
Chris@0 579 * @param $elements
Chris@0 580 * A renderable array element having a #states property as described above.
Chris@0 581 *
Chris@0 582 * @see form_example_states_form()
Chris@0 583 */
Chris@0 584 function drupal_process_states(&$elements) {
Chris@0 585 $elements['#attached']['library'][] = 'core/drupal.states';
Chris@0 586 // Elements of '#type' => 'item' are not actual form input elements, but we
Chris@0 587 // still want to be able to show/hide them. Since there's no actual HTML input
Chris@0 588 // element available, setting #attributes does not make sense, but a wrapper
Chris@0 589 // is available, so setting #wrapper_attributes makes it work.
Chris@0 590 $key = ($elements['#type'] == 'item') ? '#wrapper_attributes' : '#attributes';
Chris@0 591 $elements[$key]['data-drupal-states'] = Json::encode($elements['#states']);
Chris@0 592 }
Chris@0 593
Chris@0 594 /**
Chris@0 595 * Assists in attaching the tableDrag JavaScript behavior to a themed table.
Chris@0 596 *
Chris@0 597 * Draggable tables should be used wherever an outline or list of sortable items
Chris@0 598 * needs to be arranged by an end-user. Draggable tables are very flexible and
Chris@0 599 * can manipulate the value of form elements placed within individual columns.
Chris@0 600 *
Chris@0 601 * To set up a table to use drag and drop in place of weight select-lists or in
Chris@0 602 * place of a form that contains parent relationships, the form must be themed
Chris@0 603 * into a table. The table must have an ID attribute set and it
Chris@0 604 * may be set as follows:
Chris@0 605 * @code
Chris@0 606 * $table = array(
Chris@0 607 * '#type' => 'table',
Chris@0 608 * '#header' => $header,
Chris@0 609 * '#rows' => $rows,
Chris@0 610 * '#attributes' => array(
Chris@0 611 * 'id' => 'my-module-table',
Chris@0 612 * ),
Chris@0 613 * );
Chris@16 614 * return \Drupal::service('renderer')->render($table);
Chris@0 615 * @endcode
Chris@0 616 *
Chris@0 617 * In the theme function for the form, a special class must be added to each
Chris@0 618 * form element within the same column, "grouping" them together.
Chris@0 619 *
Chris@0 620 * In a situation where a single weight column is being sorted in the table, the
Chris@0 621 * classes could be added like this (in the theme function):
Chris@0 622 * @code
Chris@0 623 * $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
Chris@0 624 * @endcode
Chris@0 625 *
Chris@0 626 * Each row of the table must also have a class of "draggable" in order to
Chris@0 627 * enable the drag handles:
Chris@0 628 * @code
Chris@0 629 * $row = array(...);
Chris@0 630 * $rows[] = array(
Chris@0 631 * 'data' => $row,
Chris@0 632 * 'class' => array('draggable'),
Chris@0 633 * );
Chris@0 634 * @endcode
Chris@0 635 *
Chris@0 636 * When tree relationships are present, the two additional classes
Chris@0 637 * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
Chris@0 638 * - Rows with the 'tabledrag-leaf' class cannot have child rows.
Chris@0 639 * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
Chris@0 640 *
Chris@0 641 * Calling drupal_attach_tabledrag() would then be written as such:
Chris@0 642 * @code
Chris@0 643 * drupal_attach_tabledrag('my-module-table', array(
Chris@0 644 * 'action' => 'order',
Chris@0 645 * 'relationship' => 'sibling',
Chris@0 646 * 'group' => 'my-elements-weight',
Chris@0 647 * );
Chris@0 648 * @endcode
Chris@0 649 *
Chris@0 650 * In a more complex case where there are several groups in one column (such as
Chris@0 651 * the block regions on the admin/structure/block page), a separate subgroup
Chris@0 652 * class must also be added to differentiate the groups.
Chris@0 653 * @code
Chris@0 654 * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
Chris@0 655 * @endcode
Chris@0 656 *
Chris@0 657 * The 'group' option is still 'my-element-weight', and the additional
Chris@0 658 * 'subgroup' option will be passed in as 'my-elements-weight-' . $region. This
Chris@0 659 * also means that you'll need to call drupal_attach_tabledrag() once for every
Chris@0 660 * region added.
Chris@0 661 *
Chris@0 662 * @code
Chris@0 663 * foreach ($regions as $region) {
Chris@0 664 * drupal_attach_tabledrag('my-module-table', array(
Chris@0 665 * 'action' => 'order',
Chris@0 666 * 'relationship' => 'sibling',
Chris@0 667 * 'group' => 'my-elements-weight',
Chris@0 668 * 'subgroup' => 'my-elements-weight-' . $region,
Chris@0 669 * ));
Chris@0 670 * }
Chris@0 671 * @endcode
Chris@0 672 *
Chris@0 673 * In a situation where tree relationships are present, adding multiple
Chris@0 674 * subgroups is not necessary, because the table will contain indentations that
Chris@0 675 * provide enough information about the sibling and parent relationships. See
Chris@0 676 * MenuForm::BuildOverviewForm for an example creating a table
Chris@0 677 * containing parent relationships.
Chris@0 678 *
Chris@0 679 * @param $element
Chris@0 680 * A form element to attach the tableDrag behavior to.
Chris@0 681 * @param array $options
Chris@0 682 * These options are used to generate JavaScript settings necessary to
Chris@0 683 * configure the tableDrag behavior appropriately for this particular table.
Chris@0 684 * An associative array containing the following keys:
Chris@0 685 * - 'table_id': String containing the target table's id attribute.
Chris@0 686 * If the table does not have an id, one will need to be set,
Chris@0 687 * such as <table id="my-module-table">.
Chris@0 688 * - 'action': String describing the action to be done on the form item.
Chris@0 689 * Either 'match' 'depth', or 'order':
Chris@0 690 * - 'match' is typically used for parent relationships.
Chris@0 691 * - 'order' is typically used to set weights on other form elements with
Chris@0 692 * the same group.
Chris@0 693 * - 'depth' updates the target element with the current indentation.
Chris@0 694 * - 'relationship': String describing where the "action" option
Chris@0 695 * should be performed. Either 'parent', 'sibling', 'group', or 'self':
Chris@0 696 * - 'parent' will only look for fields up the tree.
Chris@0 697 * - 'sibling' will look for fields in the same group in rows above and
Chris@0 698 * below it.
Chris@0 699 * - 'self' affects the dragged row itself.
Chris@0 700 * - 'group' affects the dragged row, plus any children below it (the entire
Chris@0 701 * dragged group).
Chris@0 702 * - 'group': A class name applied on all related form elements for this action.
Chris@0 703 * - 'subgroup': (optional) If the group has several subgroups within it, this
Chris@0 704 * string should contain the class name identifying fields in the same
Chris@0 705 * subgroup.
Chris@0 706 * - 'source': (optional) If the $action is 'match', this string should contain
Chris@0 707 * the classname identifying what field will be used as the source value
Chris@0 708 * when matching the value in $subgroup.
Chris@0 709 * - 'hidden': (optional) The column containing the field elements may be
Chris@0 710 * entirely hidden from view dynamically when the JavaScript is loaded. Set
Chris@0 711 * to FALSE if the column should not be hidden.
Chris@0 712 * - 'limit': (optional) Limit the maximum amount of parenting in this table.
Chris@0 713 *
Chris@0 714 * @see MenuForm::BuildOverviewForm()
Chris@0 715 */
Chris@0 716 function drupal_attach_tabledrag(&$element, array $options) {
Chris@0 717 // Add default values to elements.
Chris@0 718 $options = $options + [
Chris@0 719 'subgroup' => NULL,
Chris@0 720 'source' => NULL,
Chris@0 721 'hidden' => TRUE,
Chris@17 722 'limit' => 0,
Chris@0 723 ];
Chris@0 724
Chris@0 725 $group = $options['group'];
Chris@0 726
Chris@0 727 $tabledrag_id = &drupal_static(__FUNCTION__);
Chris@0 728 $tabledrag_id = (!isset($tabledrag_id)) ? 0 : $tabledrag_id + 1;
Chris@0 729
Chris@0 730 // If a subgroup or source isn't set, assume it is the same as the group.
Chris@0 731 $target = isset($options['subgroup']) ? $options['subgroup'] : $group;
Chris@0 732 $source = isset($options['source']) ? $options['source'] : $target;
Chris@0 733 $element['#attached']['drupalSettings']['tableDrag'][$options['table_id']][$group][$tabledrag_id] = [
Chris@0 734 'target' => $target,
Chris@0 735 'source' => $source,
Chris@0 736 'relationship' => $options['relationship'],
Chris@0 737 'action' => $options['action'],
Chris@0 738 'hidden' => $options['hidden'],
Chris@0 739 'limit' => $options['limit'],
Chris@0 740 ];
Chris@0 741
Chris@0 742 $element['#attached']['library'][] = 'core/drupal.tabledrag';
Chris@0 743 }
Chris@0 744
Chris@0 745 /**
Chris@0 746 * Deletes old cached JavaScript files and variables.
Chris@0 747 *
Chris@0 748 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
Chris@0 749 * Use \Drupal\Core\Asset\AssetCollectionOptimizerInterface::deleteAll().
Chris@12 750 *
Chris@12 751 * @see https://www.drupal.org/node/2317841
Chris@0 752 */
Chris@0 753 function drupal_clear_js_cache() {
Chris@0 754 \Drupal::service('asset.js.collection_optimizer')->deleteAll();
Chris@0 755 }
Chris@0 756
Chris@0 757 /**
Chris@0 758 * Pre-render callback: Renders a link into #markup.
Chris@0 759 *
Chris@0 760 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
Chris@0 761 * Use \Drupal\Core\Render\Element\Link::preRenderLink().
Chris@0 762 */
Chris@0 763 function drupal_pre_render_link($element) {
Chris@0 764 return Link::preRenderLink($element);
Chris@0 765 }
Chris@0 766
Chris@0 767 /**
Chris@0 768 * Pre-render callback: Collects child links into a single array.
Chris@0 769 *
Chris@0 770 * This function can be added as a pre_render callback for a renderable array,
Chris@0 771 * usually one which will be themed by links.html.twig. It iterates through all
Chris@0 772 * unrendered children of the element, collects any #links properties it finds,
Chris@0 773 * merges them into the parent element's #links array, and prevents those
Chris@0 774 * children from being rendered separately.
Chris@0 775 *
Chris@0 776 * The purpose of this is to allow links to be logically grouped into related
Chris@0 777 * categories, so that each child group can be rendered as its own list of
Chris@0 778 * links if drupal_render() is called on it, but calling drupal_render() on the
Chris@0 779 * parent element will still produce a single list containing all the remaining
Chris@0 780 * links, regardless of what group they were in.
Chris@0 781 *
Chris@0 782 * A typical example comes from node links, which are stored in a renderable
Chris@0 783 * array similar to this:
Chris@0 784 * @code
Chris@0 785 * $build['links'] = array(
Chris@0 786 * '#theme' => 'links__node',
Chris@0 787 * '#pre_render' => array('drupal_pre_render_links'),
Chris@0 788 * 'comment' => array(
Chris@0 789 * '#theme' => 'links__node__comment',
Chris@0 790 * '#links' => array(
Chris@0 791 * // An array of links associated with node comments, suitable for
Chris@0 792 * // passing in to links.html.twig.
Chris@0 793 * ),
Chris@0 794 * ),
Chris@0 795 * 'statistics' => array(
Chris@0 796 * '#theme' => 'links__node__statistics',
Chris@0 797 * '#links' => array(
Chris@0 798 * // An array of links associated with node statistics, suitable for
Chris@0 799 * // passing in to links.html.twig.
Chris@0 800 * ),
Chris@0 801 * ),
Chris@0 802 * 'translation' => array(
Chris@0 803 * '#theme' => 'links__node__translation',
Chris@0 804 * '#links' => array(
Chris@0 805 * // An array of links associated with node translation, suitable for
Chris@0 806 * // passing in to links.html.twig.
Chris@0 807 * ),
Chris@0 808 * ),
Chris@0 809 * );
Chris@0 810 * @endcode
Chris@0 811 *
Chris@0 812 * In this example, the links are grouped by functionality, which can be
Chris@0 813 * helpful to themers who want to display certain kinds of links independently.
Chris@0 814 * For example, adding this code to node.html.twig will result in the comment
Chris@0 815 * links being rendered as a single list:
Chris@0 816 * @code
Chris@0 817 * {{ content.links.comment }}
Chris@0 818 * @endcode
Chris@0 819 *
Chris@0 820 * (where a node's content has been transformed into $content before handing
Chris@0 821 * control to the node.html.twig template).
Chris@0 822 *
Chris@0 823 * The pre_render function defined here allows the above flexibility, but also
Chris@0 824 * allows the following code to be used to render all remaining links into a
Chris@0 825 * single list, regardless of their group:
Chris@0 826 * @code
Chris@0 827 * {{ content.links }}
Chris@0 828 * @endcode
Chris@0 829 *
Chris@0 830 * In the above example, this will result in the statistics and translation
Chris@0 831 * links being rendered together in a single list (but not the comment links,
Chris@0 832 * which were rendered previously on their own).
Chris@0 833 *
Chris@0 834 * Because of the way this function works, the individual properties of each
Chris@0 835 * group (for example, a group-specific #theme property such as
Chris@0 836 * 'links__node__comment' in the example above, or any other property such as
Chris@0 837 * #attributes or #pre_render that is attached to it) are only used when that
Chris@0 838 * group is rendered on its own. When the group is rendered together with other
Chris@0 839 * children, these child-specific properties are ignored, and only the overall
Chris@0 840 * properties of the parent are used.
Chris@0 841 */
Chris@0 842 function drupal_pre_render_links($element) {
Chris@0 843 $element += ['#links' => [], '#attached' => []];
Chris@0 844 foreach (Element::children($element) as $key) {
Chris@0 845 $child = &$element[$key];
Chris@0 846 // If the child has links which have not been printed yet and the user has
Chris@0 847 // access to it, merge its links in to the parent.
Chris@0 848 if (isset($child['#links']) && empty($child['#printed']) && Element::isVisibleElement($child)) {
Chris@0 849 $element['#links'] += $child['#links'];
Chris@0 850 // Mark the child as having been printed already (so that its links
Chris@0 851 // cannot be mistakenly rendered twice).
Chris@0 852 $child['#printed'] = TRUE;
Chris@0 853 }
Chris@0 854 // Merge attachments.
Chris@0 855 if (isset($child['#attached'])) {
Chris@0 856 $element['#attached'] = BubbleableMetadata::mergeAttachments($element['#attached'], $child['#attached']);
Chris@0 857 }
Chris@0 858 }
Chris@0 859 return $element;
Chris@0 860 }
Chris@0 861
Chris@0 862 /**
Chris@0 863 * Renders final HTML given a structured array tree.
Chris@0 864 *
Chris@0 865 * @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0. Use the
Chris@0 866 * 'renderer' service instead.
Chris@0 867 *
Chris@0 868 * @see \Drupal\Core\Render\RendererInterface::renderRoot()
Chris@12 869 * @see https://www.drupal.org/node/2912696
Chris@0 870 */
Chris@0 871 function drupal_render_root(&$elements) {
Chris@0 872 return \Drupal::service('renderer')->renderRoot($elements);
Chris@0 873 }
Chris@0 874
Chris@0 875 /**
Chris@0 876 * Renders HTML given a structured array tree.
Chris@0 877 *
Chris@0 878 * @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0. Use the
Chris@0 879 * 'renderer' service instead.
Chris@0 880 *
Chris@0 881 * @see \Drupal\Core\Render\RendererInterface::render()
Chris@12 882 * @see https://www.drupal.org/node/2912696
Chris@0 883 */
Chris@0 884 function drupal_render(&$elements, $is_recursive_call = FALSE) {
Chris@0 885 return \Drupal::service('renderer')->render($elements, $is_recursive_call);
Chris@0 886 }
Chris@0 887
Chris@0 888 /**
Chris@0 889 * Renders children of an element and concatenates them.
Chris@0 890 *
Chris@0 891 * @param array $element
Chris@0 892 * The structured array whose children shall be rendered.
Chris@0 893 * @param array $children_keys
Chris@0 894 * (optional) If the keys of the element's children are already known, they
Chris@0 895 * can be passed in to save another run of
Chris@0 896 * \Drupal\Core\Render\Element::children().
Chris@0 897 *
Chris@0 898 * @return string|\Drupal\Component\Render\MarkupInterface
Chris@0 899 * The rendered HTML of all children of the element.
Chris@0 900 *
Chris@0 901 * @deprecated in Drupal 8.0.x and will be removed before 9.0.0. Avoid early
Chris@0 902 * rendering when possible or loop through the elements and render them as
Chris@0 903 * they are available.
Chris@0 904 *
Chris@16 905 * @see \Drupal\Core\Render\RendererInterface::render()
Chris@12 906 * @see https://www.drupal.org/node/2912757
Chris@0 907 */
Chris@0 908 function drupal_render_children(&$element, $children_keys = NULL) {
Chris@0 909 if ($children_keys === NULL) {
Chris@0 910 $children_keys = Element::children($element);
Chris@0 911 }
Chris@0 912 $output = '';
Chris@0 913 foreach ($children_keys as $key) {
Chris@0 914 if (!empty($element[$key])) {
Chris@0 915 $output .= \Drupal::service('renderer')->render($element[$key]);
Chris@0 916 }
Chris@0 917 }
Chris@0 918 return Markup::create($output);
Chris@0 919 }
Chris@0 920
Chris@0 921 /**
Chris@0 922 * Renders an element.
Chris@0 923 *
Chris@0 924 * This function renders an element. The top level element is shown with show()
Chris@0 925 * before rendering, so it will always be rendered even if hide() had been
Chris@0 926 * previously used on it.
Chris@0 927 *
Chris@0 928 * @param $element
Chris@0 929 * The element to be rendered.
Chris@0 930 *
Chris@0 931 * @return
Chris@0 932 * The rendered element.
Chris@0 933 *
Chris@0 934 * @see \Drupal\Core\Render\RendererInterface
Chris@0 935 * @see show()
Chris@0 936 * @see hide()
Chris@0 937 */
Chris@0 938 function render(&$element) {
Chris@0 939 if (!$element && $element !== 0) {
Chris@0 940 return NULL;
Chris@0 941 }
Chris@0 942 if (is_array($element)) {
Chris@0 943 // Early return if this element was pre-rendered (no need to re-render).
Chris@0 944 if (isset($element['#printed']) && $element['#printed'] == TRUE && isset($element['#markup']) && strlen($element['#markup']) > 0) {
Chris@0 945 return $element['#markup'];
Chris@0 946 }
Chris@0 947 show($element);
Chris@0 948 return \Drupal::service('renderer')->render($element);
Chris@0 949 }
Chris@0 950 else {
Chris@0 951 // Safe-guard for inappropriate use of render() on flat variables: return
Chris@0 952 // the variable as-is.
Chris@0 953 return $element;
Chris@0 954 }
Chris@0 955 }
Chris@0 956
Chris@0 957 /**
Chris@0 958 * Hides an element from later rendering.
Chris@0 959 *
Chris@0 960 * The first time render() or drupal_render() is called on an element tree,
Chris@0 961 * as each element in the tree is rendered, it is marked with a #printed flag
Chris@0 962 * and the rendered children of the element are cached. Subsequent calls to
Chris@0 963 * render() or drupal_render() will not traverse the child tree of this element
Chris@0 964 * again: they will just use the cached children. So if you want to hide an
Chris@0 965 * element, be sure to call hide() on the element before its parent tree is
Chris@0 966 * rendered for the first time, as it will have no effect on subsequent
Chris@0 967 * renderings of the parent tree.
Chris@0 968 *
Chris@0 969 * @param $element
Chris@0 970 * The element to be hidden.
Chris@0 971 *
Chris@0 972 * @return
Chris@0 973 * The element.
Chris@0 974 *
Chris@0 975 * @see render()
Chris@0 976 * @see show()
Chris@0 977 */
Chris@0 978 function hide(&$element) {
Chris@0 979 $element['#printed'] = TRUE;
Chris@0 980 return $element;
Chris@0 981 }
Chris@0 982
Chris@0 983 /**
Chris@0 984 * Shows a hidden element for later rendering.
Chris@0 985 *
Chris@0 986 * You can also use render($element), which shows the element while rendering
Chris@0 987 * it.
Chris@0 988 *
Chris@0 989 * The first time render() or drupal_render() is called on an element tree,
Chris@0 990 * as each element in the tree is rendered, it is marked with a #printed flag
Chris@0 991 * and the rendered children of the element are cached. Subsequent calls to
Chris@0 992 * render() or drupal_render() will not traverse the child tree of this element
Chris@0 993 * again: they will just use the cached children. So if you want to show an
Chris@0 994 * element, be sure to call show() on the element before its parent tree is
Chris@0 995 * rendered for the first time, as it will have no effect on subsequent
Chris@0 996 * renderings of the parent tree.
Chris@0 997 *
Chris@0 998 * @param $element
Chris@0 999 * The element to be shown.
Chris@0 1000 *
Chris@0 1001 * @return
Chris@0 1002 * The element.
Chris@0 1003 *
Chris@0 1004 * @see render()
Chris@0 1005 * @see hide()
Chris@0 1006 */
Chris@0 1007 function show(&$element) {
Chris@0 1008 $element['#printed'] = FALSE;
Chris@0 1009 return $element;
Chris@0 1010 }
Chris@0 1011
Chris@0 1012 /**
Chris@0 1013 * Retrieves the default properties for the defined element type.
Chris@0 1014 *
Chris@0 1015 * @param $type
Chris@0 1016 * An element type as defined by an element plugin.
Chris@0 1017 *
Chris@0 1018 * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
Chris@0 1019 * Use \Drupal::service('element_info')->getInfo() instead.
Chris@12 1020 *
Chris@12 1021 * @see https://www.drupal.org/node/2235461
Chris@0 1022 */
Chris@0 1023 function element_info($type) {
Chris@0 1024 return \Drupal::service('element_info')->getInfo($type);
Chris@0 1025 }
Chris@0 1026
Chris@0 1027 /**
Chris@0 1028 * Retrieves a single property for the defined element type.
Chris@0 1029 *
Chris@0 1030 * @param $type
Chris@0 1031 * An element type as defined by an element plugin.
Chris@0 1032 * @param $property_name
Chris@0 1033 * The property within the element type that should be returned.
Chris@0 1034 * @param $default
Chris@0 1035 * (Optional) The value to return if the element type does not specify a
Chris@0 1036 * value for the property. Defaults to NULL.
Chris@0 1037 *
Chris@0 1038 * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
Chris@0 1039 * Use \Drupal::service('element_info')->getInfoProperty() instead.
Chris@12 1040 *
Chris@12 1041 * @see https://www.drupal.org/node/2235461
Chris@0 1042 */
Chris@0 1043 function element_info_property($type, $property_name, $default = NULL) {
Chris@0 1044 return \Drupal::service('element_info')->getInfoProperty($type, $property_name, $default);
Chris@0 1045 }
Chris@0 1046
Chris@0 1047 /**
Chris@0 1048 * Flushes all persistent caches, resets all variables, and rebuilds all data structures.
Chris@0 1049 *
Chris@0 1050 * At times, it is necessary to re-initialize the entire system to account for
Chris@0 1051 * changed or new code. This function:
Chris@0 1052 * - Clears all persistent caches:
Chris@0 1053 * - The bootstrap cache bin containing base system, module system, and theme
Chris@0 1054 * system information.
Chris@0 1055 * - The common 'default' cache bin containing arbitrary caches.
Chris@0 1056 * - The page cache.
Chris@0 1057 * - The URL alias path cache.
Chris@0 1058 * - Resets all static variables that have been defined via drupal_static().
Chris@0 1059 * - Clears asset (JS/CSS) file caches.
Chris@0 1060 * - Updates the system with latest information about extensions (modules and
Chris@0 1061 * themes).
Chris@0 1062 * - Updates the bootstrap flag for modules implementing bootstrap_hooks().
Chris@0 1063 * - Rebuilds the full database schema information (invoking hook_schema()).
Chris@0 1064 * - Rebuilds data structures of all modules (invoking hook_rebuild()). In
Chris@0 1065 * core this means
Chris@0 1066 * - blocks, node types, date formats and actions are synchronized with the
Chris@0 1067 * database
Chris@0 1068 * - The 'active' status of fields is refreshed.
Chris@0 1069 * - Rebuilds the menu router.
Chris@0 1070 *
Chris@0 1071 * This means the entire system is reset so all caches and static variables are
Chris@0 1072 * effectively empty. After that is guaranteed, information about the currently
Chris@0 1073 * active code is updated, and rebuild operations are successively called in
Chris@0 1074 * order to synchronize the active system according to the current information
Chris@0 1075 * defined in code.
Chris@0 1076 *
Chris@0 1077 * All modules need to ensure that all of their caches are flushed when
Chris@0 1078 * hook_cache_flush() is invoked; any previously known information must no
Chris@0 1079 * longer exist. All following hook_rebuild() operations must be based on fresh
Chris@0 1080 * and current system data. All modules must be able to rely on this contract.
Chris@0 1081 *
Chris@0 1082 * @see \Drupal\Core\Cache\CacheHelper::getBins()
Chris@0 1083 * @see hook_cache_flush()
Chris@0 1084 * @see hook_rebuild()
Chris@0 1085 *
Chris@0 1086 * This function also resets the theme, which means it is not initialized
Chris@0 1087 * anymore and all previously added JavaScript and CSS is gone. Normally, this
Chris@0 1088 * function is called as an end-of-POST-request operation that is followed by a
Chris@0 1089 * redirect, so this effect is not visible. Since the full reset is the whole
Chris@0 1090 * point of this function, callers need to take care for backing up all needed
Chris@0 1091 * variables and properly restoring or re-initializing them on their own. For
Chris@0 1092 * convenience, this function automatically re-initializes the maintenance theme
Chris@0 1093 * if it was initialized before.
Chris@0 1094 *
Chris@0 1095 * @todo Try to clear page/JS/CSS caches last, so cached pages can still be
Chris@0 1096 * served during this possibly long-running operation. (Conflict on bootstrap
Chris@0 1097 * cache though.)
Chris@0 1098 * @todo Add a global lock to ensure that caches are not primed in concurrent
Chris@0 1099 * requests.
Chris@0 1100 */
Chris@0 1101 function drupal_flush_all_caches() {
Chris@0 1102 $module_handler = \Drupal::moduleHandler();
Chris@0 1103 // Flush all persistent caches.
Chris@0 1104 // This is executed based on old/previously known information, which is
Chris@0 1105 // sufficient, since new extensions cannot have any primed caches yet.
Chris@0 1106 $module_handler->invokeAll('cache_flush');
Chris@0 1107 foreach (Cache::getBins() as $service_id => $cache_backend) {
Chris@0 1108 $cache_backend->deleteAll();
Chris@0 1109 }
Chris@0 1110
Chris@0 1111 // Flush asset file caches.
Chris@0 1112 \Drupal::service('asset.css.collection_optimizer')->deleteAll();
Chris@0 1113 \Drupal::service('asset.js.collection_optimizer')->deleteAll();
Chris@0 1114 _drupal_flush_css_js();
Chris@0 1115
Chris@0 1116 // Reset all static caches.
Chris@0 1117 drupal_static_reset();
Chris@0 1118
Chris@0 1119 // Invalidate the container.
Chris@0 1120 \Drupal::service('kernel')->invalidateContainer();
Chris@0 1121
Chris@0 1122 // Wipe the Twig PHP Storage cache.
Chris@17 1123 \Drupal::service('twig')->invalidate();
Chris@0 1124
Chris@0 1125 // Rebuild module and theme data.
Chris@0 1126 $module_data = system_rebuild_module_data();
Chris@0 1127 /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
Chris@0 1128 $theme_handler = \Drupal::service('theme_handler');
Chris@0 1129 $theme_handler->refreshInfo();
Chris@0 1130 // In case the active theme gets requested later in the same request we need
Chris@0 1131 // to reset the theme manager.
Chris@0 1132 \Drupal::theme()->resetActiveTheme();
Chris@0 1133
Chris@0 1134 // Rebuild and reboot a new kernel. A simple DrupalKernel reboot is not
Chris@0 1135 // sufficient, since the list of enabled modules might have been adjusted
Chris@0 1136 // above due to changed code.
Chris@0 1137 $files = [];
Chris@0 1138 foreach ($module_data as $name => $extension) {
Chris@0 1139 if ($extension->status) {
Chris@0 1140 $files[$name] = $extension;
Chris@0 1141 }
Chris@0 1142 }
Chris@0 1143 \Drupal::service('kernel')->updateModules($module_handler->getModuleList(), $files);
Chris@0 1144 // New container, new module handler.
Chris@0 1145 $module_handler = \Drupal::moduleHandler();
Chris@0 1146
Chris@0 1147 // Ensure that all modules that are currently supposed to be enabled are
Chris@0 1148 // actually loaded.
Chris@0 1149 $module_handler->loadAll();
Chris@0 1150
Chris@0 1151 // Rebuild all information based on new module data.
Chris@0 1152 $module_handler->invokeAll('rebuild');
Chris@0 1153
Chris@0 1154 // Clear all plugin caches.
Chris@0 1155 \Drupal::service('plugin.cache_clearer')->clearCachedDefinitions();
Chris@0 1156
Chris@0 1157 // Rebuild the menu router based on all rebuilt data.
Chris@0 1158 // Important: This rebuild must happen last, so the menu router is guaranteed
Chris@0 1159 // to be based on up to date information.
Chris@0 1160 \Drupal::service('router.builder')->rebuild();
Chris@0 1161
Chris@0 1162 // Re-initialize the maintenance theme, if the current request attempted to
Chris@0 1163 // use it. Unlike regular usages of this function, the installer and update
Chris@0 1164 // scripts need to flush all caches during GET requests/page building.
Chris@0 1165 if (function_exists('_drupal_maintenance_theme')) {
Chris@0 1166 \Drupal::theme()->resetActiveTheme();
Chris@0 1167 drupal_maintenance_theme();
Chris@0 1168 }
Chris@0 1169 }
Chris@0 1170
Chris@0 1171 /**
Chris@0 1172 * Changes the dummy query string added to all CSS and JavaScript files.
Chris@0 1173 *
Chris@0 1174 * Changing the dummy query string appended to CSS and JavaScript files forces
Chris@0 1175 * all browsers to reload fresh files.
Chris@0 1176 */
Chris@0 1177 function _drupal_flush_css_js() {
Chris@0 1178 // The timestamp is converted to base 36 in order to make it more compact.
Chris@0 1179 Drupal::state()->set('system.css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
Chris@0 1180 }
Chris@0 1181
Chris@0 1182 /**
Chris@0 1183 * Outputs debug information.
Chris@0 1184 *
Chris@0 1185 * The debug information is passed on to trigger_error() after being converted
Chris@0 1186 * to a string using _drupal_debug_message().
Chris@0 1187 *
Chris@0 1188 * @param $data
Chris@0 1189 * Data to be output.
Chris@0 1190 * @param $label
Chris@0 1191 * Label to prefix the data.
Chris@0 1192 * @param $print_r
Chris@0 1193 * Flag to switch between print_r() and var_export() for data conversion to
Chris@0 1194 * string. Set $print_r to FALSE to use var_export() instead of print_r().
Chris@0 1195 * Passing recursive data structures to var_export() will generate an error.
Chris@0 1196 */
Chris@0 1197 function debug($data, $label = NULL, $print_r = TRUE) {
Chris@0 1198 // Print $data contents to string.
Chris@0 1199 $string = Html::escape($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
Chris@0 1200
Chris@0 1201 // Display values with pre-formatting to increase readability.
Chris@0 1202 $string = '<pre>' . $string . '</pre>';
Chris@0 1203
Chris@0 1204 trigger_error(trim($label ? "$label: $string" : $string));
Chris@0 1205 }
Chris@0 1206
Chris@0 1207 /**
Chris@0 1208 * Checks whether a version is compatible with a given dependency.
Chris@0 1209 *
Chris@0 1210 * @param $v
Chris@0 1211 * A parsed dependency structure e.g. from ModuleHandler::parseDependency().
Chris@0 1212 * @param $current_version
Chris@0 1213 * The version to check against (like 4.2).
Chris@0 1214 *
Chris@0 1215 * @return
Chris@0 1216 * NULL if compatible, otherwise the original dependency version string that
Chris@0 1217 * caused the incompatibility.
Chris@0 1218 *
Chris@0 1219 * @see \Drupal\Core\Extension\ModuleHandler::parseDependency()
Chris@0 1220 */
Chris@0 1221 function drupal_check_incompatibility($v, $current_version) {
Chris@0 1222 if (!empty($v['versions'])) {
Chris@0 1223 foreach ($v['versions'] as $required_version) {
Chris@0 1224 if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
Chris@0 1225 return $v['original_version'];
Chris@0 1226 }
Chris@0 1227 }
Chris@0 1228 }
Chris@0 1229 }
Chris@0 1230
Chris@0 1231 /**
Chris@0 1232 * Returns a string of supported archive extensions.
Chris@0 1233 *
Chris@0 1234 * @return
Chris@0 1235 * A space-separated string of extensions suitable for use by the file
Chris@0 1236 * validation system.
Chris@0 1237 */
Chris@0 1238 function archiver_get_extensions() {
Chris@0 1239 $valid_extensions = [];
Chris@0 1240 foreach (\Drupal::service('plugin.manager.archiver')->getDefinitions() as $archive) {
Chris@0 1241 foreach ($archive['extensions'] as $extension) {
Chris@0 1242 foreach (explode('.', $extension) as $part) {
Chris@0 1243 if (!in_array($part, $valid_extensions)) {
Chris@0 1244 $valid_extensions[] = $part;
Chris@0 1245 }
Chris@0 1246 }
Chris@0 1247 }
Chris@0 1248 }
Chris@0 1249 return implode(' ', $valid_extensions);
Chris@0 1250 }
Chris@0 1251
Chris@0 1252 /**
Chris@0 1253 * Creates the appropriate archiver for the specified file.
Chris@0 1254 *
Chris@0 1255 * @param $file
Chris@0 1256 * The full path of the archive file. Note that stream wrapper paths are
Chris@0 1257 * supported, but not remote ones.
Chris@0 1258 *
Chris@0 1259 * @return
Chris@0 1260 * A newly created instance of the archiver class appropriate
Chris@0 1261 * for the specified file, already bound to that file.
Chris@0 1262 * If no appropriate archiver class was found, will return FALSE.
Chris@0 1263 */
Chris@0 1264 function archiver_get_archiver($file) {
Chris@0 1265 // Archivers can only work on local paths
Chris@14 1266 $filepath = \Drupal::service('file_system')->realpath($file);
Chris@0 1267 if (!is_file($filepath)) {
Chris@0 1268 throw new Exception(t('Archivers can only operate on local files: %file not supported', ['%file' => $file]));
Chris@0 1269 }
Chris@0 1270 return \Drupal::service('plugin.manager.archiver')->getInstance(['filepath' => $filepath]);
Chris@0 1271 }
Chris@0 1272
Chris@0 1273 /**
Chris@0 1274 * Assembles the Drupal Updater registry.
Chris@0 1275 *
Chris@0 1276 * An Updater is a class that knows how to update various parts of the Drupal
Chris@0 1277 * file system, for example to update modules that have newer releases, or to
Chris@0 1278 * install a new theme.
Chris@0 1279 *
Chris@0 1280 * @return array
Chris@0 1281 * The Drupal Updater class registry.
Chris@0 1282 *
Chris@0 1283 * @see \Drupal\Core\Updater\Updater
Chris@0 1284 * @see hook_updater_info()
Chris@0 1285 * @see hook_updater_info_alter()
Chris@0 1286 */
Chris@0 1287 function drupal_get_updaters() {
Chris@0 1288 $updaters = &drupal_static(__FUNCTION__);
Chris@0 1289 if (!isset($updaters)) {
Chris@0 1290 $updaters = \Drupal::moduleHandler()->invokeAll('updater_info');
Chris@0 1291 \Drupal::moduleHandler()->alter('updater_info', $updaters);
Chris@0 1292 uasort($updaters, [SortArray::class, 'sortByWeightElement']);
Chris@0 1293 }
Chris@0 1294 return $updaters;
Chris@0 1295 }
Chris@0 1296
Chris@0 1297 /**
Chris@0 1298 * Assembles the Drupal FileTransfer registry.
Chris@0 1299 *
Chris@0 1300 * @return
Chris@0 1301 * The Drupal FileTransfer class registry.
Chris@0 1302 *
Chris@0 1303 * @see \Drupal\Core\FileTransfer\FileTransfer
Chris@0 1304 * @see hook_filetransfer_info()
Chris@0 1305 * @see hook_filetransfer_info_alter()
Chris@0 1306 */
Chris@0 1307 function drupal_get_filetransfer_info() {
Chris@0 1308 $info = &drupal_static(__FUNCTION__);
Chris@0 1309 if (!isset($info)) {
Chris@0 1310 $info = \Drupal::moduleHandler()->invokeAll('filetransfer_info');
Chris@0 1311 \Drupal::moduleHandler()->alter('filetransfer_info', $info);
Chris@0 1312 uasort($info, [SortArray::class, 'sortByWeightElement']);
Chris@0 1313 }
Chris@0 1314 return $info;
Chris@0 1315 }