common.inc 56.5 KB
Newer Older
Dries's avatar
 
Dries committed
1 2
<?php

3 4 5 6 7 8 9 10
/**
 * @file
 * Common functions that many Drupal modules will need to reference.
 *
 * The functions that are critical and need to be available even when serving
 * a cached page are instead located in bootstrap.inc.
 */

11
use Drupal\Component\Serialization\Json;
12 13
use Drupal\Component\Serialization\Yaml;
use Drupal\Component\Serialization\Exception\InvalidDataTypeException;
14
use Drupal\Component\Utility\Bytes;
15
use Drupal\Component\Utility\Crypt;
16
use Drupal\Component\Utility\Html;
17
use Drupal\Component\Utility\Number;
18
use Drupal\Component\Utility\SortArray;
19
use Drupal\Component\Utility\SafeMarkup;
20
use Drupal\Component\Utility\Tags;
21
use Drupal\Component\Utility\UrlHelper;
22
use Drupal\Core\Asset\AttachedAssets;
23
use Drupal\Core\Cache\Cache;
24
use Drupal\Core\Language\LanguageInterface;
25
use Drupal\Core\Render\Renderer;
26
use Drupal\Core\Site\Settings;
27
use Drupal\Core\Url;
28 29
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
30
use Drupal\Core\PhpStorage\PhpStorageFactory;
31
use Drupal\Component\Utility\NestedArray;
32
use Drupal\Core\Datetime\DrupalDateTime;
33
use Drupal\Core\Routing\GeneratorNotInitializedException;
34
use Drupal\Core\Template\Attribute;
35
use Drupal\Core\Render\Element;
36
use Drupal\Core\Session\AnonymousUserSession;
37

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
/**
 * @defgroup php_wrappers PHP wrapper functions
 * @{
 * Functions that are wrappers or custom implementations of PHP functions.
 *
 * Certain PHP functions should not be used in Drupal. Instead, Drupal's
 * replacement functions should be used.
 *
 * For example, for improved or more secure UTF8-handling, or RFC-compliant
 * handling of URLs in Drupal.
 *
 * For ease of use and memorizing, all these wrapper functions use the same name
 * as the original PHP function, but prefixed with "drupal_". Beware, however,
 * that not all wrapper functions support the same arguments as the original
 * functions.
 *
 * You should always use these wrapper functions in your code.
 *
 * Wrong:
 * @code
 *   $my_substring = substr($original_string, 0, 5);
 * @endcode
 *
 * Correct:
 * @code
63
 *   $my_substring = Unicode::substr($original_string, 0, 5);
64 65
 * @endcode
 *
66
 * @}
67 68
 */

69 70 71
/**
 * Return status for saving which involved creating a new item.
 */
72
const SAVED_NEW = 1;
73 74 75 76

/**
 * Return status for saving which involved an update to an existing item.
 */
77
const SAVED_UPDATED = 2;
78 79 80 81

/**
 * Return status for saving which deleted an existing item.
 */
82
const SAVED_DELETED = 3;
83

84
/**
85
 * The default aggregation group for CSS files added to the page.
86
 */
87
const CSS_AGGREGATE_DEFAULT = 0;
88 89

/**
90
 * The default aggregation group for theme CSS files added to the page.
91
 */
92 93 94 95 96 97 98 99 100 101 102 103 104
const CSS_AGGREGATE_THEME = 100;

/**
 * The default weight for CSS rules that style HTML elements ("base" styles).
 */
const CSS_BASE = -200;

/**
 * The default weight for CSS rules that layout a page.
 */
const CSS_LAYOUT = -100;

/**
105
 * The default weight for CSS rules that style design components (and their associated states and themes.)
106 107 108 109 110 111 112 113 114
 */
const CSS_COMPONENT = 0;

/**
 * The default weight for CSS rules that style states and are not included with components.
 */
const CSS_STATE = 100;

/**
115
 * The default weight for CSS rules that style themes and are not included with components.
116
 */
117
const CSS_THEME = 200;
118

119 120 121 122 123
/**
 * The default group for JavaScript settings added to the page.
 */
const JS_SETTING = -200;

124
/**
125
 * The default group for JavaScript and jQuery libraries added to the page.
126
 */
127
const JS_LIBRARY = -100;
128 129

/**
130
 * The default group for module JavaScript code added to the page.
131
 */
132
const JS_DEFAULT = 0;
133 134

