common.inc 43.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\Gettext\PoItem;
12
use Drupal\Component\Utility\Bytes;
13
use Drupal\Component\Utility\Environment;
14
use Drupal\Component\Utility\Html;
15
use Drupal\Component\Utility\SortArray;
16
use Drupal\Component\Utility\UrlHelper;
17
use Drupal\Core\Cache\Cache;
18
use Drupal\Core\Form\FormHelper;
19
use Drupal\Core\Render\Element;
20
use Drupal\Core\Render\Element\Link;
21
use Drupal\Core\Render\HtmlResponseAttachmentsProcessor;
22 23
use Drupal\Core\Render\Markup;
use Drupal\Core\StringTranslation\TranslatableMarkup;
24

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
/**
 * @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
50
 *   $my_substring = mb_substr($original_string, 0, 5);
51 52
 * @endcode
 *
53
 * @}
54 55
 */

56 57 58
/**
 * Return status for saving which involved creating a new item.
 */
59
const SAVED_NEW = 1;
60 61 62 63

/**
 * Return status for saving which involved an update to an existing item.
 */
64
const SAVED_UPDATED = 2;
65 66 67 68

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

71
/**
72
 * The default aggregation group for CSS files added to the page.
73
 */
74
const CSS_AGGREGATE_DEFAULT = 0;
75 76

/**
77
 * The default aggregation group for theme CSS files added to the page.
78
 */
79 80 81 82 83 84 85 86 87 88 89 90 91
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;

/**
92
 * The default weight for CSS rules that style design components (and their associated states and themes.)
93 94 95 96 97 98 99 100 101
 */
const CSS_COMPONENT = 0;

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

/**
102
 * The default weight for CSS rules that style themes and are not included with components.
103
 */
104
const CSS_THEME = 200;
105

106 107 108 109 110
/**
 * The default group for JavaScript settings added to the page.
 */
const JS_SETTING = -200;

111
/**
112
 * The default group for JavaScript and jQuery libraries added to the page.
113
 */
114
const JS_LIBRARY = -100;
115 116

/**
117
 * The default group for module JavaScript code added to the page.
118
 */
119
const JS_DEFAULT = 0;
120 121

/**
122
 * The default group for theme JavaScript code added to the page.
123
 */
124
const JS_THEME = 100;
125

126 127 128
/**
 * The delimiter used to split plural strings.
 *
129
 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
130
 *   Use Drupal\Component\Gettext\PoItem::DELIMITER instead.
131
 */
132
const LOCALE_PLURAL_DELIMITER = PoItem::DELIMITER;
133

134
/**
135
 * Prepares a 'destination' URL query parameter.
136
 *
137 138 139 140
 * 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.
141
 *
142
 * @return array
143
 *   An associative array containing the key:
144 145 146 147 148
 *   - 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.
149
 *
150
 * @ingroup form_api
151 152 153
 *
 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
 *   Use the redirect.destination service.
154 155 156
 *
 * @see \Drupal\Core\EventSubscriber\RedirectResponseSubscriber::checkRedirectUrl()
 * @see https://www.drupal.org/node/2448603
157 158
 */
function drupal_get_destination() {
159
  return \Drupal::destination()->getAsArray();
160 161
}

Kjartan's avatar
Kjartan committed
162
/**
Dries's avatar
 
Dries committed
163
 * @defgroup validation Input validation
Dries's avatar
 
Dries committed
164
 * @{
Dries's avatar
 
Dries committed
165
 * Functions to validate user input.
Kjartan's avatar
Kjartan committed
166 167
 */

168
/**
169
 * Verifies the syntax of the given email address.
Dries's avatar
 
Dries committed
170
 *
171
 * @param string $mail
172
 *   A string containing an email address.
173
 *
174
 * @return bool
Dries's avatar
 
Dries committed
175
 *   TRUE if the address is in a valid format.
176 177 178
 *
 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
 *   Use \Drupal::service('email.validator')->isValid().
179 180
 *
 * @see https://www.drupal.org/node/2912661
181
 */
Dries's avatar
 
Dries committed
182
function valid_email_address($mail) {
183
  return \Drupal::service('email.validator')->isValid($mail);
184 185
}

186 187 188 189
/**
 * @} End of "defgroup validation".
 */

190 191 192 193
/**
 * @defgroup sanitization Sanitization functions
 * @{
 * Functions to sanitize values.
194
 *
195
 * See https://www.drupal.org/writing-secure-code for information
196
 * on writing secure code.
197 198
 */

