comparison core/includes/common.inc @ 0:4c8ae668cc8c

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