/**
135
 * The default group for theme JavaScript code added to the page.
136
 */
137
const JS_THEME = 100;
138

139 140 141 142 143 144 145 146 147
/**
 * The delimiter used to split plural strings.
 *
 * This is the ETX (End of text) character and is used as a minimal means to
 * separate singular and plural variants in source and translation text. It
 * was found to be the most compatible delimiter for the supported databases.
 */
const LOCALE_PLURAL_DELIMITER = "\03";

Dries's avatar
Dries committed
148
/**
149
 * Adds output to the HEAD tag of the HTML page.
150
 *
151
 * This function can be called as long as the headers aren't sent. Pass no
152 153 154 155 156 157 158 159 160 161 162 163
 * arguments (or NULL for both) to retrieve the currently stored elements.
 *
 * @param $data
 *   A renderable array. If the '#type' key is not set then 'html_tag' will be
 *   added as the default '#type'.
 * @param $key
 *   A unique string key to allow implementations of hook_html_head_alter() to
 *   identify the element in $data. Required if $data is not NULL.
 *
 * @return
 *   An array of all stored HEAD elements.
 *
164
 * @see \Drupal\Core\Render\Element\HtmlTag::preRenderHtmlTag()
165 166 167
 *
 * @deprecated in Drupal 8.0.x, will be removed before Drupal 8.0.0
 *   Use #attached on render arrays.
Dries's avatar
Dries committed
168
 */
169
function _drupal_add_html_head($data = NULL, $key = NULL) {
170
  $stored_head = &drupal_static(__FUNCTION__, array());
171 172 173 174 175 176

  if (isset($data) && isset($key)) {
    if (!isset($data['#type'])) {
      $data['#type'] = 'html_tag';
    }
    $stored_head[$key] = $data;
Dries's avatar
Dries committed
177 178 179 180
  }
  return $stored_head;
}

181
/**
182
 * Retrieves output to be displayed in the HEAD tag of the HTML page.
183 184 185 186 187 188
 *
 * @param bool $render
 *   If TRUE render the HEAD elements, otherwise return just the elements.
 *
 * @return string|array
 *   Return the rendered HTML head or the elements itself.
189 190 191
 *
 * @deprecated in Drupal 8.0.x, will be removed before Drupal 8.0.0
 *   Use #attached on render arrays.
192
 */
193
function drupal_get_html_head($render = TRUE) {
194
  $elements = _drupal_add_html_head();
195
  \Drupal::moduleHandler()->alter('html_head', $elements);
196 197 198 199 200 201
  if ($render) {
    return drupal_render($elements);
  }
  else {
    return $elements;
  }
Dries's avatar
Dries committed
202 203
}

204
/**
205
 * Prepares a 'destination' URL query parameter for use with url().
206
 *
207 208 209 210
 * Used to direct the user back to the referring page after completing a form.
 * By default the current URL is returned. If a destination exists in the
 * previous request, that destination is returned. As such, a destination can
 * persist across multiple pages.
211
 *
212
 * @return array
213
 *   An associative array containing the key:
214 215 216 217 218
 *   - destination: The value of the current request's 'destination' query
 *     parameter, if present. This can be either a relative or absolute URL.
 *     However, for security, redirection to external URLs is not performed.
 *     If the query parameter isn't present, then the URL of the current
 *     request is returned.
219
 *
220
 * @see \Drupal\Core\EventSubscriber\RedirectResponseSubscriber::checkRedirectUrl()
221
 *
222
 * @ingroup form_api
223 224 225
 *
 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
 *   Use the redirect.destination service.
226 227
 */
function drupal_get_destination() {
228
  return \Drupal::destination()->getAsArray();
229 230
}

Kjartan's avatar
Kjartan committed
231
/**
Dries's avatar
 
Dries committed
232
 * @defgroup validation Input validation
Dries's avatar
 
Dries committed
233
 * @{
Dries's avatar
 
Dries committed
234
 * Functions to validate user input.
Kjartan's avatar
Kjartan committed
235 236
 */

237
/**
238
 * Verifies the syntax of the given email address.
Dries's avatar
 
Dries committed
239
 *
240
 * @param string $mail
241
 *   A string containing an email address.
242
 *
243
 * @return bool
Dries's avatar
 
Dries committed
244
 *   TRUE if the address is in a valid format.
245 246 247
 *
 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
 *   Use \Drupal::service('email.validator')->isValid().
248
 */