199
/**
200
 * Strips dangerous protocols from a URI and encodes it for output to HTML.
201 202 203 204
 *
 * @param $uri
 *   A plain-text URI that might contain dangerous protocols.
 *
205
 * @return string
206 207
 *   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
208 209 210
 *   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
211
 *   Drupal\Core\Template\Attribute, call
212
 *   \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() instead.
213
 *
214
 * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
215 216
 *   Use UrlHelper::stripDangerousProtocols() or UrlHelper::filterBadProtocol()
 *   instead. UrlHelper::stripDangerousProtocols() can be used in conjunction
217
 *   with \Drupal\Component\Render\FormattableMarkup and an @variable
218 219 220 221
 *   placeholder which will perform the necessary escaping.
 *   UrlHelper::filterBadProtocol() is functionality equivalent to check_url()
 *   apart from the fact it is protected from double escaping bugs. Note that
 *   this method no longer marks its output as safe.
222 223 224 225
 *
 * @see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols()
 * @see \Drupal\Component\Utility\UrlHelper::filterBadProtocol()
 * @see https://www.drupal.org/node/2560027
Dries's avatar
Dries committed
226 227
 */
function check_url($uri) {
228
  @trigger_error(__FUNCTION__ . '() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use UrlHelper::stripDangerousProtocols() or UrlHelper::filterBadProtocol() instead. See https://www.drupal.org/node/2560027', E_USER_DEPRECATED);
229
  return Html::escape(UrlHelper::stripDangerousProtocols($uri));
Dries's avatar
Dries committed
230 231
}

232 233 234 235
/**
 * @} End of "defgroup sanitization".
 */

Dries's avatar
 
Dries committed
236
/**
Dries's avatar
 
Dries committed
237
 * @defgroup format Formatting
Dries's avatar
 
Dries committed
238
 * @{
Dries's avatar
 
Dries committed
239
 * Functions to format numbers, strings, dates, etc.
Dries's avatar
 
Dries committed
240 241 242
 */

/**
243
 * Generates a string representation for the given byte count.
Dries's avatar
 
Dries committed
244
 *
Dries's avatar
 
Dries committed
245
 * @param $size
246
 *   A size in bytes.
247
 * @param $langcode
248 249
 *   Optional language code to translate to a language other than what is used
 *   to display the page.
250
 *
251
 * @return \Drupal\Core\StringTranslation\TranslatableMarkup
Dries's avatar
 
Dries committed
252
 *   A translated string representation of the size.
Dries's avatar
 
Dries committed
253
 */
254
function format_size($size, $langcode = NULL) {
255 256
  $absolute_size = abs($size);
  if ($absolute_size < Bytes::KILOBYTE) {
257
    return \Drupal::translation()->formatPlural($size, '1 byte', '@count bytes', [], ['langcode' => $langcode]);
Dries's avatar
 
Dries committed
258
  }
259 260 261 262 263 264 265
  // Create a multiplier to preserve the sign of $size.
  $sign = $absolute_size / $size;
  foreach (['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] as $unit) {
    $absolute_size /= Bytes::KILOBYTE;
    $rounded_size = round($absolute_size, 2);
    if ($rounded_size < Bytes::KILOBYTE) {
      break;
266
    }
Dries's avatar
 
Dries committed
267
  }
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
  $args = ['@size' => $rounded_size * $sign];
  $options = ['langcode' => $langcode];
  switch ($unit) {
    case 'KB':
      return new TranslatableMarkup('@size KB', $args, $options);

    case 'MB':
      return new TranslatableMarkup('@size MB', $args, $options);

    case 'GB':
      return new TranslatableMarkup('@size GB', $args, $options);

    case 'TB':
      return new TranslatableMarkup('@size TB', $args, $options);

    case 'PB':
      return new TranslatableMarkup('@size PB', $args, $options);

    case 'EB':
      return new TranslatableMarkup('@size EB', $args, $options);

    case 'ZB':
      return new TranslatableMarkup('@size ZB', $args, $options);

    case 'YB':
      return new TranslatableMarkup('@size YB', $args, $options);
  }
Dries's avatar
 
Dries committed
295 296
}

Dries's avatar
 
Dries committed
297
/**
298
 * Formats a date, using a date type or a custom date format string.
Dries's avatar
 
Dries committed
299
 *
Dries's avatar
 
Dries committed
300
 * @param $timestamp
301
 *   A UNIX timestamp to format.
Dries's avatar
 
Dries committed
302
 * @param $type
303
 *   (optional) The format to use, one of:
304 305 306
 *   - One of the built-in formats: 'short', 'medium',
 *     'long', 'html_datetime', 'html_date', 'html_time',
 *     'html_yearless_date', 'html_week', 'html_month', 'html_year'.
307
 *   - The name of a date type defined by a date format config entity.
308 309 310
 *   - The machine name of an administrator-defined date format.
 *   - 'custom', to use $format.
 *   Defaults to 'medium'.
Dries's avatar
 
Dries committed
311
 * @param $format
312 313 314
 *   (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
315
 * @param $timezone
316
 *   (optional) Time zone identifier, as described at
317
 *   http://php.net/manual/timezones.php Defaults to the time zone used to
318
 *   display the page.
319
 * @param $langcode
320 321 322
 *   (optional) Language code to translate to. Defaults to the language used to
 *   display the page.
 *
Dries's avatar
 
Dries committed
323 324
 * @return
 *   A translated date string in the requested format.
325
 *
326 327
 * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
 *   Use \Drupal::service('date.formatter')->format().
328 329 330
 *
 * @see \Drupal\Core\Datetime\DateFormatter::format()
 * @see https://www.drupal.org/node/1876852
Dries's avatar
 
Dries committed
331
 */
332
function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
333
  @trigger_error("format_date() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal::service('date.formatter')->format() instead. See https://www.drupal.org/node/1876852", E_USER_DEPRECATED);
334
  return \Drupal::service('date.formatter')->format($timestamp, $type, $format, $timezone, $langcode);
335 336
}

