5 * Common functions that many Drupal modules will need to reference.
7 * The functions that are critical and need to be available even when serving
8 * a cached page are instead located in bootstrap.inc.
11 use Drupal\Component\Serialization\Json;
12 use Drupal\Component\Utility\Bytes;
13 use Drupal\Component\Utility\Html;
14 use Drupal\Component\Utility\SortArray;
15 use Drupal\Component\Utility\UrlHelper;
16 use Drupal\Core\Cache\Cache;
17 use Drupal\Core\Render\Element\Link;
18 use Drupal\Core\Render\Markup;
19 use Drupal\Core\StringTranslation\TranslatableMarkup;
20 use Drupal\Core\StringTranslation\PluralTranslatableMarkup;
21 use Drupal\Core\Render\BubbleableMetadata;
22 use Drupal\Core\Render\Element;
25 * @defgroup php_wrappers PHP wrapper functions
27 * Functions that are wrappers or custom implementations of PHP functions.
29 * Certain PHP functions should not be used in Drupal. Instead, Drupal's
30 * replacement functions should be used.
32 * For example, for improved or more secure UTF8-handling, or RFC-compliant
33 * handling of URLs in Drupal.
35 * For ease of use and memorizing, all these wrapper functions use the same name
36 * as the original PHP function, but prefixed with "drupal_". Beware, however,
37 * that not all wrapper functions support the same arguments as the original
40 * You should always use these wrapper functions in your code.
44 * $my_substring = substr($original_string, 0, 5);
49 * $my_substring = mb_substr($original_string, 0, 5);
56 * Return status for saving which involved creating a new item.
61 * Return status for saving which involved an update to an existing item.
63 const SAVED_UPDATED = 2;
66 * Return status for saving which deleted an existing item.
68 const SAVED_DELETED = 3;
71 * The default aggregation group for CSS files added to the page.
73 const CSS_AGGREGATE_DEFAULT = 0;
76 * The default aggregation group for theme CSS files added to the page.
78 const CSS_AGGREGATE_THEME = 100;
81 * The default weight for CSS rules that style HTML elements ("base" styles).
83 const CSS_BASE = -200;
86 * The default weight for CSS rules that layout a page.
88 const CSS_LAYOUT = -100;
91 * The default weight for CSS rules that style design components (and their associated states and themes.)
93 const CSS_COMPONENT = 0;
96 * The default weight for CSS rules that style states and are not included with components.
98 const CSS_STATE = 100;
101 * The default weight for CSS rules that style themes and are not included with components.
103 const CSS_THEME = 200;
106 * The default group for JavaScript settings added to the page.
108 const JS_SETTING = -200;
111 * The default group for JavaScript and jQuery libraries added to the page.
113 const JS_LIBRARY = -100;
116 * The default group for module JavaScript code added to the page.
118 const JS_DEFAULT = 0;
121 * The default group for theme JavaScript code added to the page.
123 const JS_THEME = 100;
126 * The delimiter used to split plural strings.
128 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
129 * Use \Drupal\Core\StringTranslation\PluralTranslatableMarkup::DELIMITER
132 const LOCALE_PLURAL_DELIMITER = PluralTranslatableMarkup::DELIMITER;
135 * Prepares a 'destination' URL query parameter.
137 * Used to direct the user back to the referring page after completing a form.
138 * By default the current URL is returned. If a destination exists in the
139 * previous request, that destination is returned. As such, a destination can
140 * persist across multiple pages.
143 * An associative array containing the key:
144 * - destination: The value of the current request's 'destination' query
145 * parameter, if present. This can be either a relative or absolute URL.
146 * However, for security, redirection to external URLs is not performed.
147 * If the query parameter isn't present, then the URL of the current
148 * request is returned.
152 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
153 * Use the redirect.destination service.
155 * @see \Drupal\Core\EventSubscriber\RedirectResponseSubscriber::checkRedirectUrl()
156 * @see https://www.drupal.org/node/2448603
158 function drupal_get_destination() {
159 return \Drupal::destination()->getAsArray();
163 * @defgroup validation Input validation
165 * Functions to validate user input.
169 * Verifies the syntax of the given email address.
171 * @param string $mail
172 * A string containing an email address.
175 * TRUE if the address is in a valid format.
177 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
178 * Use \Drupal::service('email.validator')->isValid().
180 * @see https://www.drupal.org/node/2912661
182 function valid_email_address($mail) {
183 return \Drupal::service('email.validator')->isValid($mail);
187 * @} End of "defgroup validation".
191 * @defgroup sanitization Sanitization functions
193 * Functions to sanitize values.
195 * See https://www.drupal.org/writing-secure-code for information
196 * on writing secure code.
200 * Strips dangerous protocols from a URI and encodes it for output to HTML.
203 * A plain-text URI that might contain dangerous protocols.
206 * A URI stripped of dangerous protocols and encoded for output to an HTML
207 * attribute value. Because it is already encoded, it should not be set as a
208 * value within a $attributes array passed to Drupal\Core\Template\Attribute,
209 * because Drupal\Core\Template\Attribute expects those values to be
210 * plain-text strings. To pass a filtered URI to
211 * Drupal\Core\Template\Attribute, call
212 * \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() instead.
214 * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
215 * Use UrlHelper::stripDangerousProtocols() or UrlHelper::filterBadProtocol()
216 * instead. UrlHelper::stripDangerousProtocols() can be used in conjunction
217 * with \Drupal\Component\Render\FormattableMarkup and an @variable
218 * placeholder which will perform the necessary escaping.
219 * UrlHelper::filterBadProtocol() is functionality equivalent to check_url()
220 * apart from the fact it is protected from double escaping bugs. Note that
221 * this method no longer marks its output as safe.
223 * @see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols()
224 * @see \Drupal\Component\Utility\UrlHelper::filterBadProtocol()
225 * @see https://www.drupal.org/node/2560027
227 function check_url($uri) {
228 return Html::escape(UrlHelper::stripDangerousProtocols($uri));
232 * @} End of "defgroup sanitization".
236 * @defgroup format Formatting
238 * Functions to format numbers, strings, dates, etc.
242 * Generates a string representation for the given byte count.
247 * Optional language code to translate to a language other than what is used
248 * to display the page.
250 * @return \Drupal\Core\StringTranslation\TranslatableMarkup
251 * A translated string representation of the size.
253 function format_size($size, $langcode = NULL) {
254 $absolute_size = abs($size);
255 if ($absolute_size < Bytes::KILOBYTE) {
256 return \Drupal::translation()->formatPlural($size, '1 byte', '@count bytes', [], ['langcode' => $langcode]);
258 // Create a multiplier to preserve the sign of $size.
259 $sign = $absolute_size / $size;
260 foreach (['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] as $unit) {
261 $absolute_size /= Bytes::KILOBYTE;
262 $rounded_size = round($absolute_size, 2);
263 if ($rounded_size < Bytes::KILOBYTE) {
267 $args = ['@size' => $rounded_size * $sign];
268 $options = ['langcode' => $langcode];
271 return new TranslatableMarkup('@size KB', $args, $options);
274 return new TranslatableMarkup('@size MB', $args, $options);
277 return new TranslatableMarkup('@size GB', $args, $options);
280 return new TranslatableMarkup('@size TB', $args, $options);
283 return new TranslatableMarkup('@size PB', $args, $options);
286 return new TranslatableMarkup('@size EB', $args, $options);
289 return new TranslatableMarkup('@size ZB', $args, $options);
292 return new TranslatableMarkup('@size YB', $args, $options);
297 * Formats a date, using a date type or a custom date format string.
300 * A UNIX timestamp to format.
302 * (optional) The format to use, one of:
303 * - One of the built-in formats: 'short', 'medium',
304 * 'long', 'html_datetime', 'html_date', 'html_time',
305 * 'html_yearless_date', 'html_week', 'html_month', 'html_year'.
306 * - The name of a date type defined by a date format config entity.
307 * - The machine name of an administrator-defined date format.
308 * - 'custom', to use $format.
309 * Defaults to 'medium'.
311 * (optional) If $type is 'custom', a PHP date format string suitable for
312 * input to date(). Use a backslash to escape ordinary text, so it does not
313 * get interpreted as date format characters.
315 * (optional) Time zone identifier, as described at
316 * http://php.net/manual/timezones.php Defaults to the time zone used to
319 * (optional) Language code to translate to. Defaults to the language used to
323 * A translated date string in the requested format.
325 * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
326 * Use \Drupal::service('date.formatter')->format().
328 * @see \Drupal\Core\Datetime\DateFormatter::format()
329 * @see https://www.drupal.org/node/1876852
331 function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
332 return \Drupal::service('date.formatter')->format($timestamp, $type, $format, $timezone, $langcode);
336 * Returns an ISO8601 formatted date based on the given date.
342 * An ISO8601 formatted date.
344 function date_iso8601($date) {
345 // The DATE_ISO8601 constant cannot be used here because it does not match
346 // date('c') and produces invalid RDF markup.
347 return date('c', $date);
351 * @} End of "defgroup format".
355 * Formats an attribute string for an HTTP header.
358 * An associative array of attributes such as 'rel'.
361 * A ; separated string ready for insertion in a HTTP header. No escaping is
362 * performed for HTML entities, so this string is not safe to be printed.
364 function drupal_http_header_attributes(array $attributes = []) {
365 foreach ($attributes as $attribute => &$data) {
366 if (is_array($data)) {
367 $data = implode(' ', $data);
369 $data = $attribute . '="' . $data . '"';
371 return $attributes ? ' ' . implode('; ', $attributes) : '';
375 * Attempts to set the PHP maximum execution time.
377 * This function is a wrapper around the PHP function set_time_limit().
378 * When called, set_time_limit() restarts the timeout counter from zero.
379 * In other words, if the timeout is the default 30 seconds, and 25 seconds
380 * into script execution a call such as set_time_limit(20) is made, the
381 * script will run for a total of 45 seconds before timing out.
383 * If the current time limit is not unlimited it is possible to decrease the
384 * total time limit if the sum of the new time limit and the current time spent
385 * running the script is inferior to the original time limit. It is inherent to
386 * the way set_time_limit() works, it should rather be called with an
387 * appropriate value every time you need to allocate a certain amount of time
388 * to execute a task than only once at the beginning of the script.
390 * Before calling set_time_limit(), we check if this function is available
391 * because it could be disabled by the server administrator. We also hide all
392 * the errors that could occur when calling set_time_limit(), because it is
393 * not possible to reliably ensure that PHP or a security extension will
394 * not issue a warning/error if they prevent the use of this function.
397 * An integer specifying the new time limit, in seconds. A value of 0
398 * indicates unlimited execution time.
400 * @ingroup php_wrappers
402 function drupal_set_time_limit($time_limit) {
403 if (function_exists('set_time_limit')) {
404 $current = ini_get('max_execution_time');
405 // Do not set time limit if it is currently unlimited.
407 @set_time_limit($time_limit);
413 * Returns the base URL path (i.e., directory) of the Drupal installation.
415 * Function base_path() adds a "/" to the beginning and end of the returned path
416 * if the path is not empty. At the very least, this will return "/".
419 * - http://example.com returns "/" because the path is empty.
420 * - http://example.com/drupal/folder returns "/drupal/folder/".
422 function base_path() {
423 return $GLOBALS['base_path'];
427 * Deletes old cached CSS files.
429 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
430 * Use \Drupal\Core\Asset\AssetCollectionOptimizerInterface::deleteAll().
432 * @see https://www.drupal.org/node/2317841
434 function drupal_clear_css_cache() {
435 \Drupal::service('asset.css.collection_optimizer')->deleteAll();
439 * Constructs an array of the defaults that are used for JavaScript assets.
442 * (optional) The default data parameter for the JavaScript asset array.
444 * @see hook_js_alter()
446 function drupal_js_defaults($data = NULL) {
449 'group' => JS_DEFAULT,
453 'preprocess' => TRUE,
462 * Adds JavaScript to change the state of an element based on another element.
464 * A "state" means a certain property on a DOM element, such as "visible" or
465 * "checked". A state can be applied to an element, depending on the state of
466 * another element on the page. In general, states depend on HTML attributes and
467 * DOM element properties, which change due to user interaction.
469 * Since states are driven by JavaScript only, it is important to understand
470 * that all states are applied on presentation only, none of the states force
471 * any server-side logic, and that they will not be applied for site visitors
472 * without JavaScript support. All modules implementing states have to make
473 * sure that the intended logic also works without JavaScript being enabled.
475 * #states is an associative array in the form of:
478 * STATE1 => CONDITIONS_ARRAY1,
479 * STATE2 => CONDITIONS_ARRAY2,
483 * Each key is the name of a state to apply to the element, such as 'visible'.
484 * Each value is a list of conditions that denote when the state should be
487 * Multiple different states may be specified to act on complex conditions:
490 * 'visible' => CONDITIONS,
491 * 'checked' => OTHER_CONDITIONS,
495 * Every condition is a key/value pair, whose key is a jQuery selector that
496 * denotes another element on the page, and whose value is an array of
497 * conditions, which must be met on that element:
500 * 'visible' => array(
501 * JQUERY_SELECTOR => REMOTE_CONDITIONS,
502 * JQUERY_SELECTOR => REMOTE_CONDITIONS,
507 * All conditions must be met for the state to be applied.
509 * Each remote condition is a key/value pair specifying conditions on the other
510 * element that need to be met to apply the state to the element:
513 * 'visible' => array(
514 * ':input[name="remote_checkbox"]' => array('checked' => TRUE),
519 * For example, to show a textfield only when a checkbox is checked:
521 * $form['toggle_me'] = array(
522 * '#type' => 'checkbox',
523 * '#title' => t('Tick this box to type'),
525 * $form['settings'] = array(
526 * '#type' => 'textfield',
527 * '#states' => array(
528 * // Only show this field when the 'toggle_me' checkbox is enabled.
529 * 'visible' => array(
530 * ':input[name="toggle_me"]' => array('checked' => TRUE),
536 * The following states may be applied to an element:
548 * The following states may be used in remote conditions:
557 * The following states exist for both elements and remote conditions, but are
558 * not fully implemented and may not change anything on the element:
568 * When referencing select lists and radio buttons in remote conditions, a
569 * 'value' condition must be used:
571 * '#states' => array(
572 * // Show the settings if 'bar' has been selected for 'foo'.
573 * 'visible' => array(
574 * ':input[name="foo"]' => array('value' => 'bar'),
580 * A renderable array element having a #states property as described above.
582 * @see form_example_states_form()
584 function drupal_process_states(&$elements) {
585 $elements['#attached']['library'][] = 'core/drupal.states';
586 // Elements of '#type' => 'item' are not actual form input elements, but we
587 // still want to be able to show/hide them. Since there's no actual HTML input
588 // element available, setting #attributes does not make sense, but a wrapper
589 // is available, so setting #wrapper_attributes makes it work.
590 $key = ($elements['#type'] == 'item') ? '#wrapper_attributes' : '#attributes';
591 $elements[$key]['data-drupal-states'] = Json::encode($elements['#states']);
595 * Assists in attaching the tableDrag JavaScript behavior to a themed table.
597 * Draggable tables should be used wherever an outline or list of sortable items
598 * needs to be arranged by an end-user. Draggable tables are very flexible and
599 * can manipulate the value of form elements placed within individual columns.
601 * To set up a table to use drag and drop in place of weight select-lists or in
602 * place of a form that contains parent relationships, the form must be themed
603 * into a table. The table must have an ID attribute set and it
604 * may be set as follows:
607 * '#type' => 'table',
608 * '#header' => $header,
610 * '#attributes' => array(
611 * 'id' => 'my-module-table',
614 * return \Drupal::service('renderer')->render($table);
617 * In the theme function for the form, a special class must be added to each
618 * form element within the same column, "grouping" them together.
620 * In a situation where a single weight column is being sorted in the table, the
621 * classes could be added like this (in the theme function):
623 * $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
626 * Each row of the table must also have a class of "draggable" in order to
627 * enable the drag handles:
632 * 'class' => array('draggable'),
636 * When tree relationships are present, the two additional classes
637 * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
638 * - Rows with the 'tabledrag-leaf' class cannot have child rows.
639 * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
641 * Calling drupal_attach_tabledrag() would then be written as such:
643 * drupal_attach_tabledrag('my-module-table', array(
644 * 'action' => 'order',
645 * 'relationship' => 'sibling',
646 * 'group' => 'my-elements-weight',
650 * In a more complex case where there are several groups in one column (such as
651 * the block regions on the admin/structure/block page), a separate subgroup
652 * class must also be added to differentiate the groups.
654 * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
657 * The 'group' option is still 'my-element-weight', and the additional
658 * 'subgroup' option will be passed in as 'my-elements-weight-' . $region. This
659 * also means that you'll need to call drupal_attach_tabledrag() once for every
663 * foreach ($regions as $region) {
664 * drupal_attach_tabledrag('my-module-table', array(
665 * 'action' => 'order',
666 * 'relationship' => 'sibling',
667 * 'group' => 'my-elements-weight',
668 * 'subgroup' => 'my-elements-weight-' . $region,
673 * In a situation where tree relationships are present, adding multiple
674 * subgroups is not necessary, because the table will contain indentations that
675 * provide enough information about the sibling and parent relationships. See
676 * MenuForm::BuildOverviewForm for an example creating a table
677 * containing parent relationships.
680 * A form element to attach the tableDrag behavior to.
681 * @param array $options
682 * These options are used to generate JavaScript settings necessary to
683 * configure the tableDrag behavior appropriately for this particular table.
684 * An associative array containing the following keys:
685 * - 'table_id': String containing the target table's id attribute.
686 * If the table does not have an id, one will need to be set,
687 * such as <table id="my-module-table">.
688 * - 'action': String describing the action to be done on the form item.
689 * Either 'match' 'depth', or 'order':
690 * - 'match' is typically used for parent relationships.
691 * - 'order' is typically used to set weights on other form elements with
693 * - 'depth' updates the target element with the current indentation.
694 * - 'relationship': String describing where the "action" option
695 * should be performed. Either 'parent', 'sibling', 'group', or 'self':
696 * - 'parent' will only look for fields up the tree.
697 * - 'sibling' will look for fields in the same group in rows above and
699 * - 'self' affects the dragged row itself.
700 * - 'group' affects the dragged row, plus any children below it (the entire
702 * - 'group': A class name applied on all related form elements for this action.
703 * - 'subgroup': (optional) If the group has several subgroups within it, this
704 * string should contain the class name identifying fields in the same
706 * - 'source': (optional) If the $action is 'match', this string should contain
707 * the classname identifying what field will be used as the source value
708 * when matching the value in $subgroup.
709 * - 'hidden': (optional) The column containing the field elements may be
710 * entirely hidden from view dynamically when the JavaScript is loaded. Set
711 * to FALSE if the column should not be hidden.
712 * - 'limit': (optional) Limit the maximum amount of parenting in this table.
714 * @see MenuForm::BuildOverviewForm()
716 function drupal_attach_tabledrag(&$element, array $options) {
717 // Add default values to elements.
718 $options = $options + [
725 $group = $options['group'];
727 $tabledrag_id = &drupal_static(__FUNCTION__);
728 $tabledrag_id = (!isset($tabledrag_id)) ? 0 : $tabledrag_id + 1;
730 // If a subgroup or source isn't set, assume it is the same as the group.
731 $target = isset($options['subgroup']) ? $options['subgroup'] : $group;
732 $source = isset($options['source']) ? $options['source'] : $target;
733 $element['#attached']['drupalSettings']['tableDrag'][$options['table_id']][$group][$tabledrag_id] = [
736 'relationship' => $options['relationship'],
737 'action' => $options['action'],
738 'hidden' => $options['hidden'],
739 'limit' => $options['limit'],
742 $element['#attached']['library'][] = 'core/drupal.tabledrag';
746 * Deletes old cached JavaScript files and variables.
748 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
749 * Use \Drupal\Core\Asset\AssetCollectionOptimizerInterface::deleteAll().
751 * @see https://www.drupal.org/node/2317841
753 function drupal_clear_js_cache() {
754 \Drupal::service('asset.js.collection_optimizer')->deleteAll();
758 * Pre-render callback: Renders a link into #markup.
760 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
761 * Use \Drupal\Core\Render\Element\Link::preRenderLink().
763 function drupal_pre_render_link($element) {
764 return Link::preRenderLink($element);
768 * Pre-render callback: Collects child links into a single array.
770 * This function can be added as a pre_render callback for a renderable array,
771 * usually one which will be themed by links.html.twig. It iterates through all
772 * unrendered children of the element, collects any #links properties it finds,
773 * merges them into the parent element's #links array, and prevents those
774 * children from being rendered separately.
776 * The purpose of this is to allow links to be logically grouped into related
777 * categories, so that each child group can be rendered as its own list of
778 * links if drupal_render() is called on it, but calling drupal_render() on the
779 * parent element will still produce a single list containing all the remaining
780 * links, regardless of what group they were in.
782 * A typical example comes from node links, which are stored in a renderable
783 * array similar to this:
785 * $build['links'] = array(
786 * '#theme' => 'links__node',
787 * '#pre_render' => array('drupal_pre_render_links'),
788 * 'comment' => array(
789 * '#theme' => 'links__node__comment',
791 * // An array of links associated with node comments, suitable for
792 * // passing in to links.html.twig.
795 * 'statistics' => array(
796 * '#theme' => 'links__node__statistics',
798 * // An array of links associated with node statistics, suitable for
799 * // passing in to links.html.twig.
802 * 'translation' => array(
803 * '#theme' => 'links__node__translation',
805 * // An array of links associated with node translation, suitable for
806 * // passing in to links.html.twig.
812 * In this example, the links are grouped by functionality, which can be
813 * helpful to themers who want to display certain kinds of links independently.
814 * For example, adding this code to node.html.twig will result in the comment
815 * links being rendered as a single list:
817 * {{ content.links.comment }}
820 * (where a node's content has been transformed into $content before handing
821 * control to the node.html.twig template).
823 * The pre_render function defined here allows the above flexibility, but also
824 * allows the following code to be used to render all remaining links into a
825 * single list, regardless of their group:
827 * {{ content.links }}
830 * In the above example, this will result in the statistics and translation
831 * links being rendered together in a single list (but not the comment links,
832 * which were rendered previously on their own).
834 * Because of the way this function works, the individual properties of each
835 * group (for example, a group-specific #theme property such as
836 * 'links__node__comment' in the example above, or any other property such as
837 * #attributes or #pre_render that is attached to it) are only used when that
838 * group is rendered on its own. When the group is rendered together with other
839 * children, these child-specific properties are ignored, and only the overall
840 * properties of the parent are used.
842 function drupal_pre_render_links($element) {
843 $element += ['#links' => [], '#attached' => []];
844 foreach (Element::children($element) as $key) {
845 $child = &$element[$key];
846 // If the child has links which have not been printed yet and the user has
847 // access to it, merge its links in to the parent.
848 if (isset($child['#links']) && empty($child['#printed']) && Element::isVisibleElement($child)) {
849 $element['#links'] += $child['#links'];
850 // Mark the child as having been printed already (so that its links
851 // cannot be mistakenly rendered twice).
852 $child['#printed'] = TRUE;
854 // Merge attachments.
855 if (isset($child['#attached'])) {
856 $element['#attached'] = BubbleableMetadata::mergeAttachments($element['#attached'], $child['#attached']);
863 * Renders final HTML given a structured array tree.
865 * @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0. Use the
866 * 'renderer' service instead.
868 * @see \Drupal\Core\Render\RendererInterface::renderRoot()
869 * @see https://www.drupal.org/node/2912696
871 function drupal_render_root(&$elements) {
872 return \Drupal::service('renderer')->renderRoot($elements);
876 * Renders HTML given a structured array tree.
878 * @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0. Use the
879 * 'renderer' service instead.
881 * @see \Drupal\Core\Render\RendererInterface::render()
882 * @see https://www.drupal.org/node/2912696
884 function drupal_render(&$elements, $is_recursive_call = FALSE) {
885 return \Drupal::service('renderer')->render($elements, $is_recursive_call);
889 * Renders children of an element and concatenates them.
891 * @param array $element
892 * The structured array whose children shall be rendered.
893 * @param array $children_keys
894 * (optional) If the keys of the element's children are already known, they
895 * can be passed in to save another run of
896 * \Drupal\Core\Render\Element::children().
898 * @return string|\Drupal\Component\Render\MarkupInterface
899 * The rendered HTML of all children of the element.
901 * @deprecated in Drupal 8.0.x and will be removed before 9.0.0. Avoid early
902 * rendering when possible or loop through the elements and render them as
903 * they are available.
905 * @see \Drupal\Core\Render\RendererInterface::render()
906 * @see https://www.drupal.org/node/2912757
908 function drupal_render_children(&$element, $children_keys = NULL) {
909 if ($children_keys === NULL) {
910 $children_keys = Element::children($element);
913 foreach ($children_keys as $key) {
914 if (!empty($element[$key])) {
915 $output .= \Drupal::service('renderer')->render($element[$key]);
918 return Markup::create($output);
922 * Renders an element.
924 * This function renders an element. The top level element is shown with show()
925 * before rendering, so it will always be rendered even if hide() had been
926 * previously used on it.
929 * The element to be rendered.
932 * The rendered element.
934 * @see \Drupal\Core\Render\RendererInterface
938 function render(&$element) {
939 if (!$element && $element !== 0) {
942 if (is_array($element)) {
943 // Early return if this element was pre-rendered (no need to re-render).
944 if (isset($element['#printed']) && $element['#printed'] == TRUE && isset($element['#markup']) && strlen($element['#markup']) > 0) {
945 return $element['#markup'];
948 return \Drupal::service('renderer')->render($element);
951 // Safe-guard for inappropriate use of render() on flat variables: return
952 // the variable as-is.
958 * Hides an element from later rendering.
960 * The first time render() or drupal_render() is called on an element tree,
961 * as each element in the tree is rendered, it is marked with a #printed flag
962 * and the rendered children of the element are cached. Subsequent calls to
963 * render() or drupal_render() will not traverse the child tree of this element
964 * again: they will just use the cached children. So if you want to hide an
965 * element, be sure to call hide() on the element before its parent tree is
966 * rendered for the first time, as it will have no effect on subsequent
967 * renderings of the parent tree.
970 * The element to be hidden.
978 function hide(&$element) {
979 $element['#printed'] = TRUE;
984 * Shows a hidden element for later rendering.
986 * You can also use render($element), which shows the element while rendering
989 * The first time render() or drupal_render() is called on an element tree,
990 * as each element in the tree is rendered, it is marked with a #printed flag
991 * and the rendered children of the element are cached. Subsequent calls to
992 * render() or drupal_render() will not traverse the child tree of this element
993 * again: they will just use the cached children. So if you want to show an
994 * element, be sure to call show() on the element before its parent tree is
995 * rendered for the first time, as it will have no effect on subsequent
996 * renderings of the parent tree.
999 * The element to be shown.
1007 function show(&$element) {
1008 $element['#printed'] = FALSE;
1013 * Retrieves the default properties for the defined element type.
1016 * An element type as defined by an element plugin.
1018 * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
1019 * Use \Drupal::service('element_info')->getInfo() instead.
1021 * @see https://www.drupal.org/node/2235461
1023 function element_info($type) {
1024 return \Drupal::service('element_info')->getInfo($type);
1028 * Retrieves a single property for the defined element type.
1031 * An element type as defined by an element plugin.
1032 * @param $property_name
1033 * The property within the element type that should be returned.
1035 * (Optional) The value to return if the element type does not specify a
1036 * value for the property. Defaults to NULL.
1038 * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
1039 * Use \Drupal::service('element_info')->getInfoProperty() instead.
1041 * @see https://www.drupal.org/node/2235461
1043 function element_info_property($type, $property_name, $default = NULL) {
1044 return \Drupal::service('element_info')->getInfoProperty($type, $property_name, $default);
1048 * Flushes all persistent caches, resets all variables, and rebuilds all data structures.
1050 * At times, it is necessary to re-initialize the entire system to account for
1051 * changed or new code. This function:
1052 * - Clears all persistent caches:
1053 * - The bootstrap cache bin containing base system, module system, and theme
1054 * system information.
1055 * - The common 'default' cache bin containing arbitrary caches.
1057 * - The URL alias path cache.
1058 * - Resets all static variables that have been defined via drupal_static().
1059 * - Clears asset (JS/CSS) file caches.
1060 * - Updates the system with latest information about extensions (modules and
1062 * - Updates the bootstrap flag for modules implementing bootstrap_hooks().
1063 * - Rebuilds the full database schema information (invoking hook_schema()).
1064 * - Rebuilds data structures of all modules (invoking hook_rebuild()). In
1066 * - blocks, node types, date formats and actions are synchronized with the
1068 * - The 'active' status of fields is refreshed.
1069 * - Rebuilds the menu router.
1071 * This means the entire system is reset so all caches and static variables are
1072 * effectively empty. After that is guaranteed, information about the currently
1073 * active code is updated, and rebuild operations are successively called in
1074 * order to synchronize the active system according to the current information
1077 * All modules need to ensure that all of their caches are flushed when
1078 * hook_cache_flush() is invoked; any previously known information must no
1079 * longer exist. All following hook_rebuild() operations must be based on fresh
1080 * and current system data. All modules must be able to rely on this contract.
1082 * @see \Drupal\Core\Cache\CacheHelper::getBins()
1083 * @see hook_cache_flush()
1084 * @see hook_rebuild()
1086 * This function also resets the theme, which means it is not initialized
1087 * anymore and all previously added JavaScript and CSS is gone. Normally, this
1088 * function is called as an end-of-POST-request operation that is followed by a
1089 * redirect, so this effect is not visible. Since the full reset is the whole
1090 * point of this function, callers need to take care for backing up all needed
1091 * variables and properly restoring or re-initializing them on their own. For
1092 * convenience, this function automatically re-initializes the maintenance theme
1093 * if it was initialized before.
1095 * @todo Try to clear page/JS/CSS caches last, so cached pages can still be
1096 * served during this possibly long-running operation. (Conflict on bootstrap
1098 * @todo Add a global lock to ensure that caches are not primed in concurrent
1101 function drupal_flush_all_caches() {
1102 $module_handler = \Drupal::moduleHandler();
1103 // Flush all persistent caches.
1104 // This is executed based on old/previously known information, which is
1105 // sufficient, since new extensions cannot have any primed caches yet.
1106 $module_handler->invokeAll('cache_flush');
1107 foreach (Cache::getBins() as $service_id => $cache_backend) {
1108 $cache_backend->deleteAll();
1111 // Flush asset file caches.
1112 \Drupal::service('asset.css.collection_optimizer')->deleteAll();
1113 \Drupal::service('asset.js.collection_optimizer')->deleteAll();
1114 _drupal_flush_css_js();
1116 // Reset all static caches.
1117 drupal_static_reset();
1119 // Invalidate the container.
1120 \Drupal::service('kernel')->invalidateContainer();
1122 // Wipe the Twig PHP Storage cache.
1123 \Drupal::service('twig')->invalidate();
1125 // Rebuild module and theme data.
1126 $module_data = system_rebuild_module_data();
1127 /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
1128 $theme_handler = \Drupal::service('theme_handler');
1129 $theme_handler->refreshInfo();
1130 // In case the active theme gets requested later in the same request we need
1131 // to reset the theme manager.
1132 \Drupal::theme()->resetActiveTheme();
1134 // Rebuild and reboot a new kernel. A simple DrupalKernel reboot is not
1135 // sufficient, since the list of enabled modules might have been adjusted
1136 // above due to changed code.
1138 foreach ($module_data as $name => $extension) {
1139 if ($extension->status) {
1140 $files[$name] = $extension;
1143 \Drupal::service('kernel')->updateModules($module_handler->getModuleList(), $files);
1144 // New container, new module handler.
1145 $module_handler = \Drupal::moduleHandler();
1147 // Ensure that all modules that are currently supposed to be enabled are
1149 $module_handler->loadAll();
1151 // Rebuild all information based on new module data.
1152 $module_handler->invokeAll('rebuild');
1154 // Clear all plugin caches.
1155 \Drupal::service('plugin.cache_clearer')->clearCachedDefinitions();
1157 // Rebuild the menu router based on all rebuilt data.
1158 // Important: This rebuild must happen last, so the menu router is guaranteed
1159 // to be based on up to date information.
1160 \Drupal::service('router.builder')->rebuild();
1162 // Re-initialize the maintenance theme, if the current request attempted to
1163 // use it. Unlike regular usages of this function, the installer and update
1164 // scripts need to flush all caches during GET requests/page building.
1165 if (function_exists('_drupal_maintenance_theme')) {
1166 \Drupal::theme()->resetActiveTheme();
1167 drupal_maintenance_theme();
1172 * Changes the dummy query string added to all CSS and JavaScript files.
1174 * Changing the dummy query string appended to CSS and JavaScript files forces
1175 * all browsers to reload fresh files.
1177 function _drupal_flush_css_js() {
1178 // The timestamp is converted to base 36 in order to make it more compact.
1179 Drupal::state()->set('system.css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
1183 * Outputs debug information.
1185 * The debug information is passed on to trigger_error() after being converted
1186 * to a string using _drupal_debug_message().
1189 * Data to be output.
1191 * Label to prefix the data.
1193 * Flag to switch between print_r() and var_export() for data conversion to
1194 * string. Set $print_r to FALSE to use var_export() instead of print_r().
1195 * Passing recursive data structures to var_export() will generate an error.
1197 function debug($data, $label = NULL, $print_r = TRUE) {
1198 // Print $data contents to string.
1199 $string = Html::escape($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
1201 // Display values with pre-formatting to increase readability.
1202 $string = '<pre>' . $string . '</pre>';
1204 trigger_error(trim($label ? "$label: $string" : $string));
1208 * Checks whether a version is compatible with a given dependency.
1211 * A parsed dependency structure e.g. from ModuleHandler::parseDependency().
1212 * @param $current_version
1213 * The version to check against (like 4.2).
1216 * NULL if compatible, otherwise the original dependency version string that
1217 * caused the incompatibility.
1219 * @see \Drupal\Core\Extension\ModuleHandler::parseDependency()
1221 function drupal_check_incompatibility($v, $current_version) {
1222 if (!empty($v['versions'])) {
1223 foreach ($v['versions'] as $required_version) {
1224 if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
1225 return $v['original_version'];
1232 * Returns a string of supported archive extensions.
1235 * A space-separated string of extensions suitable for use by the file
1236 * validation system.
1238 function archiver_get_extensions() {
1239 $valid_extensions = [];
1240 foreach (\Drupal::service('plugin.manager.archiver')->getDefinitions() as $archive) {
1241 foreach ($archive['extensions'] as $extension) {
1242 foreach (explode('.', $extension) as $part) {
1243 if (!in_array($part, $valid_extensions)) {
1244 $valid_extensions[] = $part;
1249 return implode(' ', $valid_extensions);
1253 * Creates the appropriate archiver for the specified file.
1256 * The full path of the archive file. Note that stream wrapper paths are
1257 * supported, but not remote ones.
1260 * A newly created instance of the archiver class appropriate
1261 * for the specified file, already bound to that file.
1262 * If no appropriate archiver class was found, will return FALSE.
1264 function archiver_get_archiver($file) {
1265 // Archivers can only work on local paths
1266 $filepath = \Drupal::service('file_system')->realpath($file);
1267 if (!is_file($filepath)) {
1268 throw new Exception(t('Archivers can only operate on local files: %file not supported', ['%file' => $file]));
1270 return \Drupal::service('plugin.manager.archiver')->getInstance(['filepath' => $filepath]);
1274 * Assembles the Drupal Updater registry.
1276 * An Updater is a class that knows how to update various parts of the Drupal
1277 * file system, for example to update modules that have newer releases, or to
1278 * install a new theme.
1281 * The Drupal Updater class registry.
1283 * @see \Drupal\Core\Updater\Updater
1284 * @see hook_updater_info()
1285 * @see hook_updater_info_alter()
1287 function drupal_get_updaters() {
1288 $updaters = &drupal_static(__FUNCTION__);
1289 if (!isset($updaters)) {
1290 $updaters = \Drupal::moduleHandler()->invokeAll('updater_info');
1291 \Drupal::moduleHandler()->alter('updater_info', $updaters);
1292 uasort($updaters, [SortArray::class, 'sortByWeightElement']);
1298 * Assembles the Drupal FileTransfer registry.
1301 * The Drupal FileTransfer class registry.
1303 * @see \Drupal\Core\FileTransfer\FileTransfer
1304 * @see hook_filetransfer_info()
1305 * @see hook_filetransfer_info_alter()
1307 function drupal_get_filetransfer_info() {
1308 $info = &drupal_static(__FUNCTION__);
1309 if (!isset($info)) {
1310 $info = \Drupal::moduleHandler()->invokeAll('filetransfer_info');
1311 \Drupal::moduleHandler()->alter('filetransfer_info', $info);
1312 uasort($info, [SortArray::class, 'sortByWeightElement']);