Dries's avatar
 
Dries committed
249
function valid_email_address($mail) {
250
  return \Drupal::service('email.validator')->isValid($mail);
251 252
}

253 254 255 256
/**
 * @} End of "defgroup validation".
 */

257 258 259 260
/**
 * @defgroup sanitization Sanitization functions
 * @{
 * Functions to sanitize values.
261 262 263
 *
 * See http://drupal.org/writing-secure-code for information
 * on writing secure code.
264 265
 */

266
/**
267
 * Strips dangerous protocols from a URI and encodes it for output to HTML.
268 269 270 271 272 273 274
 *
 * @param $uri
 *   A plain-text URI that might contain dangerous protocols.
 *
 * @return
 *   A URI stripped of dangerous protocols and encoded for output to an HTML
 *   attribute value. Because it is already encoded, it should not be set as a
275 276 277
 *   value within a $attributes array passed to Drupal\Core\Template\Attribute,
 *   because Drupal\Core\Template\Attribute expects those values to be
 *   plain-text strings. To pass a filtered URI to
278
 *   Drupal\Core\Template\Attribute, call
279
 *   \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() instead.
280
 *
281
 * @see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols()
282
 * @see \Drupal\Component\Utility\SafeMarkup::checkPlain()
Dries's avatar
Dries committed
283 284
 */
function check_url($uri) {
285
  return SafeMarkup::checkPlain(UrlHelper::stripDangerousProtocols($uri));
Dries's avatar
Dries committed
286 287
}

288 289 290 291
/**
 * @} End of "defgroup sanitization".
 */

Dries's avatar
 
Dries committed
292
/**
Dries's avatar
 
Dries committed
293
 * @defgroup format Formatting
Dries's avatar
 
Dries committed
294
 * @{
Dries's avatar
 
Dries committed
295
 * Functions to format numbers, strings, dates, etc.
Dries's avatar
 
Dries committed
296 297
 */

298
/**
299
 * Formats XML elements.
300
 *
301 302 303
 * Note: It is the caller's responsibility to sanitize any input parameters.
 * This function does not perform sanitization.
 *
304
 * @param $array
305
 *   An array where each item represents an element and is either a:
306 307
 *   - (key => value) pair (<key>value</key>)
 *   - Associative array with fields:
308 309
 *     - 'key': The element name. Element names are not sanitized, so do not
 *       pass user input.
310 311 312 313 314 315 316
 *     - 'value': element contents
 *     - 'attributes': associative array of element attributes
 *
 * In both cases, 'value' can be a simple string, or it can be another array
 * with the same format as $array itself for nesting.
 */
function format_xml_elements($array) {
317
  $output = '';
318 319
  foreach ($array as $key => $value) {
    if (is_numeric($key)) {
Dries's avatar
 
Dries committed
320
      if ($value['key']) {
321
        $output .= ' <' . $value['key'];
322
        if (isset($value['attributes']) && is_array($value['attributes'])) {
323
          $output .= new Attribute($value['attributes']);
Dries's avatar
 
Dries committed
324 325
        }

326
        if (isset($value['value']) && $value['value'] != '') {
327
          $output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : SafeMarkup::checkPlain($value['value'])) . '</' . $value['key'] . ">\n";
Dries's avatar
 
Dries committed
328 329 330 331 332 333 334
        }
        else {
          $output .= " />\n";
        }
      }
    }
    else {
335
      $output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : SafeMarkup::checkPlain($value)) . "</$key>\n";
Dries's avatar
 
Dries committed
336
    }
Dries's avatar
 
Dries committed
337
  }
338 339 340 341 342
  // @todo This is marking the output string as safe HTML, but we have only
  //   sanitized the attributes and tag values, not the tag names, and we
  //   cannot guarantee the assembled markup is safe. Consider a fix in:
  //   https://www.drupal.org/node/2296885
  return SafeMarkup::set($output);
Dries's avatar
 
Dries committed
343 344
}

Dries's avatar
 
Dries committed
345
/**
346
 * Generates a string representation for the given byte count.
Dries's avatar
 
Dries committed
347
 *
Dries's avatar
 
Dries committed
348
 * @param $size
349
 *   A size in bytes.
350
 * @param $langcode
351 352
 *   Optional language code to translate to a language other than what is used
 *   to display the page.
353
 *
Dries's avatar
 
Dries committed
354 355
 * @return
 *   A translated string representation of the size.
Dries's avatar
 
Dries committed
356
 */