337 338 339
/**
 * Returns an ISO8601 formatted date based on the given date.
 *
340
 * @param string $date
341
 *   A UNIX timestamp.
342
 *
343 344
 * @return string
 *   An ISO8601 formatted date.
345 346 347 348 349
 *
 * @deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use
 *   date('c', $date) instead.
 *
 * @see https://www.drupal.org/node/2999991
350 351
 */
function date_iso8601($date) {
352
  @trigger_error('date_iso8601() is deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use date("c", $date) instead. See https://www.drupal.org/node/2999991.', E_USER_DEPRECATED);
353 354 355 356 357
  // The DATE_ISO8601 constant cannot be used here because it does not match
  // date('c') and produces invalid RDF markup.
  return date('c', $date);
}

Dries's avatar
 
Dries committed
358 359 360
/**
 * @} End of "defgroup format".
 */
Dries's avatar
 
Dries committed
361

362
/**
363
 * Formats an attribute string for an HTTP header.
364
 *
365
 * @param array $attributes
366 367
 *   An associative array of attributes such as 'rel'.
 *
368
 * @return string
369 370
 *   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.
371 372 373 374 375 376
 *
 * @deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use
 *   \Drupal\Core\Render\HtmlResponseAttachmentsProcessor::formatHttpHeaderAttributes()
 *   instead.
 *
 * @see https://www.drupal.org/node/3000051
377
 */
378
function drupal_http_header_attributes(array $attributes = []) {
379
  @trigger_error("drupal_http_header_attributes() is deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\Render\HtmlResponseAttachmentsProcessor::formatHttpHeaderAttributes() instead. See https://www.drupal.org/node/3000051", E_USER_DEPRECATED);
380
  return HtmlResponseAttachmentsProcessor::formatHttpHeaderAttributes($attributes);
381 382
}

383 384 385 386 387 388 389 390
/**
 * 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.
391
 *
392 393 394 395 396
 * 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
397
 * to execute a task than only once at the beginning of the script.
398
 *
399 400 401 402 403 404 405 406 407
 * 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.
408 409
 *
 * @ingroup php_wrappers
410 411
 *
 * @deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use
412
 *   \Drupal\Component\Utility\Environment::setTimeLimit() instead.
413 414
 *
 * @see https://www.drupal.org/node/3000058
415 416
 */
function drupal_set_time_limit($time_limit) {
417
  @trigger_error('drupal_set_time_limit() is deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use \Drupal\Component\Utility\Environment::setTimeLimit() instead. See https://www.drupal.org/node/3000058.', E_USER_DEPRECATED);
418
  Environment::setTimeLimit($time_limit);
419 420
}

