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