357
function format_size($size, $langcode = NULL) {
358
  if ($size < Bytes::KILOBYTE) {
359
    return \Drupal::translation()->formatPlural($size, '1 byte', '@count bytes', array(), array('langcode' => $langcode));
Dries's avatar
 
Dries committed
360
  }
361
  else {
362
    $size = $size / Bytes::KILOBYTE; // Convert bytes to kilobytes.
363
    $units = array(
364 365 366 367 368 369 370 371
      t('@size KB', array(), array('langcode' => $langcode)),
      t('@size MB', array(), array('langcode' => $langcode)),
      t('@size GB', array(), array('langcode' => $langcode)),
      t('@size TB', array(), array('langcode' => $langcode)),
      t('@size PB', array(), array('langcode' => $langcode)),
      t('@size EB', array(), array('langcode' => $langcode)),
      t('@size ZB', array(), array('langcode' => $langcode)),
      t('@size YB', array(), array('langcode' => $langcode)),
372 373
    );
    foreach ($units as $unit) {
374 375
      if (round($size, 2) >= Bytes::KILOBYTE) {
        $size = $size / Bytes::KILOBYTE;
376 377 378 379
      }
      else {
        break;
      }
380
    }
381
    return str_replace('@size', round($size, 2), $unit);
Dries's avatar
 
Dries committed
382 383 384
  }
}

Dries's avatar
 
Dries committed
385
/**
386
 * Formats a date, using a date type or a custom date format string.
Dries's avatar
 
Dries committed
387
 *
Dries's avatar
 
Dries committed
388
 * @param $timestamp
389
 *   A UNIX timestamp to format.
Dries's avatar
 
Dries committed
390
 * @param $type
391
 *   (optional) The format to use, one of:
392 393 394
 *   - One of the built-in formats: 'short', 'medium',
 *     'long', 'html_datetime', 'html_date', 'html_time',
 *     'html_yearless_date', 'html_week', 'html_month', 'html_year'.
395
 *   - The name of a date type defined by a date format config entity.
396 397 398
 *   - The machine name of an administrator-defined date format.
 *   - 'custom', to use $format.
 *   Defaults to 'medium'.
Dries's avatar
 
Dries committed
399
 * @param $format
400 401 402
 *   (optional) If $type is 'custom', a PHP date format string suitable for
 *   input to date(). Use a backslash to escape ordinary text, so it does not
 *   get interpreted as date format characters.
Dries's avatar
 
Dries committed
403
 * @param $timezone
404
 *   (optional) Time zone identifier, as described at
405
 *   http://php.net/manual/timezones.php Defaults to the time zone used to
406
 *   display the page.
407
 * @param $langcode
408 409 410
 *   (optional) Language code to translate to. Defaults to the language used to
 *   display the page.
 *
Dries's avatar
 
Dries committed
411 412
 * @return
 *   A translated date string in the requested format.
413
 *
414
 * @see \Drupal\Core\Datetime\DateFormatter::format()
Dries's avatar
 
Dries committed
415
 */
416
function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
417
  return \Drupal::service('date.formatter')->format($timestamp, $type, $format, $timezone, $langcode);
418 419
}

420 421 422 423 424
/**
 * Returns an ISO8601 formatted date based on the given date.
 *
 * @param $date
 *   A UNIX timestamp.
425
 *
426 427 428 429 430 431 432 433 434
 * @return string
 *   An ISO8601 formatted date.
 */
function date_iso8601($date) {
  // The DATE_ISO8601 constant cannot be used here because it does not match
  // date('c') and produces invalid RDF markup.
  return date('c', $date);
}

435
/**
436 437 438
 * Translates a formatted date string.
 *
 * Callback for preg_replace_callback() within format_date().
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
 */
function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
  // We cache translations to avoid redundant and rather costly calls to t().
  static $cache, $langcode;

  if (!isset($matches)) {
    $langcode = $new_langcode;
    return;
  }

  $code = $matches[1];
  $string = $matches[2];

  if (!isset($cache[$langcode][$code][$string])) {
    $options = array(
      'langcode' => $langcode,
    );

    if ($code == 'F') {
      $options['context'] = 'Long month name';
Dries's avatar
 
Dries committed
459
    }
460 461 462

    if ($code == '') {
      $cache[$langcode][$code][$string] = $string;
463
    }
Dries's avatar
 
Dries committed
464
    else {
465
      $cache[$langcode][$code][$string] = t($string, array(), $options);
Dries's avatar
 
Dries committed
466
    }
Dries's avatar
 
Dries committed
467
  }
