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