421
/**
422
 * Returns the base URL path (i.e., directory) of the Drupal installation.
423
 *
424 425
 * Function 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 "/".
426
 *
427 428 429
 * Examples:
 * - http://example.com returns "/" because the path is empty.
 * - http://example.com/drupal/folder returns "/drupal/folder/".
430 431
 */
function base_path() {
432
  return $GLOBALS['base_path'];
433 434
}

435
/**
436
 * Deletes old cached CSS files.
437
 *
438 439
 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
 *   Use \Drupal\Core\Asset\AssetCollectionOptimizerInterface::deleteAll().
440 441
 *
 * @see https://www.drupal.org/node/2317841
442
 */
443 444
function drupal_clear_css_cache() {
  \Drupal::service('asset.css.collection_optimizer')->deleteAll();
445 446
}

Steven Wittens's avatar
Steven Wittens committed
447
/**
448
 * Constructs an array of the defaults that are used for JavaScript assets.
449 450
 *
 * @param $data
451
 *   (optional) The default data parameter for the JavaScript asset array.
452
 *
453
 * @see hook_js_alter()
454 455
 */
function drupal_js_defaults($data = NULL) {
456
  return [
457
    'type' => 'file',
458 459
    'group' => JS_DEFAULT,
    'weight' => 0,
460 461
    'scope' => 'header',
    'cache' => TRUE,
462
    'preprocess' => TRUE,
463
    'attributes' => [],
464
    'version' => NULL,
465
    'data' => $data,
466 467
    'browsers' => [],
  ];
468 469
}

470
/**
471
 * Adds JavaScript to change the state of an element based on another element.
472
 *
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
 * 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
506
 * conditions, which must be met on that element:
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
 * @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),
540
 *     ),
541 542 543 544 545 546 547
 *   ),
 * );
 * @endcode
 *
 * The following states may be applied to an element:
 * - enabled
 * - disabled
548 549
 * - required
 * - optional
550 551 552 553 554 555 556 557
 * - visible
 * - invisible
 * - checked
 * - unchecked
 * - expanded
 * - collapsed
 *
 * The following states may be used in remote conditions:
558 559
 * - empty
 * - filled
560 561
 * - checked
 * - unchecked
562 563
 * - expanded
 * - collapsed
564 565
 * - value
 *
566 567
 * The following states exist for both elements and remote conditions, but are
 * not fully implemented and may not change anything on the element:
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
 * - 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.
 *
591 592 593 594 595
 * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
 *   \Drupal\Core\Form\FormHelper::processStates() instead.
 *
 * @see https://www.drupal.org/node/3000069
 * @see \Drupal\Core\Form\FormHelper::processStates()
596 597
 */
function drupal_process_states(&$elements) {
598 599
  @trigger_error('drupal_process_states() is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Form\FormHelper::processStates() instead. See https://www.drupal.org/node/3000069', E_USER_DEPRECATED);
  FormHelper::processStates($elements);
600 601
}