468
  return $cache[$langcode][$code][$string];
Dries's avatar
 
Dries committed
469 470
}

Dries's avatar
 
Dries committed
471 472 473
/**
 * @} End of "defgroup format".
 */
Dries's avatar
 
Dries committed
474

475
/**
476
 * Formats an attribute string for an HTTP header.
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
 *
 * @param $attributes
 *   An associative array of attributes such as 'rel'.
 *
 * @return
 *   A ; separated string ready for insertion in a HTTP header. No escaping is
 *   performed for HTML entities, so this string is not safe to be printed.
 */
function drupal_http_header_attributes(array $attributes = array()) {
  foreach ($attributes as $attribute => &$data) {
    if (is_array($data)) {
      $data = implode(' ', $data);
    }
    $data = $attribute . '="' . $data . '"';
  }
  return $attributes ? ' ' . implode('; ', $attributes) : '';
}

495 496 497 498 499 500 501 502
/**
 * Attempts to set the PHP maximum execution time.
 *
 * This function is a wrapper around the PHP function set_time_limit().
 * When called, set_time_limit() restarts the timeout counter from zero.
 * In other words, if the timeout is the default 30 seconds, and 25 seconds
 * into script execution a call such as set_time_limit(20) is made, the
 * script will run for a total of 45 seconds before timing out.
503
 *
504 505 506 507 508
 * If the current time limit is not unlimited it is possible to decrease the
 * total time limit if the sum of the new time limit and the current time spent
 * running the script is inferior to the original time limit. It is inherent to
 * the way set_time_limit() works, it should rather be called with an
 * appropriate value every time you need to allocate a certain amount of time
509
 * to execute a task than only once at the beginning of the script.
510
 *
511 512 513 514 515 516 517 518 519
 * Before calling set_time_limit(), we check if this function is available
 * because it could be disabled by the server administrator. We also hide all
 * the errors that could occur when calling set_time_limit(), because it is
 * not possible to reliably ensure that PHP or a security extension will
 * not issue a warning/error if they prevent the use of this function.
 *
 * @param $time_limit
 *   An integer specifying the new time limit, in seconds. A value of 0
 *   indicates unlimited execution time.
520 521
 *
 * @ingroup php_wrappers
522 523 524
 */
function drupal_set_time_limit($time_limit) {
  if (function_exists('set_time_limit')) {
525 526
    $current = ini_get('max_execution_time');
    // Do not set time limit if it is currently unlimited.
527
    if ($current != 0) {
528 529
      @set_time_limit($time_limit);
    }
530 531 532
  }
}

533
/**
534
 * Returns the base URL path (i.e., directory) of the Drupal installation.
535
 *
536 537
 * base_path() adds a "/" to the beginning and end of the returned path if the
 * path is not empty. At the very least, this will return "/".
538
 *
539 540 541
 * Examples:
 * - http://example.com returns "/" because the path is empty.
 * - http://example.com/drupal/folder returns "/drupal/folder/".
542 543
 */
function base_path() {
544
  return $GLOBALS['base_path'];
545 546
}

547
/**
548
 * Adds a LINK tag with a distinct 'rel' attribute to the page's HEAD.
549
 *
550
 * This function can be called as long the HTML header hasn't been sent, which
551
 * on normal pages is up through the preprocess step of _theme('html'). Adding
552 553
 * a link will overwrite a prior link with the exact same 'rel' and 'href'
 * attributes.
554
 *
555 556 557 558
 * @param $attributes
 *   Associative array of element attributes including 'href' and 'rel'.
 * @param $header
 *   Optional flag to determine if a HTTP 'Link:' header should be sent.
559 560 561
 *
 * @deprecated in Drupal 8.0.x, will be removed before Drupal 8.0.0
 *   Use #attached on render arrays.
562
 */
563
function _drupal_add_html_head_link($attributes, $header = FALSE) {
564 565 566 567 568 569 570 571
  $element = array(
    '#tag' => 'link',
    '#attributes' => $attributes,
  );
  $href = $attributes['href'];

  if ($header) {
    // Also add a HTTP header "Link:".
572
    $href = '<' . SafeMarkup::checkPlain($attributes['href']) . '>;';
573
    unset($attributes['href']);
574
    $element['#attached']['http_header'][] = array('Link',  $href . drupal_http_header_attributes($attributes), TRUE);
575 576
  }

577
  _drupal_add_html_head($element, 'html_head_link:' . $attributes['rel'] . ':' . $href);
578 579
}

