Chris@0: getAsArray();
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * @defgroup validation Input validation
Chris@0: * @{
Chris@0: * Functions to validate user input.
Chris@0: */
Chris@0:
Chris@0: /**
Chris@0: * Verifies the syntax of the given email address.
Chris@0: *
Chris@0: * @param string $mail
Chris@0: * A string containing an email address.
Chris@0: *
Chris@0: * @return bool
Chris@0: * TRUE if the address is in a valid format.
Chris@0: *
Chris@0: * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
Chris@0: * Use \Drupal::service('email.validator')->isValid().
Chris@12: *
Chris@12: * @see https://www.drupal.org/node/2912661
Chris@0: */
Chris@0: function valid_email_address($mail) {
Chris@0: return \Drupal::service('email.validator')->isValid($mail);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * @} End of "defgroup validation".
Chris@0: */
Chris@0:
Chris@0: /**
Chris@0: * @defgroup sanitization Sanitization functions
Chris@0: * @{
Chris@0: * Functions to sanitize values.
Chris@0: *
Chris@0: * See https://www.drupal.org/writing-secure-code for information
Chris@0: * on writing secure code.
Chris@0: */
Chris@0:
Chris@0: /**
Chris@0: * Strips dangerous protocols from a URI and encodes it for output to HTML.
Chris@0: *
Chris@0: * @param $uri
Chris@0: * A plain-text URI that might contain dangerous protocols.
Chris@0: *
Chris@0: * @return string
Chris@0: * A URI stripped of dangerous protocols and encoded for output to an HTML
Chris@0: * attribute value. Because it is already encoded, it should not be set as a
Chris@0: * value within a $attributes array passed to Drupal\Core\Template\Attribute,
Chris@0: * because Drupal\Core\Template\Attribute expects those values to be
Chris@0: * plain-text strings. To pass a filtered URI to
Chris@0: * Drupal\Core\Template\Attribute, call
Chris@0: * \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() instead.
Chris@0: *
Chris@18: * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
Chris@0: * Use UrlHelper::stripDangerousProtocols() or UrlHelper::filterBadProtocol()
Chris@0: * instead. UrlHelper::stripDangerousProtocols() can be used in conjunction
Chris@17: * with \Drupal\Component\Render\FormattableMarkup and an @variable
Chris@0: * placeholder which will perform the necessary escaping.
Chris@0: * UrlHelper::filterBadProtocol() is functionality equivalent to check_url()
Chris@0: * apart from the fact it is protected from double escaping bugs. Note that
Chris@0: * this method no longer marks its output as safe.
Chris@12: *
Chris@12: * @see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols()
Chris@12: * @see \Drupal\Component\Utility\UrlHelper::filterBadProtocol()
Chris@12: * @see https://www.drupal.org/node/2560027
Chris@0: */
Chris@0: function check_url($uri) {
Chris@18: @trigger_error(__FUNCTION__ . '() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use UrlHelper::stripDangerousProtocols() or UrlHelper::filterBadProtocol() instead. See https://www.drupal.org/node/2560027', E_USER_DEPRECATED);
Chris@0: return Html::escape(UrlHelper::stripDangerousProtocols($uri));
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * @} End of "defgroup sanitization".
Chris@0: */
Chris@0:
Chris@0: /**
Chris@0: * @defgroup format Formatting
Chris@0: * @{
Chris@0: * Functions to format numbers, strings, dates, etc.
Chris@0: */
Chris@0:
Chris@0: /**
Chris@0: * Generates a string representation for the given byte count.
Chris@0: *
Chris@0: * @param $size
Chris@0: * A size in bytes.
Chris@0: * @param $langcode
Chris@0: * Optional language code to translate to a language other than what is used
Chris@0: * to display the page.
Chris@0: *
Chris@0: * @return \Drupal\Core\StringTranslation\TranslatableMarkup
Chris@0: * A translated string representation of the size.
Chris@0: */
Chris@0: function format_size($size, $langcode = NULL) {
Chris@17: $absolute_size = abs($size);
Chris@17: if ($absolute_size < Bytes::KILOBYTE) {
Chris@0: return \Drupal::translation()->formatPlural($size, '1 byte', '@count bytes', [], ['langcode' => $langcode]);
Chris@0: }
Chris@17: // Create a multiplier to preserve the sign of $size.
Chris@17: $sign = $absolute_size / $size;
Chris@17: foreach (['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] as $unit) {
Chris@17: $absolute_size /= Bytes::KILOBYTE;
Chris@17: $rounded_size = round($absolute_size, 2);
Chris@17: if ($rounded_size < Bytes::KILOBYTE) {
Chris@17: break;
Chris@0: }
Chris@17: }
Chris@17: $args = ['@size' => $rounded_size * $sign];
Chris@17: $options = ['langcode' => $langcode];
Chris@17: switch ($unit) {
Chris@17: case 'KB':
Chris@17: return new TranslatableMarkup('@size KB', $args, $options);
Chris@17:
Chris@17: case 'MB':
Chris@17: return new TranslatableMarkup('@size MB', $args, $options);
Chris@17:
Chris@17: case 'GB':
Chris@17: return new TranslatableMarkup('@size GB', $args, $options);
Chris@17:
Chris@17: case 'TB':
Chris@17: return new TranslatableMarkup('@size TB', $args, $options);
Chris@17:
Chris@17: case 'PB':
Chris@17: return new TranslatableMarkup('@size PB', $args, $options);
Chris@17:
Chris@17: case 'EB':
Chris@17: return new TranslatableMarkup('@size EB', $args, $options);
Chris@17:
Chris@17: case 'ZB':
Chris@17: return new TranslatableMarkup('@size ZB', $args, $options);
Chris@17:
Chris@17: case 'YB':
Chris@17: return new TranslatableMarkup('@size YB', $args, $options);
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Formats a date, using a date type or a custom date format string.
Chris@0: *
Chris@0: * @param $timestamp
Chris@0: * A UNIX timestamp to format.
Chris@0: * @param $type
Chris@0: * (optional) The format to use, one of:
Chris@0: * - One of the built-in formats: 'short', 'medium',
Chris@0: * 'long', 'html_datetime', 'html_date', 'html_time',
Chris@0: * 'html_yearless_date', 'html_week', 'html_month', 'html_year'.
Chris@0: * - The name of a date type defined by a date format config entity.
Chris@0: * - The machine name of an administrator-defined date format.
Chris@0: * - 'custom', to use $format.
Chris@0: * Defaults to 'medium'.
Chris@0: * @param $format
Chris@0: * (optional) If $type is 'custom', a PHP date format string suitable for
Chris@0: * input to date(). Use a backslash to escape ordinary text, so it does not
Chris@0: * get interpreted as date format characters.
Chris@0: * @param $timezone
Chris@0: * (optional) Time zone identifier, as described at
Chris@0: * http://php.net/manual/timezones.php Defaults to the time zone used to
Chris@0: * display the page.
Chris@0: * @param $langcode
Chris@0: * (optional) Language code to translate to. Defaults to the language used to
Chris@0: * display the page.
Chris@0: *
Chris@0: * @return
Chris@0: * A translated date string in the requested format.
Chris@0: *
Chris@0: * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
Chris@0: * Use \Drupal::service('date.formatter')->format().
Chris@12: *
Chris@12: * @see \Drupal\Core\Datetime\DateFormatter::format()
Chris@12: * @see https://www.drupal.org/node/1876852
Chris@0: */
Chris@0: function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
Chris@18: @trigger_error("format_date() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal::service('date.formatter')->format() instead. See https://www.drupal.org/node/1876852", E_USER_DEPRECATED);
Chris@0: return \Drupal::service('date.formatter')->format($timestamp, $type, $format, $timezone, $langcode);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Returns an ISO8601 formatted date based on the given date.
Chris@0: *
Chris@18: * @param string $date
Chris@0: * A UNIX timestamp.
Chris@0: *
Chris@0: * @return string
Chris@0: * An ISO8601 formatted date.
Chris@18: *
Chris@18: * @deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use
Chris@18: * date('c', $date) instead.
Chris@18: *
Chris@18: * @see https://www.drupal.org/node/2999991
Chris@0: */
Chris@0: function date_iso8601($date) {
Chris@18: @trigger_error('date_iso8601() is deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use date("c", $date) instead. See https://www.drupal.org/node/2999991.', E_USER_DEPRECATED);
Chris@0: // The DATE_ISO8601 constant cannot be used here because it does not match
Chris@0: // date('c') and produces invalid RDF markup.
Chris@0: return date('c', $date);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * @} End of "defgroup format".
Chris@0: */
Chris@0:
Chris@0: /**
Chris@0: * Formats an attribute string for an HTTP header.
Chris@0: *
Chris@18: * @param array $attributes
Chris@0: * An associative array of attributes such as 'rel'.
Chris@0: *
Chris@18: * @return string
Chris@0: * A ; separated string ready for insertion in a HTTP header. No escaping is
Chris@0: * performed for HTML entities, so this string is not safe to be printed.
Chris@18: *
Chris@18: * @deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use
Chris@18: * \Drupal\Core\Render\HtmlResponseAttachmentsProcessor::formatHttpHeaderAttributes()
Chris@18: * instead.
Chris@18: *
Chris@18: * @see https://www.drupal.org/node/3000051
Chris@0: */
Chris@0: function drupal_http_header_attributes(array $attributes = []) {
Chris@18: @trigger_error("drupal_http_header_attributes() is deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\Render\HtmlResponseAttachmentsProcessor::formatHttpHeaderAttributes() instead. See https://www.drupal.org/node/3000051", E_USER_DEPRECATED);
Chris@18: return HtmlResponseAttachmentsProcessor::formatHttpHeaderAttributes($attributes);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Attempts to set the PHP maximum execution time.
Chris@0: *
Chris@0: * This function is a wrapper around the PHP function set_time_limit().
Chris@0: * When called, set_time_limit() restarts the timeout counter from zero.
Chris@0: * In other words, if the timeout is the default 30 seconds, and 25 seconds
Chris@0: * into script execution a call such as set_time_limit(20) is made, the
Chris@0: * script will run for a total of 45 seconds before timing out.
Chris@0: *
Chris@0: * If the current time limit is not unlimited it is possible to decrease the
Chris@0: * total time limit if the sum of the new time limit and the current time spent
Chris@0: * running the script is inferior to the original time limit. It is inherent to
Chris@0: * the way set_time_limit() works, it should rather be called with an
Chris@0: * appropriate value every time you need to allocate a certain amount of time
Chris@0: * to execute a task than only once at the beginning of the script.
Chris@0: *
Chris@0: * Before calling set_time_limit(), we check if this function is available
Chris@0: * because it could be disabled by the server administrator. We also hide all
Chris@0: * the errors that could occur when calling set_time_limit(), because it is
Chris@0: * not possible to reliably ensure that PHP or a security extension will
Chris@0: * not issue a warning/error if they prevent the use of this function.
Chris@0: *
Chris@0: * @param $time_limit
Chris@0: * An integer specifying the new time limit, in seconds. A value of 0
Chris@0: * indicates unlimited execution time.
Chris@0: *
Chris@0: * @ingroup php_wrappers
Chris@18: *
Chris@18: * @deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use
Chris@18: * \Drupal\Core\Environment::setTimeLimit() instead.
Chris@18: *
Chris@18: * @see https://www.drupal.org/node/3000058
Chris@0: */
Chris@0: function drupal_set_time_limit($time_limit) {
Chris@18: @trigger_error('drupal_set_time_limit() is deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\Environment::setTimeLimit() instead. See https://www.drupal.org/node/3000058.', E_USER_DEPRECATED);
Chris@18: Environment::setTimeLimit($time_limit);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Returns the base URL path (i.e., directory) of the Drupal installation.
Chris@0: *
Chris@17: * Function base_path() adds a "/" to the beginning and end of the returned path
Chris@17: * if the path is not empty. At the very least, this will return "/".
Chris@0: *
Chris@0: * Examples:
Chris@0: * - http://example.com returns "/" because the path is empty.
Chris@0: * - http://example.com/drupal/folder returns "/drupal/folder/".
Chris@0: */
Chris@0: function base_path() {
Chris@0: return $GLOBALS['base_path'];
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Deletes old cached CSS files.
Chris@0: *
Chris@0: * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
Chris@0: * Use \Drupal\Core\Asset\AssetCollectionOptimizerInterface::deleteAll().
Chris@12: *
Chris@12: * @see https://www.drupal.org/node/2317841
Chris@0: */
Chris@0: function drupal_clear_css_cache() {
Chris@0: \Drupal::service('asset.css.collection_optimizer')->deleteAll();
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Constructs an array of the defaults that are used for JavaScript assets.
Chris@0: *
Chris@0: * @param $data
Chris@0: * (optional) The default data parameter for the JavaScript asset array.
Chris@0: *
Chris@0: * @see hook_js_alter()
Chris@0: */
Chris@0: function drupal_js_defaults($data = NULL) {
Chris@0: return [
Chris@0: 'type' => 'file',
Chris@0: 'group' => JS_DEFAULT,
Chris@0: 'weight' => 0,
Chris@0: 'scope' => 'header',
Chris@0: 'cache' => TRUE,
Chris@0: 'preprocess' => TRUE,
Chris@0: 'attributes' => [],
Chris@0: 'version' => NULL,
Chris@0: 'data' => $data,
Chris@0: 'browsers' => [],
Chris@0: ];
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Adds JavaScript to change the state of an element based on another element.
Chris@0: *
Chris@0: * A "state" means a certain property on a DOM element, such as "visible" or
Chris@0: * "checked". A state can be applied to an element, depending on the state of
Chris@0: * another element on the page. In general, states depend on HTML attributes and
Chris@0: * DOM element properties, which change due to user interaction.
Chris@0: *
Chris@0: * Since states are driven by JavaScript only, it is important to understand
Chris@0: * that all states are applied on presentation only, none of the states force
Chris@0: * any server-side logic, and that they will not be applied for site visitors
Chris@0: * without JavaScript support. All modules implementing states have to make
Chris@0: * sure that the intended logic also works without JavaScript being enabled.
Chris@0: *
Chris@0: * #states is an associative array in the form of:
Chris@0: * @code
Chris@0: * array(
Chris@0: * STATE1 => CONDITIONS_ARRAY1,
Chris@0: * STATE2 => CONDITIONS_ARRAY2,
Chris@0: * ...
Chris@0: * )
Chris@0: * @endcode
Chris@0: * Each key is the name of a state to apply to the element, such as 'visible'.
Chris@0: * Each value is a list of conditions that denote when the state should be
Chris@0: * applied.
Chris@0: *
Chris@0: * Multiple different states may be specified to act on complex conditions:
Chris@0: * @code
Chris@0: * array(
Chris@0: * 'visible' => CONDITIONS,
Chris@0: * 'checked' => OTHER_CONDITIONS,
Chris@0: * )
Chris@0: * @endcode
Chris@0: *
Chris@0: * Every condition is a key/value pair, whose key is a jQuery selector that
Chris@0: * denotes another element on the page, and whose value is an array of
Chris@17: * conditions, which must be met on that element:
Chris@0: * @code
Chris@0: * array(
Chris@0: * 'visible' => array(
Chris@0: * JQUERY_SELECTOR => REMOTE_CONDITIONS,
Chris@0: * JQUERY_SELECTOR => REMOTE_CONDITIONS,
Chris@0: * ...
Chris@0: * ),
Chris@0: * )
Chris@0: * @endcode
Chris@0: * All conditions must be met for the state to be applied.
Chris@0: *
Chris@0: * Each remote condition is a key/value pair specifying conditions on the other
Chris@0: * element that need to be met to apply the state to the element:
Chris@0: * @code
Chris@0: * array(
Chris@0: * 'visible' => array(
Chris@0: * ':input[name="remote_checkbox"]' => array('checked' => TRUE),
Chris@0: * ),
Chris@0: * )
Chris@0: * @endcode
Chris@0: *
Chris@0: * For example, to show a textfield only when a checkbox is checked:
Chris@0: * @code
Chris@0: * $form['toggle_me'] = array(
Chris@0: * '#type' => 'checkbox',
Chris@0: * '#title' => t('Tick this box to type'),
Chris@0: * );
Chris@0: * $form['settings'] = array(
Chris@0: * '#type' => 'textfield',
Chris@0: * '#states' => array(
Chris@0: * // Only show this field when the 'toggle_me' checkbox is enabled.
Chris@0: * 'visible' => array(
Chris@0: * ':input[name="toggle_me"]' => array('checked' => TRUE),
Chris@0: * ),
Chris@0: * ),
Chris@0: * );
Chris@0: * @endcode
Chris@0: *
Chris@0: * The following states may be applied to an element:
Chris@0: * - enabled
Chris@0: * - disabled
Chris@0: * - required
Chris@0: * - optional
Chris@0: * - visible
Chris@0: * - invisible
Chris@0: * - checked
Chris@0: * - unchecked
Chris@0: * - expanded
Chris@0: * - collapsed
Chris@0: *
Chris@0: * The following states may be used in remote conditions:
Chris@0: * - empty
Chris@0: * - filled
Chris@0: * - checked
Chris@0: * - unchecked
Chris@0: * - expanded
Chris@0: * - collapsed
Chris@0: * - value
Chris@0: *
Chris@0: * The following states exist for both elements and remote conditions, but are
Chris@0: * not fully implemented and may not change anything on the element:
Chris@0: * - relevant
Chris@0: * - irrelevant
Chris@0: * - valid
Chris@0: * - invalid
Chris@0: * - touched
Chris@0: * - untouched
Chris@0: * - readwrite
Chris@0: * - readonly
Chris@0: *
Chris@0: * When referencing select lists and radio buttons in remote conditions, a
Chris@0: * 'value' condition must be used:
Chris@0: * @code
Chris@0: * '#states' => array(
Chris@0: * // Show the settings if 'bar' has been selected for 'foo'.
Chris@0: * 'visible' => array(
Chris@0: * ':input[name="foo"]' => array('value' => 'bar'),
Chris@0: * ),
Chris@0: * ),
Chris@0: * @endcode
Chris@0: *
Chris@0: * @param $elements
Chris@0: * A renderable array element having a #states property as described above.
Chris@0: *
Chris@0: * @see form_example_states_form()
Chris@0: */
Chris@0: function drupal_process_states(&$elements) {
Chris@0: $elements['#attached']['library'][] = 'core/drupal.states';
Chris@0: // Elements of '#type' => 'item' are not actual form input elements, but we
Chris@0: // still want to be able to show/hide them. Since there's no actual HTML input
Chris@0: // element available, setting #attributes does not make sense, but a wrapper
Chris@0: // is available, so setting #wrapper_attributes makes it work.
Chris@0: $key = ($elements['#type'] == 'item') ? '#wrapper_attributes' : '#attributes';
Chris@0: $elements[$key]['data-drupal-states'] = Json::encode($elements['#states']);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Assists in attaching the tableDrag JavaScript behavior to a themed table.
Chris@0: *
Chris@0: * Draggable tables should be used wherever an outline or list of sortable items
Chris@0: * needs to be arranged by an end-user. Draggable tables are very flexible and
Chris@0: * can manipulate the value of form elements placed within individual columns.
Chris@0: *
Chris@0: * To set up a table to use drag and drop in place of weight select-lists or in
Chris@0: * place of a form that contains parent relationships, the form must be themed
Chris@0: * into a table. The table must have an ID attribute set and it
Chris@0: * may be set as follows:
Chris@0: * @code
Chris@0: * $table = array(
Chris@0: * '#type' => 'table',
Chris@0: * '#header' => $header,
Chris@0: * '#rows' => $rows,
Chris@0: * '#attributes' => array(
Chris@0: * 'id' => 'my-module-table',
Chris@0: * ),
Chris@0: * );
Chris@16: * return \Drupal::service('renderer')->render($table);
Chris@0: * @endcode
Chris@0: *
Chris@0: * In the theme function for the form, a special class must be added to each
Chris@0: * form element within the same column, "grouping" them together.
Chris@0: *
Chris@0: * In a situation where a single weight column is being sorted in the table, the
Chris@0: * classes could be added like this (in the theme function):
Chris@0: * @code
Chris@0: * $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
Chris@0: * @endcode
Chris@0: *
Chris@0: * Each row of the table must also have a class of "draggable" in order to
Chris@0: * enable the drag handles:
Chris@0: * @code
Chris@0: * $row = array(...);
Chris@0: * $rows[] = array(
Chris@0: * 'data' => $row,
Chris@0: * 'class' => array('draggable'),
Chris@0: * );
Chris@0: * @endcode
Chris@0: *
Chris@0: * When tree relationships are present, the two additional classes
Chris@0: * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
Chris@0: * - Rows with the 'tabledrag-leaf' class cannot have child rows.
Chris@0: * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
Chris@0: *
Chris@0: * Calling drupal_attach_tabledrag() would then be written as such:
Chris@0: * @code
Chris@0: * drupal_attach_tabledrag('my-module-table', array(
Chris@0: * 'action' => 'order',
Chris@0: * 'relationship' => 'sibling',
Chris@0: * 'group' => 'my-elements-weight',
Chris@0: * );
Chris@0: * @endcode
Chris@0: *
Chris@0: * In a more complex case where there are several groups in one column (such as
Chris@0: * the block regions on the admin/structure/block page), a separate subgroup
Chris@0: * class must also be added to differentiate the groups.
Chris@0: * @code
Chris@0: * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
Chris@0: * @endcode
Chris@0: *
Chris@0: * The 'group' option is still 'my-element-weight', and the additional
Chris@0: * 'subgroup' option will be passed in as 'my-elements-weight-' . $region. This
Chris@0: * also means that you'll need to call drupal_attach_tabledrag() once for every
Chris@0: * region added.
Chris@0: *
Chris@0: * @code
Chris@0: * foreach ($regions as $region) {
Chris@0: * drupal_attach_tabledrag('my-module-table', array(
Chris@0: * 'action' => 'order',
Chris@0: * 'relationship' => 'sibling',
Chris@0: * 'group' => 'my-elements-weight',
Chris@0: * 'subgroup' => 'my-elements-weight-' . $region,
Chris@0: * ));
Chris@0: * }
Chris@0: * @endcode
Chris@0: *
Chris@0: * In a situation where tree relationships are present, adding multiple
Chris@0: * subgroups is not necessary, because the table will contain indentations that
Chris@0: * provide enough information about the sibling and parent relationships. See
Chris@0: * MenuForm::BuildOverviewForm for an example creating a table
Chris@0: * containing parent relationships.
Chris@0: *
Chris@0: * @param $element
Chris@0: * A form element to attach the tableDrag behavior to.
Chris@0: * @param array $options
Chris@0: * These options are used to generate JavaScript settings necessary to
Chris@0: * configure the tableDrag behavior appropriately for this particular table.
Chris@0: * An associative array containing the following keys:
Chris@0: * - 'table_id': String containing the target table's id attribute.
Chris@0: * If the table does not have an id, one will need to be set,
Chris@0: * such as
.
Chris@0: * - 'action': String describing the action to be done on the form item.
Chris@0: * Either 'match' 'depth', or 'order':
Chris@0: * - 'match' is typically used for parent relationships.
Chris@0: * - 'order' is typically used to set weights on other form elements with
Chris@0: * the same group.
Chris@0: * - 'depth' updates the target element with the current indentation.
Chris@0: * - 'relationship': String describing where the "action" option
Chris@0: * should be performed. Either 'parent', 'sibling', 'group', or 'self':
Chris@0: * - 'parent' will only look for fields up the tree.
Chris@0: * - 'sibling' will look for fields in the same group in rows above and
Chris@0: * below it.
Chris@0: * - 'self' affects the dragged row itself.
Chris@0: * - 'group' affects the dragged row, plus any children below it (the entire
Chris@0: * dragged group).
Chris@0: * - 'group': A class name applied on all related form elements for this action.
Chris@0: * - 'subgroup': (optional) If the group has several subgroups within it, this
Chris@0: * string should contain the class name identifying fields in the same
Chris@0: * subgroup.
Chris@0: * - 'source': (optional) If the $action is 'match', this string should contain
Chris@0: * the classname identifying what field will be used as the source value
Chris@0: * when matching the value in $subgroup.
Chris@0: * - 'hidden': (optional) The column containing the field elements may be
Chris@0: * entirely hidden from view dynamically when the JavaScript is loaded. Set
Chris@0: * to FALSE if the column should not be hidden.
Chris@0: * - 'limit': (optional) Limit the maximum amount of parenting in this table.
Chris@0: *
Chris@0: * @see MenuForm::BuildOverviewForm()
Chris@0: */
Chris@0: function drupal_attach_tabledrag(&$element, array $options) {
Chris@0: // Add default values to elements.
Chris@0: $options = $options + [
Chris@0: 'subgroup' => NULL,
Chris@0: 'source' => NULL,
Chris@0: 'hidden' => TRUE,
Chris@17: 'limit' => 0,
Chris@0: ];
Chris@0:
Chris@0: $group = $options['group'];
Chris@0:
Chris@0: $tabledrag_id = &drupal_static(__FUNCTION__);
Chris@0: $tabledrag_id = (!isset($tabledrag_id)) ? 0 : $tabledrag_id + 1;
Chris@0:
Chris@0: // If a subgroup or source isn't set, assume it is the same as the group.
Chris@0: $target = isset($options['subgroup']) ? $options['subgroup'] : $group;
Chris@0: $source = isset($options['source']) ? $options['source'] : $target;
Chris@0: $element['#attached']['drupalSettings']['tableDrag'][$options['table_id']][$group][$tabledrag_id] = [
Chris@0: 'target' => $target,
Chris@0: 'source' => $source,
Chris@0: 'relationship' => $options['relationship'],
Chris@0: 'action' => $options['action'],
Chris@0: 'hidden' => $options['hidden'],
Chris@0: 'limit' => $options['limit'],
Chris@0: ];
Chris@0:
Chris@0: $element['#attached']['library'][] = 'core/drupal.tabledrag';
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Deletes old cached JavaScript files and variables.
Chris@0: *
Chris@0: * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
Chris@0: * Use \Drupal\Core\Asset\AssetCollectionOptimizerInterface::deleteAll().
Chris@12: *
Chris@12: * @see https://www.drupal.org/node/2317841
Chris@0: */
Chris@0: function drupal_clear_js_cache() {
Chris@0: \Drupal::service('asset.js.collection_optimizer')->deleteAll();
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Pre-render callback: Renders a link into #markup.
Chris@0: *
Chris@0: * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
Chris@0: * Use \Drupal\Core\Render\Element\Link::preRenderLink().
Chris@0: */
Chris@0: function drupal_pre_render_link($element) {
Chris@0: return Link::preRenderLink($element);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Pre-render callback: Collects child links into a single array.
Chris@0: *
Chris@0: * This function can be added as a pre_render callback for a renderable array,
Chris@0: * usually one which will be themed by links.html.twig. It iterates through all
Chris@0: * unrendered children of the element, collects any #links properties it finds,
Chris@0: * merges them into the parent element's #links array, and prevents those
Chris@0: * children from being rendered separately.
Chris@0: *
Chris@0: * The purpose of this is to allow links to be logically grouped into related
Chris@0: * categories, so that each child group can be rendered as its own list of
Chris@0: * links if drupal_render() is called on it, but calling drupal_render() on the
Chris@0: * parent element will still produce a single list containing all the remaining
Chris@0: * links, regardless of what group they were in.
Chris@0: *
Chris@0: * A typical example comes from node links, which are stored in a renderable
Chris@0: * array similar to this:
Chris@0: * @code
Chris@0: * $build['links'] = array(
Chris@0: * '#theme' => 'links__node',
Chris@0: * '#pre_render' => array('drupal_pre_render_links'),
Chris@0: * 'comment' => array(
Chris@0: * '#theme' => 'links__node__comment',
Chris@0: * '#links' => array(
Chris@0: * // An array of links associated with node comments, suitable for
Chris@0: * // passing in to links.html.twig.
Chris@0: * ),
Chris@0: * ),
Chris@0: * 'statistics' => array(
Chris@0: * '#theme' => 'links__node__statistics',
Chris@0: * '#links' => array(
Chris@0: * // An array of links associated with node statistics, suitable for
Chris@0: * // passing in to links.html.twig.
Chris@0: * ),
Chris@0: * ),
Chris@0: * 'translation' => array(
Chris@0: * '#theme' => 'links__node__translation',
Chris@0: * '#links' => array(
Chris@0: * // An array of links associated with node translation, suitable for
Chris@0: * // passing in to links.html.twig.
Chris@0: * ),
Chris@0: * ),
Chris@0: * );
Chris@0: * @endcode
Chris@0: *
Chris@0: * In this example, the links are grouped by functionality, which can be
Chris@0: * helpful to themers who want to display certain kinds of links independently.
Chris@0: * For example, adding this code to node.html.twig will result in the comment
Chris@0: * links being rendered as a single list:
Chris@0: * @code
Chris@0: * {{ content.links.comment }}
Chris@0: * @endcode
Chris@0: *
Chris@0: * (where a node's content has been transformed into $content before handing
Chris@0: * control to the node.html.twig template).
Chris@0: *
Chris@0: * The pre_render function defined here allows the above flexibility, but also
Chris@0: * allows the following code to be used to render all remaining links into a
Chris@0: * single list, regardless of their group:
Chris@0: * @code
Chris@0: * {{ content.links }}
Chris@0: * @endcode
Chris@0: *
Chris@0: * In the above example, this will result in the statistics and translation
Chris@0: * links being rendered together in a single list (but not the comment links,
Chris@0: * which were rendered previously on their own).
Chris@0: *
Chris@0: * Because of the way this function works, the individual properties of each
Chris@0: * group (for example, a group-specific #theme property such as
Chris@0: * 'links__node__comment' in the example above, or any other property such as
Chris@0: * #attributes or #pre_render that is attached to it) are only used when that
Chris@0: * group is rendered on its own. When the group is rendered together with other
Chris@0: * children, these child-specific properties are ignored, and only the overall
Chris@0: * properties of the parent are used.
Chris@0: */
Chris@0: function drupal_pre_render_links($element) {
Chris@0: $element += ['#links' => [], '#attached' => []];
Chris@0: foreach (Element::children($element) as $key) {
Chris@0: $child = &$element[$key];
Chris@0: // If the child has links which have not been printed yet and the user has
Chris@0: // access to it, merge its links in to the parent.
Chris@0: if (isset($child['#links']) && empty($child['#printed']) && Element::isVisibleElement($child)) {
Chris@0: $element['#links'] += $child['#links'];
Chris@0: // Mark the child as having been printed already (so that its links
Chris@0: // cannot be mistakenly rendered twice).
Chris@0: $child['#printed'] = TRUE;
Chris@0: }
Chris@0: // Merge attachments.
Chris@0: if (isset($child['#attached'])) {
Chris@0: $element['#attached'] = BubbleableMetadata::mergeAttachments($element['#attached'], $child['#attached']);
Chris@0: }
Chris@0: }
Chris@0: return $element;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Renders final HTML given a structured array tree.
Chris@0: *
Chris@0: * @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0. Use the
Chris@0: * 'renderer' service instead.
Chris@0: *
Chris@0: * @see \Drupal\Core\Render\RendererInterface::renderRoot()
Chris@12: * @see https://www.drupal.org/node/2912696
Chris@0: */
Chris@0: function drupal_render_root(&$elements) {
Chris@0: return \Drupal::service('renderer')->renderRoot($elements);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Renders HTML given a structured array tree.
Chris@0: *
Chris@0: * @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0. Use the
Chris@0: * 'renderer' service instead.
Chris@0: *
Chris@0: * @see \Drupal\Core\Render\RendererInterface::render()
Chris@12: * @see https://www.drupal.org/node/2912696
Chris@0: */
Chris@0: function drupal_render(&$elements, $is_recursive_call = FALSE) {
Chris@0: return \Drupal::service('renderer')->render($elements, $is_recursive_call);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Renders children of an element and concatenates them.
Chris@0: *
Chris@0: * @param array $element
Chris@0: * The structured array whose children shall be rendered.
Chris@0: * @param array $children_keys
Chris@0: * (optional) If the keys of the element's children are already known, they
Chris@0: * can be passed in to save another run of
Chris@0: * \Drupal\Core\Render\Element::children().
Chris@0: *
Chris@0: * @return string|\Drupal\Component\Render\MarkupInterface
Chris@0: * The rendered HTML of all children of the element.
Chris@0: *
Chris@0: * @deprecated in Drupal 8.0.x and will be removed before 9.0.0. Avoid early
Chris@0: * rendering when possible or loop through the elements and render them as
Chris@0: * they are available.
Chris@0: *
Chris@16: * @see \Drupal\Core\Render\RendererInterface::render()
Chris@12: * @see https://www.drupal.org/node/2912757
Chris@0: */
Chris@0: function drupal_render_children(&$element, $children_keys = NULL) {
Chris@0: if ($children_keys === NULL) {
Chris@0: $children_keys = Element::children($element);
Chris@0: }
Chris@0: $output = '';
Chris@0: foreach ($children_keys as $key) {
Chris@0: if (!empty($element[$key])) {
Chris@0: $output .= \Drupal::service('renderer')->render($element[$key]);
Chris@0: }
Chris@0: }
Chris@0: return Markup::create($output);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Renders an element.
Chris@0: *
Chris@0: * This function renders an element. The top level element is shown with show()
Chris@0: * before rendering, so it will always be rendered even if hide() had been
Chris@0: * previously used on it.
Chris@0: *
Chris@0: * @param $element
Chris@0: * The element to be rendered.
Chris@0: *
Chris@0: * @return
Chris@0: * The rendered element.
Chris@0: *
Chris@0: * @see \Drupal\Core\Render\RendererInterface
Chris@0: * @see show()
Chris@0: * @see hide()
Chris@0: */
Chris@0: function render(&$element) {
Chris@0: if (!$element && $element !== 0) {
Chris@0: return NULL;
Chris@0: }
Chris@0: if (is_array($element)) {
Chris@0: // Early return if this element was pre-rendered (no need to re-render).
Chris@0: if (isset($element['#printed']) && $element['#printed'] == TRUE && isset($element['#markup']) && strlen($element['#markup']) > 0) {
Chris@0: return $element['#markup'];
Chris@0: }
Chris@0: show($element);
Chris@0: return \Drupal::service('renderer')->render($element);
Chris@0: }
Chris@0: else {
Chris@0: // Safe-guard for inappropriate use of render() on flat variables: return
Chris@0: // the variable as-is.
Chris@0: return $element;
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Hides an element from later rendering.
Chris@0: *
Chris@0: * The first time render() or drupal_render() is called on an element tree,
Chris@0: * as each element in the tree is rendered, it is marked with a #printed flag
Chris@0: * and the rendered children of the element are cached. Subsequent calls to
Chris@0: * render() or drupal_render() will not traverse the child tree of this element
Chris@0: * again: they will just use the cached children. So if you want to hide an
Chris@0: * element, be sure to call hide() on the element before its parent tree is
Chris@0: * rendered for the first time, as it will have no effect on subsequent
Chris@0: * renderings of the parent tree.
Chris@0: *
Chris@0: * @param $element
Chris@0: * The element to be hidden.
Chris@0: *
Chris@0: * @return
Chris@0: * The element.
Chris@0: *
Chris@0: * @see render()
Chris@0: * @see show()
Chris@0: */
Chris@0: function hide(&$element) {
Chris@0: $element['#printed'] = TRUE;
Chris@0: return $element;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Shows a hidden element for later rendering.
Chris@0: *
Chris@0: * You can also use render($element), which shows the element while rendering
Chris@0: * it.
Chris@0: *
Chris@0: * The first time render() or drupal_render() is called on an element tree,
Chris@0: * as each element in the tree is rendered, it is marked with a #printed flag
Chris@0: * and the rendered children of the element are cached. Subsequent calls to
Chris@0: * render() or drupal_render() will not traverse the child tree of this element
Chris@0: * again: they will just use the cached children. So if you want to show an
Chris@0: * element, be sure to call show() on the element before its parent tree is
Chris@0: * rendered for the first time, as it will have no effect on subsequent
Chris@0: * renderings of the parent tree.
Chris@0: *
Chris@0: * @param $element
Chris@0: * The element to be shown.
Chris@0: *
Chris@0: * @return
Chris@0: * The element.
Chris@0: *
Chris@0: * @see render()
Chris@0: * @see hide()
Chris@0: */
Chris@0: function show(&$element) {
Chris@0: $element['#printed'] = FALSE;
Chris@0: return $element;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Retrieves the default properties for the defined element type.
Chris@0: *
Chris@0: * @param $type
Chris@0: * An element type as defined by an element plugin.
Chris@0: *
Chris@0: * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
Chris@0: * Use \Drupal::service('element_info')->getInfo() instead.
Chris@12: *
Chris@12: * @see https://www.drupal.org/node/2235461
Chris@0: */
Chris@0: function element_info($type) {
Chris@0: return \Drupal::service('element_info')->getInfo($type);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Retrieves a single property for the defined element type.
Chris@0: *
Chris@0: * @param $type
Chris@0: * An element type as defined by an element plugin.
Chris@0: * @param $property_name
Chris@0: * The property within the element type that should be returned.
Chris@0: * @param $default
Chris@0: * (Optional) The value to return if the element type does not specify a
Chris@0: * value for the property. Defaults to NULL.
Chris@0: *
Chris@0: * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
Chris@0: * Use \Drupal::service('element_info')->getInfoProperty() instead.
Chris@12: *
Chris@12: * @see https://www.drupal.org/node/2235461
Chris@0: */
Chris@0: function element_info_property($type, $property_name, $default = NULL) {
Chris@0: return \Drupal::service('element_info')->getInfoProperty($type, $property_name, $default);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Flushes all persistent caches, resets all variables, and rebuilds all data structures.
Chris@0: *
Chris@0: * At times, it is necessary to re-initialize the entire system to account for
Chris@0: * changed or new code. This function:
Chris@0: * - Clears all persistent caches:
Chris@0: * - The bootstrap cache bin containing base system, module system, and theme
Chris@0: * system information.
Chris@0: * - The common 'default' cache bin containing arbitrary caches.
Chris@0: * - The page cache.
Chris@0: * - The URL alias path cache.
Chris@0: * - Resets all static variables that have been defined via drupal_static().
Chris@0: * - Clears asset (JS/CSS) file caches.
Chris@0: * - Updates the system with latest information about extensions (modules and
Chris@0: * themes).
Chris@0: * - Updates the bootstrap flag for modules implementing bootstrap_hooks().
Chris@0: * - Rebuilds the full database schema information (invoking hook_schema()).
Chris@0: * - Rebuilds data structures of all modules (invoking hook_rebuild()). In
Chris@0: * core this means
Chris@0: * - blocks, node types, date formats and actions are synchronized with the
Chris@0: * database
Chris@0: * - The 'active' status of fields is refreshed.
Chris@0: * - Rebuilds the menu router.
Chris@0: *
Chris@0: * This means the entire system is reset so all caches and static variables are
Chris@0: * effectively empty. After that is guaranteed, information about the currently
Chris@0: * active code is updated, and rebuild operations are successively called in
Chris@0: * order to synchronize the active system according to the current information
Chris@0: * defined in code.
Chris@0: *
Chris@0: * All modules need to ensure that all of their caches are flushed when
Chris@0: * hook_cache_flush() is invoked; any previously known information must no
Chris@0: * longer exist. All following hook_rebuild() operations must be based on fresh
Chris@0: * and current system data. All modules must be able to rely on this contract.
Chris@0: *
Chris@0: * @see \Drupal\Core\Cache\CacheHelper::getBins()
Chris@0: * @see hook_cache_flush()
Chris@0: * @see hook_rebuild()
Chris@0: *
Chris@0: * This function also resets the theme, which means it is not initialized
Chris@0: * anymore and all previously added JavaScript and CSS is gone. Normally, this
Chris@0: * function is called as an end-of-POST-request operation that is followed by a
Chris@0: * redirect, so this effect is not visible. Since the full reset is the whole
Chris@0: * point of this function, callers need to take care for backing up all needed
Chris@0: * variables and properly restoring or re-initializing them on their own. For
Chris@0: * convenience, this function automatically re-initializes the maintenance theme
Chris@0: * if it was initialized before.
Chris@0: *
Chris@0: * @todo Try to clear page/JS/CSS caches last, so cached pages can still be
Chris@0: * served during this possibly long-running operation. (Conflict on bootstrap
Chris@0: * cache though.)
Chris@0: * @todo Add a global lock to ensure that caches are not primed in concurrent
Chris@0: * requests.
Chris@0: */
Chris@0: function drupal_flush_all_caches() {
Chris@0: $module_handler = \Drupal::moduleHandler();
Chris@0: // Flush all persistent caches.
Chris@0: // This is executed based on old/previously known information, which is
Chris@0: // sufficient, since new extensions cannot have any primed caches yet.
Chris@0: $module_handler->invokeAll('cache_flush');
Chris@0: foreach (Cache::getBins() as $service_id => $cache_backend) {
Chris@0: $cache_backend->deleteAll();
Chris@0: }
Chris@0:
Chris@0: // Flush asset file caches.
Chris@0: \Drupal::service('asset.css.collection_optimizer')->deleteAll();
Chris@0: \Drupal::service('asset.js.collection_optimizer')->deleteAll();
Chris@0: _drupal_flush_css_js();
Chris@0:
Chris@0: // Reset all static caches.
Chris@0: drupal_static_reset();
Chris@0:
Chris@0: // Invalidate the container.
Chris@0: \Drupal::service('kernel')->invalidateContainer();
Chris@0:
Chris@0: // Wipe the Twig PHP Storage cache.
Chris@17: \Drupal::service('twig')->invalidate();
Chris@0:
Chris@0: // Rebuild module and theme data.
Chris@0: $module_data = system_rebuild_module_data();
Chris@0: /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
Chris@0: $theme_handler = \Drupal::service('theme_handler');
Chris@0: $theme_handler->refreshInfo();
Chris@0: // In case the active theme gets requested later in the same request we need
Chris@0: // to reset the theme manager.
Chris@0: \Drupal::theme()->resetActiveTheme();
Chris@0:
Chris@0: // Rebuild and reboot a new kernel. A simple DrupalKernel reboot is not
Chris@0: // sufficient, since the list of enabled modules might have been adjusted
Chris@0: // above due to changed code.
Chris@0: $files = [];
Chris@0: foreach ($module_data as $name => $extension) {
Chris@0: if ($extension->status) {
Chris@0: $files[$name] = $extension;
Chris@0: }
Chris@0: }
Chris@0: \Drupal::service('kernel')->updateModules($module_handler->getModuleList(), $files);
Chris@0: // New container, new module handler.
Chris@0: $module_handler = \Drupal::moduleHandler();
Chris@0:
Chris@0: // Ensure that all modules that are currently supposed to be enabled are
Chris@0: // actually loaded.
Chris@0: $module_handler->loadAll();
Chris@0:
Chris@0: // Rebuild all information based on new module data.
Chris@0: $module_handler->invokeAll('rebuild');
Chris@0:
Chris@0: // Clear all plugin caches.
Chris@0: \Drupal::service('plugin.cache_clearer')->clearCachedDefinitions();
Chris@0:
Chris@0: // Rebuild the menu router based on all rebuilt data.
Chris@0: // Important: This rebuild must happen last, so the menu router is guaranteed
Chris@0: // to be based on up to date information.
Chris@0: \Drupal::service('router.builder')->rebuild();
Chris@0:
Chris@0: // Re-initialize the maintenance theme, if the current request attempted to
Chris@0: // use it. Unlike regular usages of this function, the installer and update
Chris@0: // scripts need to flush all caches during GET requests/page building.
Chris@0: if (function_exists('_drupal_maintenance_theme')) {
Chris@0: \Drupal::theme()->resetActiveTheme();
Chris@0: drupal_maintenance_theme();
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Changes the dummy query string added to all CSS and JavaScript files.
Chris@0: *
Chris@0: * Changing the dummy query string appended to CSS and JavaScript files forces
Chris@0: * all browsers to reload fresh files.
Chris@0: */
Chris@0: function _drupal_flush_css_js() {
Chris@0: // The timestamp is converted to base 36 in order to make it more compact.
Chris@0: Drupal::state()->set('system.css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Outputs debug information.
Chris@0: *
Chris@0: * The debug information is passed on to trigger_error() after being converted
Chris@0: * to a string using _drupal_debug_message().
Chris@0: *
Chris@0: * @param $data
Chris@0: * Data to be output.
Chris@0: * @param $label
Chris@0: * Label to prefix the data.
Chris@0: * @param $print_r
Chris@0: * Flag to switch between print_r() and var_export() for data conversion to
Chris@0: * string. Set $print_r to FALSE to use var_export() instead of print_r().
Chris@0: * Passing recursive data structures to var_export() will generate an error.
Chris@0: */
Chris@0: function debug($data, $label = NULL, $print_r = TRUE) {
Chris@0: // Print $data contents to string.
Chris@0: $string = Html::escape($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
Chris@0:
Chris@0: // Display values with pre-formatting to increase readability.
Chris@0: $string = '' . $string . '
';
Chris@0:
Chris@0: trigger_error(trim($label ? "$label: $string" : $string));
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Checks whether a version is compatible with a given dependency.
Chris@0: *
Chris@0: * @param $v
Chris@0: * A parsed dependency structure e.g. from ModuleHandler::parseDependency().
Chris@0: * @param $current_version
Chris@0: * The version to check against (like 4.2).
Chris@0: *
Chris@0: * @return
Chris@0: * NULL if compatible, otherwise the original dependency version string that
Chris@0: * caused the incompatibility.
Chris@0: *
Chris@18: * @deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use
Chris@18: * \Drupal\Core\Extension\Dependency::isCompatible() instead.
Chris@18: *
Chris@18: * @see https://www.drupal.org/node/2756875
Chris@0: */
Chris@0: function drupal_check_incompatibility($v, $current_version) {
Chris@18: @trigger_error(__FUNCTION__ . '() is deprecated. Use \Drupal\Core\Extension\Dependency::isCompatible() instead. See https://www.drupal.org/node/2756875', E_USER_DEPRECATED);
Chris@0: if (!empty($v['versions'])) {
Chris@0: foreach ($v['versions'] as $required_version) {
Chris@0: if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
Chris@0: return $v['original_version'];
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Returns a string of supported archive extensions.
Chris@0: *
Chris@0: * @return
Chris@0: * A space-separated string of extensions suitable for use by the file
Chris@0: * validation system.
Chris@0: */
Chris@0: function archiver_get_extensions() {
Chris@0: $valid_extensions = [];
Chris@0: foreach (\Drupal::service('plugin.manager.archiver')->getDefinitions() as $archive) {
Chris@0: foreach ($archive['extensions'] as $extension) {
Chris@0: foreach (explode('.', $extension) as $part) {
Chris@0: if (!in_array($part, $valid_extensions)) {
Chris@0: $valid_extensions[] = $part;
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0: return implode(' ', $valid_extensions);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Creates the appropriate archiver for the specified file.
Chris@0: *
Chris@0: * @param $file
Chris@0: * The full path of the archive file. Note that stream wrapper paths are
Chris@0: * supported, but not remote ones.
Chris@0: *
Chris@0: * @return
Chris@0: * A newly created instance of the archiver class appropriate
Chris@0: * for the specified file, already bound to that file.
Chris@0: * If no appropriate archiver class was found, will return FALSE.
Chris@0: */
Chris@0: function archiver_get_archiver($file) {
Chris@0: // Archivers can only work on local paths
Chris@14: $filepath = \Drupal::service('file_system')->realpath($file);
Chris@0: if (!is_file($filepath)) {
Chris@0: throw new Exception(t('Archivers can only operate on local files: %file not supported', ['%file' => $file]));
Chris@0: }
Chris@0: return \Drupal::service('plugin.manager.archiver')->getInstance(['filepath' => $filepath]);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Assembles the Drupal Updater registry.
Chris@0: *
Chris@0: * An Updater is a class that knows how to update various parts of the Drupal
Chris@0: * file system, for example to update modules that have newer releases, or to
Chris@0: * install a new theme.
Chris@0: *
Chris@0: * @return array
Chris@0: * The Drupal Updater class registry.
Chris@0: *
Chris@0: * @see \Drupal\Core\Updater\Updater
Chris@0: * @see hook_updater_info()
Chris@0: * @see hook_updater_info_alter()
Chris@0: */
Chris@0: function drupal_get_updaters() {
Chris@0: $updaters = &drupal_static(__FUNCTION__);
Chris@0: if (!isset($updaters)) {
Chris@0: $updaters = \Drupal::moduleHandler()->invokeAll('updater_info');
Chris@0: \Drupal::moduleHandler()->alter('updater_info', $updaters);
Chris@0: uasort($updaters, [SortArray::class, 'sortByWeightElement']);
Chris@0: }
Chris@0: return $updaters;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Assembles the Drupal FileTransfer registry.
Chris@0: *
Chris@0: * @return
Chris@0: * The Drupal FileTransfer class registry.
Chris@0: *
Chris@0: * @see \Drupal\Core\FileTransfer\FileTransfer
Chris@0: * @see hook_filetransfer_info()
Chris@0: * @see hook_filetransfer_info_alter()
Chris@0: */
Chris@0: function drupal_get_filetransfer_info() {
Chris@0: $info = &drupal_static(__FUNCTION__);
Chris@0: if (!isset($info)) {
Chris@0: $info = \Drupal::moduleHandler()->invokeAll('filetransfer_info');
Chris@0: \Drupal::moduleHandler()->alter('filetransfer_info', $info);
Chris@0: uasort($info, [SortArray::class, 'sortByWeightElement']);
Chris@0: }
Chris@0: return $info;
Chris@0: }