annotate core/includes/common.inc @ 19:fa3358dc1485 tip

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