580
/**
581
 * Deletes old cached CSS files.
582
 *
583 584
 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
 *   Use \Drupal\Core\Asset\AssetCollectionOptimizerInterface::deleteAll().
585
 */
586 587
function drupal_clear_css_cache() {
  \Drupal::service('asset.css.collection_optimizer')->deleteAll();
588 589
}

Steven Wittens's avatar
Steven Wittens committed
590
/**
591
 * Constructs an array of the defaults that are used for JavaScript assets.
592 593
 *
 * @param $data
594
 *   (optional) The default data parameter for the JavaScript asset array.
595
 *
596
 * @see hook_js_alter()
597 598 599 600
 */
function drupal_js_defaults($data = NULL) {
  return array(
    'type' => 'file',
601 602 603
    'group' => JS_DEFAULT,
    'every_page' => FALSE,
    'weight' => 0,
604 605
    'scope' => 'header',
    'cache' => TRUE,
606
    'preprocess' => TRUE,
607
    'attributes' => array(),
608
    'version' => NULL,
609
    'data' => $data,
610
    'browsers' => array(),
611 612 613
  );
}

614
/**
615
 * Merges two #attached arrays.
616
 *
617
 * The values under the 'drupalSettings' key are merged in a special way, to
618
 * match the behavior of:
619 620 621 622 623
 *
 * @code
 *   jQuery.extend(true, {}, $settings_items[0], $settings_items[1], ...)
 * @endcode
 *
624
 * This means integer indices are preserved just like string indices are,
625 626 627 628
 * rather than re-indexed as is common in PHP array merging.
 *
 * Example:
 * @code
629
 * function module1_page_attachments(&$page) {
630
 *   $page['a']['#attached']['drupalSettings']['foo'] = ['a', 'b', 'c'];
631
 * }
632
 * function module2_page_attachments(&$page) {
633
 *   $page['#attached']['drupalSettings']['foo'] = ['d'];
634 635 636 637 638 639 640 641
 * }
 * // When the page is rendered after the above code, and the browser runs the
 * // resulting <SCRIPT> tags, the value of drupalSettings.foo is
 * // ['d', 'b', 'c'], not ['a', 'b', 'c', 'd'].
 * @endcode
 *
 * By following jQuery.extend() merge logic rather than common PHP array merge
 * logic, the following are ensured:
642 643
 * - Attaching JavaScript settings is idempotent: attaching the same settings
 *   twice does not change the output sent to the browser.
644 645 646 647
 * - If pieces of the page are rendered in separate PHP requests and the
 *   returned settings are merged by JavaScript, the resulting settings are the
 *   same as if rendered in one PHP request and merged by PHP.
 *
648 649 650 651 652 653 654
 * @param array $a
 *   An #attached array.
 * @param array $b
 *   Another #attached array.
 *
 * @return array
 *   The merged #attached array.
655 656 657
 *
 * @deprecated To be removed in Drupal 8.0.x. Use
 *   \Drupal\Core\Render\Renderer::mergeAttachments() instead.
658 659
 */
function drupal_merge_attached(array $a, array $b) {
660
  return \Drupal::service('renderer')->mergeAttachments($a, $b);
661 662
}

663
/**
664
 * Processes non-asset attachments in a render() structure.
665
 *
666 667 668 669
 * Libraries, JavaScript settings, feeds, HTML <head> tags and HTML <head> links
 * are attached to elements using the #attached property. The #attached property
 * is an associative array, where the keys are the attachment types and the
 * values are the attached data. For example:
670
 *
671
 * @code
672 673 674
 * $build['#attached'] = [
 *   'library' => ['core/jquery']
 * ];
675 676 677
 * $build['#attached']['http_header'] = [
 *   ['Content-Type', 'application/rss+xml; charset=utf-8'],
 * ];
678 679
 * @endcode
 *
680 681 682 683 684 685 686 687
 * The available keys are:
 * - 'library' (asset libraries)
 * - 'drupalSettings' (JavaScript settings)
 * - 'feed' (RSS feeds)
 * - 'html_head' (tags in HTML <head>)
 * - 'html_head_link' (<link> tags in HTML <head>)
 * - 'http_header' (HTTP headers)
 *
688 689
 * This function processes all non-asset attachments, to apply them to the
 * current response (that means all keys except 'library' and 'drupalSettings').
690
 *
691
 * @param array $elements
692
 *   The structured array describing the data being rendered.
693
 *
694
 * @see drupal_render()
695 696 697 698
 * @see \Drupal\Core\Asset\AssetResolver
 *
 * @throws LogicException
 *   When attaching something of a non-existing attachment type.
699
 */