602
/**
603
 * Assists in attaching the tableDrag JavaScript behavior to a themed table.
604 605 606 607 608
 *
 * 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.
 *
609 610
 * 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
611 612
 * into a table. The table must have an ID attribute set and it
 * may be set as follows:
613
 * @code
614 615 616 617 618 619 620 621
 * $table = array(
 *   '#type' => 'table',
 *   '#header' => $header,
 *   '#rows' => $rows,
 *   '#attributes' => array(
 *     'id' => 'my-module-table',
 *   ),
 * );
622
 * return \Drupal::service('renderer')->render($table);
623 624 625 626 627 628 629 630
 * @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
631
 * $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
632 633
 * @endcode
 *
634 635
 * Each row of the table must also have a class of "draggable" in order to
 * enable the drag handles:
636 637 638 639
 * @code
 * $row = array(...);
 * $rows[] = array(
 *   'data' => $row,
640
 *   'class' => array('draggable'),
641 642
 * );
 * @endcode
Dries's avatar
Dries committed
643
 *
644 645 646 647 648
 * 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.
 *
649
 * Calling drupal_attach_tabledrag() would then be written as such:
650
 * @code
651 652 653 654 655
 * drupal_attach_tabledrag('my-module-table', array(
 *   'action' => 'order',
 *   'relationship' => 'sibling',
 *   'group' => 'my-elements-weight',
 * );
656 657 658
 * @endcode
 *
 * In a more complex case where there are several groups in one column (such as
659 660
 * the block regions on the admin/structure/block page), a separate subgroup
 * class must also be added to differentiate the groups.
661
 * @code
662
 * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
663 664
 * @endcode
 *
665 666 667 668
 * 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.
669 670 671
 *
 * @code
 * foreach ($regions as $region) {
672 673
 *   drupal_attach_tabledrag('my-module-table', array(
 *     'action' => 'order',
674
 *     'relationship' => 'sibling',
675
 *     'group' => 'my-elements-weight',
676
 *     'subgroup' => 'my-elements-weight-' . $region,
677
 *   ));
678 679 680 681 682
 * }
 * @endcode
 *
 * In a situation where tree relationships are present, adding multiple
 * subgroups is not necessary, because the table will contain indentations that
683
 * provide enough information about the sibling and parent relationships. See
684 685
 * MenuForm::BuildOverviewForm for an example creating a table
 * containing parent relationships.
686
 *
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
 * @param $element
 *   A form element to attach the tableDrag behavior to.
 * @param array $options
 *   These options are used to generate JavaScript settings necessary to
 *   configure the tableDrag behavior appropriately for this particular table.
 *   An associative array containing the following keys:
 *   - 'table_id': String containing the target table's id attribute.
 *     If the table does not have an id, one will need to be set,
 *     such as <table id="my-module-table">.
 *   - 'action': String describing the action to be done on the form item.
 *      Either 'match' 'depth', or 'order':
 *     - 'match' is typically used for parent relationships.
 *     - 'order' is typically used to set weights on other form elements with
 *       the same group.
 *     - 'depth' updates the target element with the current indentation.
 *   - 'relationship': String describing where the "action" option
 *     should be performed. Either 'parent', 'sibling', 'group', or 'self':
 *     - 'parent' will only look for fields up the tree.
 *     - 'sibling' will look for fields in the same group in rows above and
 *       below it.
 *     - 'self' affects the dragged row itself.
 *     - 'group' affects the dragged row, plus any children below it (the entire
 *       dragged group).
 *   - 'group': A class name applied on all related form elements for this action.
 *   - 'subgroup': (optional) If the group has several subgroups within it, this
 *     string should contain the class name identifying fields in the same
 *     subgroup.
 *   - 'source': (optional) If the $action is 'match', this string should contain
 *     the classname identifying what field will be used as the source value
 *     when matching the value in $subgroup.
 *   - 'hidden': (optional) The column containing the field elements may be
 *     entirely hidden from view dynamically when the JavaScript is loaded. Set
 *     to FALSE if the column should not be hidden.
 *   - 'limit': (optional) Limit the maximum amount of parenting in this table.
 *
722
 * @see MenuForm::BuildOverviewForm()
723
 */
724 725
function drupal_attach_tabledrag(&$element, array $options) {
  // Add default values to elements.
726
  $options = $options + [
727 728 729
    'subgroup' => NULL,
    'source' => NULL,
    'hidden' => TRUE,
730
    'limit' => 0,
731
  ];
732

733 734 735 736
  $group = $options['group'];

  $tabledrag_id = &drupal_static(__FUNCTION__);
  $tabledrag_id = (!isset($tabledrag_id)) ? 0 : $tabledrag_id + 1;
737 738

  // If a subgroup or source isn't set, assume it is the same as the group.
739 740
  $target = isset($options['subgroup']) ? $options['subgroup'] : $group;
  $source = isset($options['source']) ? $options['source'] : $target;
741
  $element['#attached']['drupalSettings']['tableDrag'][$options['table_id']][$group][$tabledrag_id] = [
742 743
    'target' => $target,
    'source' => $source,
744 745 746 747
    'relationship' => $options['relationship'],
    'action' => $options['action'],
    'hidden' => $options['hidden'],
    'limit' => $options['limit'],
748
  ];
749

750
  $element['#attached']['library'][] = 'core/drupal.tabledrag';
751 752
}

753
/**
754
 * Deletes old cached JavaScript files and variables.
755 756 757
 *
 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
 *   Use \Drupal\Core\Asset\AssetCollectionOptimizerInterface::deleteAll().
758 759
 *
 * @see https://www.drupal.org/node/2317841
760 761
 */
function drupal_clear_js_cache() {
762
  \Drupal::service('asset.js.collection_optimizer')->deleteAll();
763 764
}

765
/**
766
 * Pre-render callback: Renders a link into #markup.
767
 *
768 769
 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
 *   Use \Drupal\Core\Render\Element\Link::preRenderLink().
770
 */
