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