700 701 702 703
function drupal_process_attached(array $elements) {
  // Asset attachments are handled by \Drupal\Core\Asset\AssetResolver.
  foreach (array('library', 'drupalSettings') as $type) {
    unset($elements['#attached'][$type]);
704 705
  }

706 707
  // Add additional types of attachments specified in the render() structure.
  foreach ($elements['#attached'] as $callback => $options) {
708
    foreach ($elements['#attached'][$callback] as $args) {
709 710 711 712 713 714
      // Limit the amount allowed entries.
      switch ($callback) {
        case 'html_head':
          call_user_func_array('_drupal_add_html_head', $args);
          break;
        case 'feed':
715 716 717 718 719 720 721
          $args = [[
            'href' => $args[0],
            'rel' => 'alternate',
            'title' => $args[1],
            'type' => 'application/rss+xml',
          ]];
          call_user_func_array('_drupal_add_html_head_link', $args);
722 723 724 725 726 727 728 729 730 731
          break;
        case 'html_head_link':
          call_user_func_array('_drupal_add_html_head_link', $args);
          break;
        case 'http_header':
          call_user_func_array('_drupal_add_http_header', $args);
          break;
        default:
          throw new \LogicException(sprintf('You are not allowed to use %s in #attached', $callback));
      }
732
    }
733 734 735
  }
}

736
/**
737
 * Adds JavaScript to change the state of an element based on another element.
738
 *
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
 * A "state" means a certain property on a DOM element, such as "visible" or
 * "checked". A state can be applied to an element, depending on the state of
 * another element on the page. In general, states depend on HTML attributes and
 * DOM element properties, which change due to user interaction.
 *
 * Since states are driven by JavaScript only, it is important to understand
 * that all states are applied on presentation only, none of the states force
 * any server-side logic, and that they will not be applied for site visitors
 * without JavaScript support. All modules implementing states have to make
 * sure that the intended logic also works without JavaScript being enabled.
 *
 * #states is an associative array in the form of:
 * @code
 * array(
 *   STATE1 => CONDITIONS_ARRAY1,
 *   STATE2 => CONDITIONS_ARRAY2,
 *   ...
 * )
 * @endcode
 * Each key is the name of a state to apply to the element, such as 'visible'.
 * Each value is a list of conditions that denote when the state should be
 * applied.
 *
 * Multiple different states may be specified to act on complex conditions:
 * @code
 * array(
 *   'visible' => CONDITIONS,
 *   'checked' => OTHER_CONDITIONS,
 * )
 * @endcode
 *
 * Every condition is a key/value pair, whose key is a jQuery selector that
 * denotes another element on the page, and whose value is an array of
 * conditions, which must bet met on that element:
 * @code
 * array(
 *   'visible' => array(
 *     JQUERY_SELECTOR => REMOTE_CONDITIONS,
 *     JQUERY_SELECTOR => REMOTE_CONDITIONS,
 *     ...
 *   ),
 * )
 * @endcode
 * All conditions must be met for the state to be applied.
 *
 * Each remote condition is a key/value pair specifying conditions on the other
 * element that need to be met to apply the state to the element:
 * @code
 * array(
 *   'visible' => array(
 *     ':input[name="remote_checkbox"]' => array('checked' => TRUE),
 *   ),
 * )
 * @endcode
 *
 * For example, to show a textfield only when a checkbox is checked:
 * @code
 * $form['toggle_me'] = array(
 *   '#type' => 'checkbox',
 *   '#title' => t('Tick this box to type'),
 * );
 * $form['settings'] = array(
 *   '#type' => 'textfield',
 *   '#states' => array(
 *     // Only show this field when the 'toggle_me' checkbox is enabled.
 *     'visible' => array(
 *       ':input[name="toggle_me"]' => array('checked' => TRUE),
806
 *     ),
807 808 809 810 811 812 813
 *   ),
 * );
 * @endcode
 *
 * The following states may be applied to an element:
 * - enabled
 * - disabled
814 815
 * - required
 * - optional
816 817 818 819 820 821 822 823
 * - visible
 * - invisible
 * - checked
 * - unchecked
 * - expanded
 * - collapsed
 *
 * The following states may be used in remote conditions:
824 825
 * - empty
 * - filled
826 827
 * - checked
 * - unchecked
828 829
 * - expanded
 * - collapsed
830 831
 * - value
 *
832 833
 * The following states exist for both elements and remote conditions, but are
 * not fully implemented and may not change anything on the element:
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
 * - relevant
 * - irrelevant
 * - valid
 * - invalid
 * - touched
 * - untouched
 * - readwrite
 * - readonly
 *
 * When referencing select lists and radio buttons in remote conditions, a
 * 'value' condition must be used:
 * @code
 *   '#states' => array(
 *     // Show the settings if 'bar' has been selected for 'foo'.
 *     'visible' => array(
 *       ':input[name="foo"]' => array('value' => 'bar'),
 *     ),
 *   ),
 * @endcode
 *
 * @param $elements
 *   A renderable array element having a #states property as described above.
 *
 * @see form_example_states_form()
858 859
 */