771
function drupal_pre_render_link($element) {
772
  return Link::preRenderLink($element);
773 774
}

775
/**
776
 * Pre-render callback: Collects child links into a single array.
777
 *
778
 * @deprecated in drupal:8.0.0 and will be removed before drupal:9.0.0. Use
779
 *   \Drupal\Core\Render\Element\Link::preRenderLinks() instead.
780
 *
781
 * @see https://www.drupal.org/node/2966725
782 783
 */
function drupal_pre_render_links($element) {
784 785
  @trigger_error('drupal_pre_render_links() is deprecated in Drupal 8.8.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\Render\Element\Link::preRenderLinks() instead. See https://www.drupal.org/node/2966725', E_USER_DEPRECATED);
  return Link::preRenderLinks($element);
786 787
}

788 789 790
/**
 * Renders final HTML given a structured array tree.
 *
791 792
 * @deprecated as of drupal:8.0.0 and is removed from drupal:9.0.0. Use
 *   \Drupal\Core\Render\RendererInterface::renderRoot() instead.
793
 *
794
 * @see \Drupal\Core\Render\RendererInterface::renderRoot()
795
 * @see https://www.drupal.org/node/2912696
796 797
 */
function drupal_render_root(&$elements) {
798
  @trigger_error('drupal_render_root() is deprecated in drupal:8.0.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Render\RendererInterface::renderRoot() instead. See https://www.drupal.org/node/2912696', E_USER_DEPRECATED);
799
  return \Drupal::service('renderer')->renderRoot($elements);
800 801
}

802
/**
803 804
 * Renders HTML given a structured array tree.
 *
805 806
 * @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0. Use the
 *   'renderer' service instead.
807
 *
808
 * @see \Drupal\Core\Render\RendererInterface::render()
809
 * @see https://www.drupal.org/node/2912696
810 811 812
 */
function drupal_render(&$elements, $is_recursive_call = FALSE) {
  return \Drupal::service('renderer')->render($elements, $is_recursive_call);
813 814 815
}

/**
816
 * Renders children of an element and concatenates them.
817
 *
818
 * @param array $element
819
 *   The structured array whose children shall be rendered.
820 821
 * @param array $children_keys
 *   (optional) If the keys of the element's children are already known, they
822 823
 *   can be passed in to save another run of
 *   \Drupal\Core\Render\Element::children().
824
 *
825
 * @return string|\Drupal\Component\Render\MarkupInterface
826
 *   The rendered HTML of all children of the element.
827
 *
828 829 830 831
 * @deprecated in Drupal 8.0.x and will be removed before 9.0.0. Avoid early
 *   rendering when possible or loop through the elements and render them as
 *   they are available.
 *
832
 * @see \Drupal\Core\Render\RendererInterface::render()
833
 * @see https://www.drupal.org/node/2912757
834
 */
835
function drupal_render_children(&$element, $children_keys = NULL) {
836
  if ($children_keys === NULL) {
837
    $children_keys = Element::children($element);
838 839 840
  }
  $output = '';
  foreach ($children_keys as $key) {
841
    if (!empty($element[$key])) {
842
      $output .= \Drupal::service('renderer')->render($element[$key]);
843
    }
844
  }
845
  return Markup::create($output);
846 847
}

848
/**
849
 * Renders an element.
850
 *
851 852 853
 * This function renders an element. The top level element is shown with show()
 * before rendering, so it will always be rendered even if hide() had been
 * previously used on it.
854
 *
855 856 857 858 859
 * @param $element
 *   The element to be rendered.
 *
 * @return
 *   The rendered element.
860
 *
861
 * @see \Drupal\Core\Render\RendererInterface
862 863 864 865
 * @see show()
 * @see hide()
 */
function render(&$element) {
866 867 868
  if (!$element && $element !== 0) {
    return NULL;
  }
869
  if (is_array($element)) {
870 871 872 873
    // Early return if this element was pre-rendered (no need to re-render).
    if (isset($element['#printed']) && $element['#printed'] == TRUE && isset($element['#markup']) && strlen($element['#markup']) > 0) {
      return $element['#markup'];
    }
874
    show($element);
875
    return \Drupal::service('renderer')->render($element);
876 877
  }
  else {
878 879 880
    // Safe-guard for inappropriate use of render() on flat variables: return
    // the variable as-is.
    return $element;
881 882 883 884
  }
}

/**
885
 * Hides an element from later rendering.
886
 *
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901