function drupal_process_states(&$elements) {
860
  $elements['#attached']['library'][] = 'core/drupal.states';
861 862 863 864 865 866
  // Elements of '#type' => 'item' are not actual form input elements, but we
  // still want to be able to show/hide them. Since there's no actual HTML input
  // element available, setting #attributes does not make sense, but a wrapper
  // is available, so setting #wrapper_attributes makes it work.
  $key = ($elements['#type'] == 'item') ? '#wrapper_attributes' : '#attributes';
  $elements[$key]['data-drupal-states'] = JSON::encode($elements['#states']);
867 868
}

869
/**
870
 * Assists in attaching the tableDrag JavaScript behavior to a themed table.
871 872 873 874 875
 *
 * Draggable tables should be used wherever an outline or list of sortable items
 * needs to be arranged by an end-user. Draggable tables are very flexible and
 * can manipulate the value of form elements placed within individual columns.
 *
876 877
 * To set up a table to use drag and drop in place of weight select-lists or in
 * place of a form that contains parent relationships, the form must be themed
878 879
 * into a table. The table must have an ID attribute set and it
 * may be set as follows:
880
 * @code
881 882 883 884 885 886 887 888 889
 * $table = array(
 *   '#type' => 'table',
 *   '#header' => $header,
 *   '#rows' => $rows,
 *   '#attributes' => array(
 *     'id' => 'my-module-table',
 *   ),
 * );
 * return drupal_render($table);
890 891 892 893 894 895 896 897
 * @endcode
 *
 * In the theme function for the form, a special class must be added to each
 * form element within the same column, "grouping" them together.
 *
 * In a situation where a single weight column is being sorted in the table, the
 * classes could be added like this (in the theme function):
 * @code
898
 * $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
899 900
 * @endcode
 *
901 902
 * Each row of the table must also have a class of "draggable" in order to
 * enable the drag handles:
903 904 905 906
 * @code
 * $row = array(...);
 * $rows[] = array(
 *   'data' => $row,
907
 *   'class' => array('draggable'),
908 909
 * );
 * @endcode
Dries's avatar
Dries committed
910
 *
911 912 913 914 915
 * When tree relationships are present, the two additional classes
 * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
 * - Rows with the 'tabledrag-leaf' class cannot have child rows.
 * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
 *
916
 * Calling drupal_attach_tabledrag() would then be written as such:
917
 * @code
918 919 920 921 922
 * drupal_attach_tabledrag('my-module-table', array(
 *   'action' => 'order',
 *   'relationship' => 'sibling',
 *   'group' => 'my-elements-weight',
 * );
923 924 925
 * @endcode
 *
 * In a more complex case where there are several groups in one column (such as
926 927
 * the block regions on the admin/structure/block page), a separate subgroup
 * class must also be added to differentiate the groups.
928
 * @code
929
 * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
930 931
 * @endcode
 *
932 933 934 935
 * The 'group' option is still 'my-element-weight', and the additional
 * 'subgroup' option will be passed in as 'my-elements-weight-' . $region. This
 * also means that you'll need to call drupal_attach_tabledrag() once for every
 * region added.
936 937 938
 *
 * @code
 * foreach ($regions as $region) {
939 940 941 942