common.inc

Common functions that many Drupal modules will need to reference.

The functions that are critical and need to be available even when serving a cached page are instead located in bootstrap.inc.

File

drupal/core/includes/common.inc
View source
  1. <?php
  2. use Drupal\Component\Utility\Crypt;
  3. use Drupal\Component\Utility\String;
  4. use Drupal\Component\Utility\Tags;
  5. use Drupal\Component\Utility\UrlValidator;
  6. use Drupal\Component\Utility\Xss;
  7. use Drupal\Core\Cache\Cache;
  8. use Drupal\Core\Language\Language;
  9. use Symfony\Component\DependencyInjection\Container;
  10. use Symfony\Component\HttpFoundation\RedirectResponse;
  11. use Symfony\Component\Yaml\Parser;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Drupal\Component\PhpStorage\PhpStorageFactory;
  15. use Drupal\Component\Utility\MapArray;
  16. use Drupal\Component\Utility\NestedArray;
  17. use Drupal\Component\Utility\Unicode;
  18. use Drupal\Core\Cache\CacheBackendInterface;
  19. use Drupal\Core\Datetime\DrupalDateTime;
  20. use Drupal\Core\Database\Database;
  21. use Drupal\Core\Routing\GeneratorNotInitializedException;
  22. use Drupal\Core\SystemListingInfo;
  23. use Drupal\Core\Template\Attribute;
  24. /**
  25. * @file
  26. * Common functions that many Drupal modules will need to reference.
  27. *
  28. * The functions that are critical and need to be available even when serving
  29. * a cached page are instead located in bootstrap.inc.
  30. */
  31. /**
  32. * @defgroup php_wrappers PHP wrapper functions
  33. * @{
  34. * Functions that are wrappers or custom implementations of PHP functions.
  35. *
  36. * Certain PHP functions should not be used in Drupal. Instead, Drupal's
  37. * replacement functions should be used.
  38. *
  39. * For example, for improved or more secure UTF8-handling, or RFC-compliant
  40. * handling of URLs in Drupal.
  41. *
  42. * For ease of use and memorizing, all these wrapper functions use the same name
  43. * as the original PHP function, but prefixed with "drupal_". Beware, however,
  44. * that not all wrapper functions support the same arguments as the original
  45. * functions.
  46. *
  47. * You should always use these wrapper functions in your code.
  48. *
  49. * Wrong:
  50. * @code
  51. * $my_substring = substr($original_string, 0, 5);
  52. * @endcode
  53. *
  54. * Correct:
  55. * @code
  56. * $my_substring = drupal_substr($original_string, 0, 5);
  57. * @endcode
  58. *
  59. * @}
  60. */
  61. /**
  62. * Return status for saving which involved creating a new item.
  63. */
  64. const SAVED_NEW = 1;
  65. /**
  66. * Return status for saving which involved an update to an existing item.
  67. */
  68. const SAVED_UPDATED = 2;
  69. /**
  70. * Return status for saving which deleted an existing item.
  71. */
  72. const SAVED_DELETED = 3;
  73. /**
  74. * The default aggregation group for CSS files added to the page.
  75. */
  76. const CSS_AGGREGATE_DEFAULT = 0;
  77. /**
  78. * The default aggregation group for theme CSS files added to the page.
  79. */
  80. const CSS_AGGREGATE_THEME = 100;
  81. /**
  82. * The default weight for CSS rules that style HTML elements ("base" styles).
  83. */
  84. const CSS_BASE = -200;
  85. /**
  86. * The default weight for CSS rules that layout a page.
  87. */
  88. const CSS_LAYOUT = -100;
  89. /**
  90. * The default weight for CSS rules that style design components (and their associated states and skins.)
  91. */
  92. const CSS_COMPONENT = 0;
  93. /**
  94. * The default weight for CSS rules that style states and are not included with components.
  95. */
  96. const CSS_STATE = 100;
  97. /**
  98. * The default weight for CSS rules that style skins and are not included with components.
  99. */
  100. const CSS_SKIN = 200;
  101. /**
  102. * The default group for JavaScript settings added to the page.
  103. */
  104. const JS_SETTING = -200;
  105. /**
  106. * The default group for JavaScript and jQuery libraries added to the page.
  107. */
  108. const JS_LIBRARY = -100;
  109. /**
  110. * The default group for module JavaScript code added to the page.
  111. */
  112. const JS_DEFAULT = 0;
  113. /**
  114. * The default group for theme JavaScript code added to the page.
  115. */
  116. const JS_THEME = 100;
  117. /**
  118. * @defgroup block_caching Block Caching
  119. * @{
  120. * Constants that define each block's caching state.
  121. *
  122. * Modules specify how their blocks can be cached in their hook_block_info()
  123. * implementations. Caching can be turned off (DRUPAL_NO_CACHE), managed by the
  124. * module declaring the block (DRUPAL_CACHE_CUSTOM), or managed by the core
  125. * Block module. If the Block module is managing the cache, you can specify that
  126. * the block is the same for every page and user (DRUPAL_CACHE_GLOBAL), or that
  127. * it can change depending on the page (DRUPAL_CACHE_PER_PAGE) or by user
  128. * (DRUPAL_CACHE_PER_ROLE or DRUPAL_CACHE_PER_USER). Page and user settings can
  129. * be combined with a bitwise-binary or operator; for example,
  130. * DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE means that the block can change
  131. * depending on the user role or page it is on.
  132. *
  133. * The block cache is cleared when the 'content' cache tag is invalidated,
  134. * following the same pattern as the page cache (node, comment, user, taxonomy
  135. * added or updated...).
  136. *
  137. * Note that user 1 is excluded from block caching.
  138. */
  139. /**
  140. * The block should not get cached.
  141. *
  142. * This setting should be used:
  143. * - For simple blocks (notably those that do not perform any db query), where
  144. * querying the db cache would be more expensive than directly generating the
  145. * content.
  146. * - For blocks that change too frequently.
  147. */
  148. const DRUPAL_NO_CACHE = -1;
  149. /**
  150. * The block is handling its own caching in its hook_block_view().
  151. *
  152. * This setting is useful when time based expiration is needed or a site uses a
  153. * node access which invalidates standard block cache.
  154. */
  155. const DRUPAL_CACHE_CUSTOM = -2;
  156. /**
  157. * The block or element can change depending on the user's roles.
  158. *
  159. * This is the default setting for blocks, used when the block does not specify
  160. * anything.
  161. */
  162. const DRUPAL_CACHE_PER_ROLE = 0x0001;
  163. /**
  164. * The block or element can change depending on the user.
  165. *
  166. * This setting can be resource-consuming for sites with large number of users,
  167. * and thus should only be used when DRUPAL_CACHE_PER_ROLE is not sufficient.
  168. */
  169. const DRUPAL_CACHE_PER_USER = 0x0002;
  170. /**
  171. * The block or element can change depending on the page being viewed.
  172. */
  173. const DRUPAL_CACHE_PER_PAGE = 0x0004;
  174. /**
  175. * The block or element is the same for every user and page that it is visible.
  176. */
  177. const DRUPAL_CACHE_GLOBAL = 0x0008;
  178. /**
  179. * @} End of "defgroup block_caching".
  180. */
  181. /**
  182. * The delimiter used to split plural strings.
  183. *
  184. * This is the ETX (End of text) character and is used as a minimal means to
  185. * separate singular and plural variants in source and translation text. It
  186. * was found to be the most compatible delimiter for the supported databases.
  187. */
  188. const LOCALE_PLURAL_DELIMITER = "\03";
  189. /**
  190. * Adds content to a specified region.
  191. *
  192. * @param $region
  193. * Page region the content is added to.
  194. * @param $data
  195. * Content to be added.
  196. */
  197. function drupal_add_region_content($region = NULL, $data = NULL) {
  198. static $content = array();
  199. if (isset($region) && isset($data)) {
  200. $content[$region][] = $data;
  201. }
  202. return $content;
  203. }
  204. /**
  205. * Gets assigned content for a given region.
  206. *
  207. * @param $region
  208. * A specified region to fetch content for. If NULL, all regions will be
  209. * returned.
  210. * @param $delimiter
  211. * Content to be inserted between imploded array elements.
  212. */
  213. function drupal_get_region_content($region = NULL, $delimiter = ' ') {
  214. $content = drupal_add_region_content();
  215. if (isset($region)) {
  216. if (isset($content[$region]) && is_array($content[$region])) {
  217. return implode($delimiter, $content[$region]);
  218. }
  219. }
  220. else {
  221. foreach (array_keys($content) as $region) {
  222. if (is_array($content[$region])) {
  223. $content[$region] = implode($delimiter, $content[$region]);
  224. }
  225. }
  226. return $content;
  227. }
  228. }
  229. /**
  230. * Gets the name of the currently active installation profile.
  231. *
  232. * When this function is called during Drupal's initial installation process,
  233. * the name of the profile that's about to be installed is stored in the global
  234. * installation state. At all other times, the standard Drupal systems variable
  235. * table contains the name of the current profile, and we can call
  236. * variable_get() to determine what one is active.
  237. *
  238. * @return $profile
  239. * The name of the installation profile.
  240. */
  241. function drupal_get_profile() {
  242. global $install_state;
  243. if (isset($install_state['parameters']['profile'])) {
  244. $profile = $install_state['parameters']['profile'];
  245. }
  246. else {
  247. $profile = variable_get('install_profile', 'standard');
  248. }
  249. return $profile;
  250. }
  251. /**
  252. * Sets the breadcrumb trail for the current page.
  253. *
  254. * @param $breadcrumb
  255. * Array of links, starting with "home" and proceeding up to but not including
  256. * the current page.
  257. */
  258. function drupal_set_breadcrumb($breadcrumb = NULL) {
  259. $stored_breadcrumb = &drupal_static(__FUNCTION__);
  260. if (isset($breadcrumb)) {
  261. $stored_breadcrumb = $breadcrumb;
  262. }
  263. return $stored_breadcrumb;
  264. }
  265. /**
  266. * Gets the breadcrumb trail for the current page.
  267. */
  268. function drupal_get_breadcrumb() {
  269. $breadcrumb = drupal_set_breadcrumb();
  270. if (!isset($breadcrumb)) {
  271. $breadcrumb = menu_get_active_breadcrumb();
  272. }
  273. return $breadcrumb;
  274. }
  275. /**
  276. * Adds output to the HEAD tag of the HTML page.
  277. *
  278. * This function can be called as long as the headers aren't sent. Pass no
  279. * arguments (or NULL for both) to retrieve the currently stored elements.
  280. *
  281. * @param $data
  282. * A renderable array. If the '#type' key is not set then 'html_tag' will be
  283. * added as the default '#type'.
  284. * @param $key
  285. * A unique string key to allow implementations of hook_html_head_alter() to
  286. * identify the element in $data. Required if $data is not NULL.
  287. *
  288. * @return
  289. * An array of all stored HEAD elements.
  290. *
  291. * @see drupal_pre_render_html_tag()
  292. */
  293. function drupal_add_html_head($data = NULL, $key = NULL) {
  294. $stored_head = &drupal_static(__FUNCTION__);
  295. if (!isset($stored_head)) {
  296. // Make sure the defaults, including Content-Type, come first.
  297. $stored_head = _drupal_default_html_head();
  298. }
  299. if (isset($data) && isset($key)) {
  300. if (!isset($data['#type'])) {
  301. $data['#type'] = 'html_tag';
  302. }
  303. $stored_head[$key] = $data;
  304. }
  305. return $stored_head;
  306. }
  307. /**
  308. * Returns elements that are always displayed in the HEAD tag of the HTML page.
  309. */
  310. function _drupal_default_html_head() {
  311. // Add default elements. Make sure the Content-Type comes first because the
  312. // IE browser may be vulnerable to XSS via encoding attacks from any content
  313. // that comes before this META tag, such as a TITLE tag.
  314. $elements['system_meta_content_type'] = array(
  315. '#type' => 'html_tag',
  316. '#tag' => 'meta',
  317. '#attributes' => array(
  318. 'charset' => 'utf-8',
  319. ),
  320. // Security: This always has to be output first.
  321. '#weight' => -1000,
  322. );
  323. // Show Drupal and the major version number in the META GENERATOR tag.
  324. // Get the major version.
  325. list($version, ) = explode('.', VERSION);
  326. $elements['system_meta_generator'] = array(
  327. '#type' => 'html_tag',
  328. '#tag' => 'meta',
  329. '#attributes' => array(
  330. 'name' => 'Generator',
  331. 'content' => 'Drupal ' . $version . ' (http://drupal.org)',
  332. ),
  333. );
  334. // Also send the generator in the HTTP header.
  335. $elements['system_meta_generator']['#attached']['drupal_add_http_header'][] = array('X-Generator', $elements['system_meta_generator']['#attributes']['content']);
  336. return $elements;
  337. }
  338. /**
  339. * Retrieves output to be displayed in the HEAD tag of the HTML page.
  340. */
  341. function drupal_get_html_head() {
  342. $elements = drupal_add_html_head();
  343. drupal_alter('html_head', $elements);
  344. return drupal_render($elements);
  345. }
  346. /**
  347. * Adds a feed URL for the current page.
  348. *
  349. * This function can be called as long the HTML header hasn't been sent.
  350. *
  351. * @param $url
  352. * An internal system path or a fully qualified external URL of the feed.
  353. * @param $title
  354. * The title of the feed.
  355. */
  356. function drupal_add_feed($url = NULL, $title = '') {
  357. $stored_feed_links = &drupal_static(__FUNCTION__, array());
  358. if (isset($url)) {
  359. $stored_feed_links[$url] = theme('feed_icon', array('url' => $url, 'title' => $title));
  360. drupal_add_html_head_link(array(
  361. 'rel' => 'alternate',
  362. 'type' => 'application/rss+xml',
  363. 'title' => $title,
  364. // Force the URL to be absolute, for consistency with other <link> tags
  365. // output by Drupal.
  366. 'href' => url($url, array('absolute' => TRUE)),
  367. ));
  368. }
  369. return $stored_feed_links;
  370. }
  371. /**
  372. * Gets the feed URLs for the current page.
  373. *
  374. * @param $delimiter
  375. * A delimiter to split feeds by.
  376. */
  377. function drupal_get_feeds($delimiter = "\n") {
  378. $feeds = drupal_add_feed();
  379. return implode($feeds, $delimiter);
  380. }
  381. /**
  382. * @defgroup http_handling HTTP handling
  383. * @{
  384. * Functions to properly handle HTTP responses.
  385. */
  386. /**
  387. * Processes a URL query parameter array to remove unwanted elements.
  388. *
  389. * @param $query
  390. * (optional) An array to be processed. Defaults to $_GET.
  391. * @param $exclude
  392. * (optional) A list of $query array keys to remove. Use "parent[child]" to
  393. * exclude nested items.
  394. * @param $parent
  395. * Internal use only. Used to build the $query array key for nested items.
  396. *
  397. * @return
  398. * An array containing query parameters, which can be used for url().
  399. */
  400. function drupal_get_query_parameters(array $query = NULL, array $exclude = array(), $parent = '') {
  401. // Set defaults, if none given.
  402. if (!isset($query)) {
  403. $query = $_GET;
  404. }
  405. // If $exclude is empty, there is nothing to filter.
  406. if (empty($exclude)) {
  407. return $query;
  408. }
  409. elseif (!$parent) {
  410. $exclude = array_flip($exclude);
  411. }
  412. $params = array();
  413. foreach ($query as $key => $value) {
  414. $string_key = ($parent ? $parent . '[' . $key . ']' : $key);
  415. if (isset($exclude[$string_key])) {
  416. continue;
  417. }
  418. if (is_array($value)) {
  419. $params[$key] = drupal_get_query_parameters($value, $exclude, $string_key);
  420. }
  421. else {
  422. $params[$key] = $value;
  423. }
  424. }
  425. return $params;
  426. }
  427. /**
  428. * Splits a URL-encoded query string into an array.
  429. *
  430. * @param $query
  431. * The query string to split.
  432. *
  433. * @return
  434. * An array of URL decoded couples $param_name => $value.
  435. */
  436. function drupal_get_query_array($query) {
  437. $result = array();
  438. if (!empty($query)) {
  439. foreach (explode('&', $query) as $param) {
  440. $param = explode('=', $param);
  441. $result[$param[0]] = isset($param[1]) ? rawurldecode($param[1]) : '';
  442. }
  443. }
  444. return $result;
  445. }
  446. /**
  447. * Parses an array into a valid, rawurlencoded query string.
  448. *
  449. * @see \Drupal\Core\Routing\PathBasedGeneratorInterface::httpBuildQuery()
  450. * @see drupal_get_query_parameters()
  451. * @deprecated as of Drupal 8.0. Use
  452. * Drupal::urlGenerator()->httpBuildQuery() instead.
  453. * @ingroup php_wrappers
  454. */
  455. function drupal_http_build_query(array $query, $parent = '') {
  456. return Drupal::urlGenerator()->httpBuildQuery($query, $parent);
  457. }
  458. /**
  459. * Prepares a 'destination' URL query parameter for use with drupal_goto().
  460. *
  461. * Used to direct the user back to the referring page after completing a form.
  462. * By default the current URL is returned. If a destination exists in the
  463. * previous request, that destination is returned. As such, a destination can
  464. * persist across multiple pages.
  465. *
  466. * @return
  467. * An associative array containing the key:
  468. * - destination: The path provided via the destination query string or, if
  469. * not available, the current path.
  470. *
  471. * @see current_path()
  472. * @see drupal_goto()
  473. */
  474. function drupal_get_destination() {
  475. $destination = &drupal_static(__FUNCTION__);
  476. if (isset($destination)) {
  477. return $destination;
  478. }
  479. if (isset($_GET['destination'])) {
  480. $destination = array('destination' => $_GET['destination']);
  481. }
  482. else {
  483. $path = current_path();
  484. $query = Drupal::urlGenerator()->httpBuildQuery(drupal_get_query_parameters());
  485. if ($query != '') {
  486. $path .= '?' . $query;
  487. }
  488. $destination = array('destination' => $path);
  489. }
  490. return $destination;
  491. }
  492. /**
  493. * Parses a system URL string into an associative array suitable for url().
  494. *
  495. * This function should only be used for URLs that have been generated by the
  496. * system, such as via url(). It should not be used for URLs that come from
  497. * external sources, or URLs that link to external resources.
  498. *
  499. * The returned array contains a 'path' that may be passed separately to url().
  500. * For example:
  501. * @code
  502. * $options = drupal_parse_url($_GET['destination']);
  503. * $my_url = url($options['path'], $options);
  504. * $my_link = l('Example link', $options['path'], $options);
  505. * @endcode
  506. *
  507. * This is required, because url() does not support relative URLs containing a
  508. * query string or fragment in its $path argument. Instead, any query string
  509. * needs to be parsed into an associative query parameter array in
  510. * $options['query'] and the fragment into $options['fragment'].
  511. *
  512. * @param $url
  513. * The URL string to parse, f.e. $_GET['destination'].
  514. *
  515. * @return
  516. * An associative array containing the keys:
  517. * - 'path': The path of the URL. If the given $url is external, this includes
  518. * the scheme and host.
  519. * - 'query': An array of query parameters of $url, if existent.
  520. * - 'fragment': The fragment of $url, if existent.
  521. *
  522. * @see url()
  523. * @see drupal_goto()
  524. * @ingroup php_wrappers
  525. */
  526. function drupal_parse_url($url) {
  527. $options = array(
  528. 'path' => NULL,
  529. 'query' => array(),
  530. 'fragment' => '',
  531. );
  532. // External URLs: not using parse_url() here, so we do not have to rebuild
  533. // the scheme, host, and path without having any use for it.
  534. if (strpos($url, '://') !== FALSE) {
  535. // Split off everything before the query string into 'path'.
  536. $parts = explode('?', $url);
  537. $options['path'] = $parts[0];
  538. // If there is a query string, transform it into keyed query parameters.
  539. if (isset($parts[1])) {
  540. $query_parts = explode('#', $parts[1]);
  541. parse_str($query_parts[0], $options['query']);
  542. // Take over the fragment, if there is any.
  543. if (isset($query_parts[1])) {
  544. $options['fragment'] = $query_parts[1];
  545. }
  546. }
  547. }
  548. // Internal URLs.
  549. else {
  550. // parse_url() does not support relative URLs, so make it absolute. E.g. the
  551. // relative URL "foo/bar:1" isn't properly parsed.
  552. $parts = parse_url('http://example.com/' . $url);
  553. // Strip the leading slash that was just added.
  554. $options['path'] = substr($parts['path'], 1);
  555. if (isset($parts['query'])) {
  556. parse_str($parts['query'], $options['query']);
  557. }
  558. if (isset($parts['fragment'])) {
  559. $options['fragment'] = $parts['fragment'];
  560. }
  561. }
  562. return $options;
  563. }
  564. /**
  565. * Encodes a Drupal path for use in a URL.
  566. *
  567. * For aesthetic reasons slashes are not escaped.
  568. *
  569. * Note that url() takes care of calling this function, so a path passed to that
  570. * function should not be encoded in advance.
  571. *
  572. * @param $path
  573. * The Drupal path to encode.
  574. */
  575. function drupal_encode_path($path) {
  576. return str_replace('%2F', '/', rawurlencode($path));
  577. }
  578. /**
  579. * Sends the user to a different Drupal page.
  580. *
  581. * This issues an on-site HTTP redirect. The function makes sure the redirected
  582. * URL is formatted correctly.
  583. *
  584. * If a destination was specified in the current request's URI (i.e.,
  585. * $_GET['destination']) then it will override the $path and $options values
  586. * passed to this function. This provides the flexibility to build a link to
  587. * user/login and override the default redirection so that the user is
  588. * redirected to a specific path after logging in:
  589. * @code
  590. * $query = array('destination' => "node/$node->nid");
  591. * $link = l(t('Log in'), 'user/login', array('query' => $query));
  592. * @endcode
  593. *
  594. * Drupal will ensure that messages set by drupal_set_message() and other
  595. * session data are written to the database before the user is redirected.
  596. *
  597. * This function ends the request; use it instead of a return in your menu
  598. * callback.
  599. *
  600. * @param $path
  601. * (optional) A Drupal path or a full URL, which will be passed to url() to
  602. * compute the redirect for the URL.
  603. * @param $options
  604. * (optional) An associative array of additional URL options to pass to url().
  605. * @param $http_response_code
  606. * (optional) The HTTP status code to use for the redirection, defaults to
  607. * 302. The valid values for 3xx redirection status codes are defined in
  608. * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3 RFC 2616 @endlink
  609. * and the
  610. * @link http://tools.ietf.org/html/draft-reschke-http-status-308-07 draft for the new HTTP status codes: @endlink
  611. * - 301: Moved Permanently (the recommended value for most redirects).
  612. * - 302: Found (default in Drupal and PHP, sometimes used for spamming search
  613. * engines).
  614. * - 303: See Other.
  615. * - 304: Not Modified.
  616. * - 305: Use Proxy.
  617. * - 307: Temporary Redirect.
  618. *
  619. * @see drupal_get_destination()
  620. * @see url()
  621. */
  622. function drupal_goto($path = '', array $options = array(), $http_response_code = 302) {
  623. // A destination in $_GET always overrides the function arguments.
  624. // We do not allow absolute URLs to be passed via $_GET, as this can be an
  625. // attack vector, with the following exception:
  626. // - Absolute URLs that point to this site (i.e. same base URL and
  627. // base path) are allowed.
  628. if (isset($_GET['destination']) && (!url_is_external($_GET['destination']) || _external_url_is_local($_GET['destination']))) {
  629. $destination = drupal_parse_url($_GET['destination']);
  630. $path = $destination['path'];
  631. $options['query'] = $destination['query'];
  632. $options['fragment'] = $destination['fragment'];
  633. }
  634. drupal_alter('drupal_goto', $path, $options, $http_response_code);
  635. // The 'Location' HTTP header must be absolute.
  636. $options['absolute'] = TRUE;
  637. $url = Drupal::urlGenerator()->generateFromPath($path, $options);
  638. if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL) {
  639. drupal_session_commit();
  640. }
  641. $response = new RedirectResponse($url, $http_response_code);
  642. // @todo We should not send the response here: http://drupal.org/node/1668866
  643. $response->sendHeaders();
  644. // The "Location" header sends a redirect status code to the HTTP daemon. In
  645. // some cases this can be wrong, so we make sure none of the code below the
  646. // drupal_goto() call gets executed upon redirection.
  647. exit;
  648. }
  649. /**
  650. * Determines if an external URL points to this Drupal installation.
  651. *
  652. * @param $url
  653. * A string containing an external URL, such as "http://example.com/foo".
  654. *
  655. * @return
  656. * TRUE if the URL has the same domain and base path.
  657. */
  658. function _external_url_is_local($url) {
  659. $url_parts = parse_url($url);
  660. $base_host = parse_url($GLOBALS['base_url'], PHP_URL_HOST);
  661. if (!isset($url_parts['path'])) {
  662. return ($url_parts['host'] == $base_host);
  663. }
  664. else {
  665. // When comparing base paths, we need a trailing slash to make sure a
  666. // partial URL match isn't occuring. Since base_path() always returns with
  667. // a trailing slash, we don't need to add the trailing slash here.
  668. return ($url_parts['host'] == $base_host && stripos($url_parts['path'], base_path()) === 0);
  669. }
  670. }
  671. /**
  672. * Helper function for determining hosts excluded from needing a proxy.
  673. *
  674. * @return
  675. * TRUE if a proxy should be used for this host.
  676. */
  677. function _drupal_http_use_proxy($host) {
  678. $proxy_exceptions = settings()->get('proxy_exceptions', array('localhost', '127.0.0.1'));
  679. return !in_array(strtolower($host), $proxy_exceptions, TRUE);
  680. }
  681. /**
  682. * @} End of "defgroup http_handling".
  683. */
  684. /**
  685. * @defgroup validation Input validation
  686. * @{
  687. * Functions to validate user input.
  688. */
  689. /**
  690. * Verifies the syntax of the given e-mail address.
  691. *
  692. * This uses the
  693. * @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
  694. *
  695. * @param $mail
  696. * A string containing an e-mail address.
  697. *
  698. * @return
  699. * TRUE if the address is in a valid format.
  700. */
  701. function valid_email_address($mail) {
  702. return (bool)filter_var($mail, FILTER_VALIDATE_EMAIL);
  703. }
  704. /**
  705. * Verifies the syntax of the given URL.
  706. *
  707. * This function should only be used on actual URLs. It should not be used for
  708. * Drupal menu paths, which can contain arbitrary characters.
  709. * Valid values per RFC 3986.
  710. * @param $url
  711. * The URL to verify.
  712. * @param $absolute
  713. * Whether the URL is absolute (beginning with a scheme such as "http:").
  714. *
  715. * @return
  716. * TRUE if the URL is in a valid format.
  717. *
  718. * @see \Drupal\Component\Utility\UrlValidator::isValid()
  719. *
  720. * @deprecated as of Drupal 8.0. Use UrlValidator::isValid() instead.
  721. */
  722. function valid_url($url, $absolute = FALSE) {
  723. return UrlValidator::isValid($url, $absolute);
  724. }
  725. /**
  726. * Verifies that a number is a multiple of a given step.
  727. *
  728. * The implementation assumes it is dealing with IEEE 754 double precision
  729. * floating point numbers that are used by PHP on most systems.
  730. *
  731. * This is based on the number/range verification methods of webkit.
  732. *
  733. * @param $value
  734. * The value that needs to be checked.
  735. * @param $step
  736. * The step scale factor. Must be positive.
  737. * @param $offset
  738. * (optional) An offset, to which the difference must be a multiple of the
  739. * given step.
  740. *
  741. * @return bool
  742. * TRUE if no step mismatch has occured, or FALSE otherwise.
  743. *
  744. * @see http://opensource.apple.com/source/WebCore/WebCore-1298/html/NumberInputType.cpp
  745. */
  746. function valid_number_step($value, $step, $offset = 0.0) {
  747. $double_value = (double) abs($value - $offset);
  748. // The fractional part of a double has 53 bits. The greatest number that could
  749. // be represented with that is 2^53. If the given value is even bigger than
  750. // $step * 2^53, then dividing by $step will result in a very small remainder.
  751. // Since that remainder can't even be represented with a single precision
  752. // float the following computation of the remainder makes no sense and we can
  753. // safely ignore it instead.
  754. if ($double_value / pow(2.0, 53) > $step) {
  755. return TRUE;
  756. }
  757. // Now compute that remainder of a division by $step.
  758. $remainder = (double) abs($double_value - $step * round($double_value / $step));
  759. // $remainder is a double precision floating point number. Remainders that
  760. // can't be represented with single precision floats are acceptable. The
  761. // fractional part of a float has 24 bits. That means remainders smaller than
  762. // $step * 2^-24 are acceptable.
  763. $computed_acceptable_error = (double)($step / pow(2.0, 24));
  764. return $computed_acceptable_error >= $remainder || $remainder >= ($step - $computed_acceptable_error);
  765. }
  766. /**
  767. * @} End of "defgroup validation".
  768. */
  769. /**
  770. * @defgroup sanitization Sanitization functions
  771. * @{
  772. * Functions to sanitize values.
  773. *
  774. * See http://drupal.org/writing-secure-code for information
  775. * on writing secure code.
  776. */
  777. /**
  778. * Strips dangerous protocols (e.g. 'javascript:') from a URI.
  779. *
  780. * This function must be called for all URIs within user-entered input prior
  781. * to being output to an HTML attribute value. It is often called as part of
  782. * check_url() or filter_xss(), but those functions return an HTML-encoded
  783. * string, so this function can be called independently when the output needs to
  784. * be a plain-text string for passing to t(), l(),
  785. * Drupal\Core\Template\Attribute, or another function that will call
  786. * check_plain() separately.
  787. *
  788. * @param $uri
  789. * A plain-text URI that might contain dangerous protocols.
  790. *
  791. * @return
  792. * A plain-text URI stripped of dangerous protocols. As with all plain-text
  793. * strings, this return value must not be output to an HTML page without
  794. * check_plain() being called on it. However, it can be passed to functions
  795. * expecting plain-text strings.
  796. *
  797. * @see \Drupal\Component\Utility\Url::stripDangerousProtocols()
  798. */
  799. function drupal_strip_dangerous_protocols($uri) {
  800. return UrlValidator::stripDangerousProtocols($uri);
  801. }
  802. /**
  803. * Strips dangerous protocols from a URI and encodes it for output to HTML.
  804. *
  805. * @param $uri
  806. * A plain-text URI that might contain dangerous protocols.
  807. *
  808. * @return
  809. * A URI stripped of dangerous protocols and encoded for output to an HTML
  810. * attribute value. Because it is already encoded, it should not be set as a
  811. * value within a $attributes array passed to Drupal\Core\Template\Attribute,
  812. * because Drupal\Core\Template\Attribute expects those values to be
  813. * plain-text strings. To pass a filtered URI to
  814. * Drupal\Core\Template\Attribute, call drupal_strip_dangerous_protocols()
  815. * instead.
  816. *
  817. * @see \Drupal\Component\Utility\Url::stripDangerousProtocols()
  818. * @see \Drupal\Component\Utility\String::checkPlain()
  819. */
  820. function check_url($uri) {
  821. return String::checkPlain(UrlValidator::stripDangerousProtocols($uri));
  822. }
  823. /**
  824. * Applies a very permissive XSS/HTML filter for admin-only use.
  825. *
  826. * Use only for fields where it is impractical to use the
  827. * whole filter system, but where some (mainly inline) mark-up
  828. * is desired (so check_plain() is not acceptable).
  829. *
  830. * Allows all tags that can be used inside an HTML body, save
  831. * for scripts and styles.
  832. *
  833. * @param string $string
  834. * The string to apply the filter to.
  835. *
  836. * @return string
  837. * The filtered string.
  838. *
  839. * @see \Drupal\Component\Utility\Xss::filterAdmin()
  840. */
  841. function filter_xss_admin($string) {
  842. return Xss::filterAdmin($string);
  843. }
  844. /**
  845. * Filters HTML to prevent cross-site-scripting (XSS) vulnerabilities.
  846. *
  847. * Based on kses by Ulf Harnhammar, see http://sourceforge.net/projects/kses.
  848. * For examples of various XSS attacks, see: http://ha.ckers.org/xss.html.
  849. *
  850. * This code does four things:
  851. * - Removes characters and constructs that can trick browsers.
  852. * - Makes sure all HTML entities are well-formed.
  853. * - Makes sure all HTML tags and attributes are well-formed.
  854. * - Makes sure no HTML tags contain URLs with a disallowed protocol (e.g.
  855. * javascript:).
  856. *
  857. * @param $string
  858. * The string with raw HTML in it. It will be stripped of everything that can
  859. * cause an XSS attack.
  860. * @param $allowed_tags
  861. * An array of allowed tags.
  862. *
  863. * @return
  864. * An XSS safe version of $string, or an empty string if $string is not
  865. * valid UTF-8.
  866. *
  867. * @see \Drupal\Component\Utility\Xss::filter()
  868. *
  869. * @ingroup sanitization
  870. */
  871. function filter_xss($string, $allowed_tags = array('a', 'em', 'strong', 'cite', 'blockquote', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd')) {
  872. return Xss::filter($string, $allowed_tags);
  873. }
  874. /**
  875. * Processes an HTML attribute value and strips dangerous protocols from URLs.
  876. *
  877. * @param string $string
  878. * The string with the attribute value.
  879. *
  880. * @return string
  881. * Cleaned up and HTML-escaped version of $string.
  882. *
  883. * @see \Drupal\Component\Utility\Url::filterBadProtocol()
  884. */
  885. function filter_xss_bad_protocol($string) {
  886. return UrlValidator::filterBadProtocol($string);
  887. }
  888. /**
  889. * @} End of "defgroup sanitization".
  890. */
  891. /**
  892. * @defgroup format Formatting
  893. * @{
  894. * Functions to format numbers, strings, dates, etc.
  895. */
  896. /**
  897. * Formats an RSS channel.
  898. *
  899. * Arbitrary elements may be added using the $args associative array.
  900. */
  901. function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
  902. $langcode = $langcode ? $langcode : language(Language::TYPE_CONTENT)->langcode;
  903. $output = "<channel>\n";
  904. $output .= ' <title>' . check_plain($title) . "</title>\n";
  905. $output .= ' <link>' . check_url($link) . "</link>\n";
  906. // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
  907. // We strip all HTML tags, but need to prevent double encoding from properly
  908. // escaped source data (such as &amp becoming &amp;amp;).
  909. $output .= ' <description>' . check_plain(decode_entities(strip_tags($description))) . "</description>\n";
  910. $output .= ' <language>' . check_plain($langcode) . "</language>\n";
  911. $output .= format_xml_elements($args);
  912. $output .= $items;
  913. $output .= "</channel>\n";
  914. return $output;
  915. }
  916. /**
  917. * Formats a single RSS item.
  918. *
  919. * Arbitrary elements may be added using the $args associative array.
  920. */
  921. function format_rss_item($title, $link, $description, $args = array()) {
  922. $output = "<item>\n";
  923. $output .= ' <title>' . check_plain($title) . "</title>\n";
  924. $output .= ' <link>' . check_url($link) . "</link>\n";
  925. $output .= ' <description>' . check_plain($description) . "</description>\n";
  926. $output .= format_xml_elements($args);
  927. $output .= "</item>\n";
  928. return $output;
  929. }
  930. /**
  931. * Formats XML elements.
  932. *
  933. * @param $array
  934. * An array where each item represents an element and is either a:
  935. * - (key => value) pair (<key>value</key>)
  936. * - Associative array with fields:
  937. * - 'key': element name
  938. * - 'value': element contents
  939. * - 'attributes': associative array of element attributes
  940. *
  941. * In both cases, 'value' can be a simple string, or it can be another array
  942. * with the same format as $array itself for nesting.
  943. */
  944. function format_xml_elements($array) {
  945. $output = '';
  946. foreach ($array as $key => $value) {
  947. if (is_numeric($key)) {
  948. if ($value['key']) {
  949. $output .= ' <' . $value['key'];
  950. if (isset($value['attributes']) && is_array($value['attributes'])) {
  951. $output .= new Attribute($value['attributes']);
  952. }
  953. if (isset($value['value']) && $value['value'] != '') {
  954. $output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) . '</' . $value['key'] . ">\n";
  955. }
  956. else {
  957. $output .= " />\n";
  958. }
  959. }
  960. }
  961. else {
  962. $output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</$key>\n";
  963. }
  964. }
  965. return $output;
  966. }
  967. /**
  968. * Formats a string containing a count of items.
  969. *
  970. * This function ensures that the string is pluralized correctly. Since t() is
  971. * called by this function, make sure not to pass already-localized strings to
  972. * it.
  973. *
  974. * For example:
  975. * @code
  976. * $output = format_plural($node->comment_count, '1 comment', '@count comments');
  977. * @endcode
  978. *
  979. * Example with additional replacements:
  980. * @code
  981. * $output = format_plural($update_count,
  982. * 'Changed the content type of 1 post from %old-type to %new-type.',
  983. * 'Changed the content type of @count posts from %old-type to %new-type.',
  984. * array('%old-type' => $info->old_type, '%new-type' => $info->new_type));
  985. * @endcode
  986. *
  987. * @param $count
  988. * The item count to display.
  989. * @param $singular
  990. * The string for the singular case. Make sure it is clear this is singular,
  991. * to ease translation (e.g. use "1 new comment" instead of "1 new"). Do not
  992. * use @count in the singular string.
  993. * @param $plural
  994. * The string for the plural case. Make sure it is clear this is plural, to
  995. * ease translation. Use @count in place of the item count, as in
  996. * "@count new comments".
  997. * @param $args
  998. * An associative array of replacements to make after translation. Instances
  999. * of any key in this array are replaced with the corresponding value.
  1000. * Based on the first character of the key, the value is escaped and/or
  1001. * themed. See format_string(). Note that you do not need to include @count
  1002. * in this array; this replacement is done automatically for the plural case.
  1003. * @param $options
  1004. * An associative array of additional options. See t() for allowed keys.
  1005. *
  1006. * @return
  1007. * A translated string.
  1008. *
  1009. * @see t()
  1010. * @see format_string()
  1011. */
  1012. function format_plural($count, $singular, $plural, array $args = array(), array $options = array()) {
  1013. $args['@count'] = $count;
  1014. // Join both forms to search a translation.
  1015. $tranlatable_string = implode(LOCALE_PLURAL_DELIMITER, array($singular, $plural));
  1016. // Translate as usual.
  1017. $translated_strings = t($tranlatable_string, $args, $options);
  1018. // Split joined translation strings into array.
  1019. $translated_array = explode(LOCALE_PLURAL_DELIMITER, $translated_strings);
  1020. if ($count == 1) {
  1021. return $translated_array[0];
  1022. }
  1023. // Get the plural index through the gettext formula.
  1024. // @todo implement static variable to minimize function_exists() usage.
  1025. $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, isset($options['langcode']) ? $options['langcode'] : NULL) : -1;
  1026. if ($index == 0) {
  1027. // Singular form.
  1028. return $translated_array[0];
  1029. }
  1030. else {
  1031. if (isset($translated_array[$index])) {
  1032. // N-th plural form.
  1033. return $translated_array[$index];
  1034. }
  1035. else {
  1036. // If the index cannot be computed or there's no translation, use
  1037. // the second plural form as a fallback (which allows for most flexiblity
  1038. // with the replaceable @count value).
  1039. return $translated_array[1];
  1040. }
  1041. }
  1042. }
  1043. /**
  1044. * Parses a given byte count.
  1045. *
  1046. * @param $size
  1047. * A size expressed as a number of bytes with optional SI or IEC binary unit
  1048. * prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).
  1049. *
  1050. * @return
  1051. * An integer representation of the size in bytes.
  1052. */
  1053. function parse_size($size) {
  1054. $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size.
  1055. $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size.
  1056. if ($unit) {
  1057. // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by.
  1058. return round($size * pow(DRUPAL_KILOBYTE, stripos('bkmgtpezy', $unit[0])));
  1059. }
  1060. else {
  1061. return round($size);
  1062. }
  1063. }
  1064. /**
  1065. * Generates a string representation for the given byte count.
  1066. *
  1067. * @param $size
  1068. * A size in bytes.
  1069. * @param $langcode
  1070. * Optional language code to translate to a language other than what is used
  1071. * to display the page.
  1072. *
  1073. * @return
  1074. * A translated string representation of the size.
  1075. */
  1076. function format_size($size, $langcode = NULL) {
  1077. if ($size < DRUPAL_KILOBYTE) {
  1078. return format_plural($size, '1 byte', '@count bytes', array(), array('langcode' => $langcode));
  1079. }
  1080. else {
  1081. $size = $size / DRUPAL_KILOBYTE; // Convert bytes to kilobytes.
  1082. $units = array(
  1083. t('@size KB', array(), array('langcode' => $langcode)),
  1084. t('@size MB', array(), array('langcode' => $langcode)),
  1085. t('@size GB', array(), array('langcode' => $langcode)),
  1086. t('@size TB', array(), array('langcode' => $langcode)),
  1087. t('@size PB', array(), array('langcode' => $langcode)),
  1088. t('@size EB', array(), array('langcode' => $langcode)),
  1089. t('@size ZB', array(), array('langcode' => $langcode)),
  1090. t('@size YB', array(), array('langcode' => $langcode)),
  1091. );
  1092. foreach ($units as $unit) {
  1093. if (round($size, 2) >= DRUPAL_KILOBYTE) {
  1094. $size = $size / DRUPAL_KILOBYTE;
  1095. }
  1096. else {
  1097. break;
  1098. }
  1099. }
  1100. return str_replace('@size', round($size, 2), $unit);
  1101. }
  1102. }
  1103. /**
  1104. * Formats a time interval with the requested granularity.
  1105. *
  1106. * @param $interval
  1107. * The length of the interval in seconds.
  1108. * @param $granularity
  1109. * How many different units to display in the string.
  1110. * @param $langcode
  1111. * Optional language code to translate to a language other than
  1112. * what is used to display the page.
  1113. *
  1114. * @return
  1115. * A translated string representation of the interval.
  1116. */
  1117. function format_interval($interval, $granularity = 2, $langcode = NULL) {
  1118. $units = array(
  1119. '1 year|@count years' => 31536000,
  1120. '1 month|@count months' => 2592000,
  1121. '1 week|@count weeks' => 604800,
  1122. '1 day|@count days' => 86400,
  1123. '1 hour|@count hours' => 3600,
  1124. '1 min|@count min' => 60,
  1125. '1 sec|@count sec' => 1
  1126. );
  1127. $output = '';
  1128. foreach ($units as $key => $value) {
  1129. $key = explode('|', $key);
  1130. if ($interval >= $value) {
  1131. $output .= ($output ? ' ' : '') . format_plural(floor($interval / $value), $key[0], $key[1], array(), array('langcode' => $langcode));
  1132. $interval %= $value;
  1133. $granularity--;
  1134. }
  1135. if ($granularity == 0) {
  1136. break;
  1137. }
  1138. }
  1139. return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
  1140. }
  1141. /**
  1142. * Formats a date, using a date type or a custom date format string.
  1143. *
  1144. * @param $timestamp
  1145. * A UNIX timestamp to format.
  1146. * @param $type
  1147. * (optional) The format to use, one of:
  1148. * - One of the built-in formats: 'short', 'medium',
  1149. * 'long', 'html_datetime', 'html_date', 'html_time',
  1150. * 'html_yearless_date', 'html_week', 'html_month', 'html_year'.
  1151. * - The name of a date type defined by a module in
  1152. * hook_date_format_types(), if it's been assigned a format.
  1153. * - The machine name of an administrator-defined date format.
  1154. * - 'custom', to use $format.
  1155. * Defaults to 'medium'.
  1156. * @param $format
  1157. * (optional) If $type is 'custom', a PHP date format string suitable for
  1158. * input to date(). Use a backslash to escape ordinary text, so it does not
  1159. * get interpreted as date format characters.
  1160. * @param $timezone
  1161. * (optional) Time zone identifier, as described at
  1162. * http://php.net/manual/timezones.php Defaults to the time zone used to
  1163. * display the page.
  1164. * @param $langcode
  1165. * (optional) Language code to translate to. Defaults to the language used to
  1166. * display the page.
  1167. *
  1168. * @return
  1169. * A translated date string in the requested format.
  1170. *
  1171. * @see \Drupal\Component\Datetime\Date::format()
  1172. */
  1173. function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
  1174. return Drupal::service('date')->format($timestamp, $type, $format, $timezone, $langcode);
  1175. }
  1176. /**
  1177. * Returns an ISO8601 formatted date based on the given date.
  1178. *
  1179. * Callback for use within hook_rdf_mapping() implementations.
  1180. *
  1181. * @param $date
  1182. * A UNIX timestamp.
  1183. *
  1184. * @return string
  1185. * An ISO8601 formatted date.
  1186. */
  1187. function date_iso8601($date) {
  1188. // The DATE_ISO8601 constant cannot be used here because it does not match
  1189. // date('c') and produces invalid RDF markup.
  1190. return date('c', $date);
  1191. }
  1192. /**
  1193. * Translates a formatted date string.
  1194. *
  1195. * Callback for preg_replace_callback() within format_date().
  1196. */
  1197. function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
  1198. // We cache translations to avoid redundant and rather costly calls to t().
  1199. static $cache, $langcode;
  1200. if (!isset($matches)) {
  1201. $langcode = $new_langcode;
  1202. return;
  1203. }
  1204. $code = $matches[1];
  1205. $string = $matches[2];
  1206. if (!isset($cache[$langcode][$code][$string])) {
  1207. $options = array(
  1208. 'langcode' => $langcode,
  1209. );
  1210. if ($code == 'F') {
  1211. $options['context'] = 'Long month name';
  1212. }
  1213. if ($code == '') {
  1214. $cache[$langcode][$code][$string] = $string;
  1215. }
  1216. else {
  1217. $cache[$langcode][$code][$string] = t($string, array(), $options);
  1218. }
  1219. }
  1220. return $cache[$langcode][$code][$string];
  1221. }
  1222. /**
  1223. * Retrieves the correct datetime format type for this system.
  1224. *
  1225. * This value is sometimes required when the format type needs to be determined
  1226. * before a date can be created.
  1227. *
  1228. * @return string
  1229. * A string as defined in \DrupalComponent\Datetime\DateTimePlus.php: either
  1230. * 'intl' or 'php', depending on whether IntlDateFormatter is available.
  1231. */
  1232. function datetime_default_format_type() {
  1233. static $drupal_static_fast;
  1234. if (!isset($drupal_static_fast)) {
  1235. $drupal_static_fast['format_type'] = &drupal_static(__FUNCTION__);
  1236. }
  1237. $format_type = &$drupal_static_fast['format_type'];
  1238. if (!isset($format_type)) {
  1239. $date = new DrupalDateTime();
  1240. $format_type = $date->canUseIntl() ? DrupalDateTime::INTL : DrupalDateTime::PHP;
  1241. }
  1242. return $format_type;
  1243. }
  1244. /**
  1245. * @} End of "defgroup format".
  1246. */
  1247. /**
  1248. * Generates an internal or external URL.
  1249. *
  1250. * When creating links in modules, consider whether l() could be a better
  1251. * alternative than url().
  1252. *
  1253. * @see \Drupal\Core\Routing\PathBasedGeneratorInterface::generateFromPath().
  1254. */
  1255. function url($path = NULL, array $options = array()) {
  1256. $generator = Drupal::urlGenerator();
  1257. try {
  1258. $url = $generator->generateFromPath($path, $options);
  1259. }
  1260. catch (GeneratorNotInitializedException $e) {
  1261. // Fallback to using globals.
  1262. // @todo Remove this once there is no code that calls url() when there is
  1263. // no request.
  1264. global $base_url, $base_path, $script_path;
  1265. $generator->setBasePath($base_path);
  1266. $generator->setBaseUrl($base_url . '/');
  1267. $generator->setScriptPath($script_path);
  1268. $url = $generator->generateFromPath($path, $options);
  1269. }
  1270. return $url;
  1271. }
  1272. /**
  1273. * Returns TRUE if a path is external to Drupal (e.g. http://example.com).
  1274. *
  1275. * If a path cannot be assessed by Drupal's menu handler, then we must
  1276. * treat it as potentially insecure.
  1277. *
  1278. * @param $path
  1279. * The internal path or external URL being linked to, such as "node/34" or
  1280. * "http://example.com/foo".
  1281. *
  1282. * @return
  1283. * Boolean TRUE or FALSE, where TRUE indicates an external path.
  1284. */
  1285. function url_is_external($path) {
  1286. $colonpos = strpos($path, ':');
  1287. // Avoid calling drupal_strip_dangerous_protocols() if there is any
  1288. // slash (/), hash (#) or question_mark (?) before the colon (:)
  1289. // occurrence - if any - as this would clearly mean it is not a URL.
  1290. return $colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && drupal_strip_dangerous_protocols($path) == $path;
  1291. }
  1292. /**
  1293. * Formats an attribute string for an HTTP header.
  1294. *
  1295. * @param $attributes
  1296. * An associative array of attributes such as 'rel'.
  1297. *
  1298. * @return
  1299. * A ; separated string ready for insertion in a HTTP header. No escaping is
  1300. * performed for HTML entities, so this string is not safe to be printed.
  1301. *
  1302. * @see drupal_add_http_header()
  1303. */
  1304. function drupal_http_header_attributes(array $attributes = array()) {
  1305. foreach ($attributes as $attribute => &$data) {
  1306. if (is_array($data)) {
  1307. $data = implode(' ', $data);
  1308. }
  1309. $data = $attribute . '="' . $data . '"';
  1310. }
  1311. return $attributes ? ' ' . implode('; ', $attributes) : '';
  1312. }
  1313. /**
  1314. * Formats an internal or external URL link as an HTML anchor tag.
  1315. *
  1316. * This function correctly handles aliased paths and adds an 'active' class
  1317. * attribute to links that point to the current page (for theming), so all
  1318. * internal links output by modules should be generated by this function if
  1319. * possible.
  1320. *
  1321. * However, for links enclosed in translatable text you should use t() and
  1322. * embed the HTML anchor tag directly in the translated string. For example:
  1323. * @code
  1324. * t('Visit the <a href="@url">settings</a> page', array('@url' => url('admin')));
  1325. * @endcode
  1326. * This keeps the context of the link title ('settings' in the example) for
  1327. * translators.
  1328. *
  1329. * @param string|array $text
  1330. * The link text for the anchor tag as a translated string or render array.
  1331. * @param string $path
  1332. * The internal path or external URL being linked to, such as "node/34" or
  1333. * "http://example.com/foo". After the url() function is called to construct
  1334. * the URL from $path and $options, the resulting URL is passed through
  1335. * check_plain() before it is inserted into the HTML anchor tag, to ensure
  1336. * well-formed HTML. See url() for more information and notes.
  1337. * @param array $options
  1338. * An associative array of additional options. Defaults to an empty array. It
  1339. * may contain the following elements.
  1340. * - 'attributes': An associative array of HTML attributes to apply to the
  1341. * anchor tag. If element 'class' is included, it must be an array; 'title'
  1342. * must be a string; other elements are more flexible, as they just need
  1343. * to work as an argument for the constructor of the class
  1344. * Drupal\Core\Template\Attribute($options['attributes']).
  1345. * - 'html' (default FALSE): Whether $text is HTML or just plain-text. For
  1346. * example, to make an image tag into a link, this must be set to TRUE, or
  1347. * you will see the escaped HTML image tag. $text is not sanitized if
  1348. * 'html' is TRUE. The calling function must ensure that $text is already
  1349. * safe.
  1350. * - 'language': An optional language object. If the path being linked to is
  1351. * internal to the site, $options['language'] is used to determine whether
  1352. * the link is "active", or pointing to the current page (the language as
  1353. * well as the path must match). This element is also used by url().
  1354. * - Additional $options elements used by the url() function.
  1355. *
  1356. * @return string
  1357. * An HTML string containing a link to the given path.
  1358. *
  1359. * @see url()
  1360. * @see theme_link()
  1361. */
  1362. function l($text, $path, array $options = array()) {
  1363. // Start building a structured representation of our link to be altered later.
  1364. $variables = array(
  1365. 'text' => is_array($text) ? drupal_render($text) : $text,
  1366. 'path' => $path,
  1367. 'options' => $options,
  1368. );
  1369. // Merge in default options.
  1370. $variables['options'] += array(
  1371. 'attributes' => array(),
  1372. 'query' => array(),
  1373. 'html' => FALSE,
  1374. 'language' => NULL,
  1375. );
  1376. // Because l() is called very often we statically cache values that require an
  1377. // extra function call.
  1378. static $drupal_static_fast;
  1379. if (!isset($drupal_static_fast['active'])) {
  1380. $drupal_static_fast['active'] = &drupal_static(__FUNCTION__);
  1381. }
  1382. $active = &$drupal_static_fast['active'];
  1383. if (!isset($active)) {
  1384. $active = array(
  1385. 'path' => current_path(),
  1386. 'front_page' => drupal_is_front_page(),
  1387. 'language' => language(Language::TYPE_URL)->langcode,
  1388. 'query' => Drupal::service('request')->query->all(),
  1389. );
  1390. }
  1391. // Determine whether this link is "active', meaning that it links to the
  1392. // current page. It is important that we stop checking "active" conditions if
  1393. // we know the link is not active. This helps ensure that l() remains fast.
  1394. // An active link's path is equal to the current path.
  1395. $variables['url_is_active'] = ($path == $active['path'] || ($path == '<front>' && $active['front_page']))
  1396. // The language of an active link is equal to the current language.
  1397. && (empty($variables['options']['language']) || $variables['options']['language']->langcode == $active['language'])
  1398. // The query parameters of an active link are equal to the current parameters.
  1399. && ($variables['options']['query'] == $active['query']);
  1400. // Add the "active" class if appropriate.
  1401. if ($variables['url_is_active']) {
  1402. $variables['options']['attributes']['class'][] = 'active';
  1403. }
  1404. // Remove all HTML and PHP tags from a tooltip, calling expensive strip_tags()
  1405. // only when a quick strpos() gives suspicion tags are present.
  1406. if (isset($variables['options']['attributes']['title']) && strpos($variables['options']['attributes']['title'], '<') !== FALSE) {
  1407. $variables['options']['attributes']['title'] = strip_tags($variables['options']['attributes']['title']);
  1408. }
  1409. // Allow other modules to modify the structure of the link.
  1410. Drupal::moduleHandler()->alter('link', $variables);
  1411. // Move attributes out of options. url() doesn't need them.
  1412. $attributes = new Attribute($variables['options']['attributes']);
  1413. unset($variables['options']['attributes']);
  1414. // The result of url() is a plain-text URL. Because we are using it here
  1415. // in an HTML argument context, we need to encode it properly.
  1416. $url = check_plain(url($variables['path'], $variables['options']));
  1417. // Sanitize the link text if necessary.
  1418. $text = $variables['options']['html'] ? $variables['text'] : check_plain($variables['text']);
  1419. return '<a href="' . $url . '"' . $attributes . '>' . $text . '</a>';
  1420. }
  1421. /**
  1422. * Forms an associative array from a linear array.
  1423. *
  1424. * @see \Drupal\Component\Utility\MapArray::copyValuesToKeys()
  1425. */
  1426. function drupal_map_assoc($array, $callable = NULL) {
  1427. return MapArray::copyValuesToKeys($array, $callable);
  1428. }
  1429. /**
  1430. * Attempts to set the PHP maximum execution time.
  1431. *
  1432. * This function is a wrapper around the PHP function set_time_limit().
  1433. * When called, set_time_limit() restarts the timeout counter from zero.
  1434. * In other words, if the timeout is the default 30 seconds, and 25 seconds
  1435. * into script execution a call such as set_time_limit(20) is made, the
  1436. * script will run for a total of 45 seconds before timing out.
  1437. *
  1438. * It also means that it is possible to decrease the total time limit if
  1439. * the sum of the new time limit and the current time spent running the
  1440. * script is inferior to the original time limit. It is inherent to the way
  1441. * set_time_limit() works, it should rather be called with an appropriate
  1442. * value every time you need to allocate a certain amount of time
  1443. * to execute a task than only once at the beginning of the script.
  1444. *
  1445. * Before calling set_time_limit(), we check if this function is available
  1446. * because it could be disabled by the server administrator. We also hide all
  1447. * the errors that could occur when calling set_time_limit(), because it is
  1448. * not possible to reliably ensure that PHP or a security extension will
  1449. * not issue a warning/error if they prevent the use of this function.
  1450. *
  1451. * @param $time_limit
  1452. * An integer specifying the new time limit, in seconds. A value of 0
  1453. * indicates unlimited execution time.
  1454. *
  1455. * @ingroup php_wrappers
  1456. */
  1457. function drupal_set_time_limit($time_limit) {
  1458. if (function_exists('set_time_limit')) {
  1459. @set_time_limit($time_limit);
  1460. }
  1461. }
  1462. /**
  1463. * Returns the path to a system item (module, theme, etc.).
  1464. *
  1465. * @param $type
  1466. * The type of the item (i.e. theme, theme_engine, module, profile).
  1467. * @param $name
  1468. * The name of the item for which the path is requested.
  1469. *
  1470. * @return
  1471. * The path to the requested item or an empty string if the item is not found.
  1472. */
  1473. function drupal_get_path($type, $name) {
  1474. return dirname(drupal_get_filename($type, $name));
  1475. }
  1476. /**
  1477. * Returns the base URL path (i.e., directory) of the Drupal installation.
  1478. *
  1479. * base_path() adds a "/" to the beginning and end of the returned path if the
  1480. * path is not empty. At the very least, this will return "/".
  1481. *
  1482. * Examples:
  1483. * - http://example.com returns "/" because the path is empty.
  1484. * - http://example.com/drupal/folder returns "/drupal/folder/".
  1485. */
  1486. function base_path() {
  1487. return $GLOBALS['base_path'];
  1488. }
  1489. /**
  1490. * Adds a LINK tag with a distinct 'rel' attribute to the page's HEAD.
  1491. *
  1492. * This function can be called as long the HTML header hasn't been sent, which
  1493. * on normal pages is up through the preprocess step of theme('html'). Adding
  1494. * a link will overwrite a prior link with the exact same 'rel' and 'href'
  1495. * attributes.
  1496. *
  1497. * @param $attributes
  1498. * Associative array of element attributes including 'href' and 'rel'.
  1499. * @param $header
  1500. * Optional flag to determine if a HTTP 'Link:' header should be sent.
  1501. */
  1502. function drupal_add_html_head_link($attributes, $header = FALSE) {
  1503. $element = array(
  1504. '#tag' => 'link',
  1505. '#attributes' => $attributes,
  1506. );
  1507. $href = $attributes['href'];
  1508. if ($header) {
  1509. // Also add a HTTP header "Link:".
  1510. $href = '<' . check_plain($attributes['href']) . '>;';
  1511. unset($attributes['href']);
  1512. $element['#attached']['drupal_add_http_header'][] = array('Link', $href . drupal_http_header_attributes($attributes), TRUE);
  1513. }
  1514. drupal_add_html_head($element, 'drupal_add_html_head_link:' . $attributes['rel'] . ':' . $href);
  1515. }
  1516. /**
  1517. * Adds a cascading stylesheet to the stylesheet queue.
  1518. *
  1519. * Calling drupal_static_reset('drupal_add_css') will clear all cascading
  1520. * stylesheets added so far.
  1521. *
  1522. * If CSS aggregation/compression is enabled, all cascading style sheets added
  1523. * with $options['preprocess'] set to TRUE will be merged into one aggregate
  1524. * file and compressed by removing all extraneous white space.
  1525. * Preprocessed inline stylesheets will not be aggregated into this single file;
  1526. * instead, they are just compressed upon output on the page. Externally hosted
  1527. * stylesheets are never aggregated or compressed.
  1528. *
  1529. * The reason for aggregating the files is outlined quite thoroughly here:
  1530. * http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
  1531. * to request overhead, one bigger file just loads faster than two smaller ones
  1532. * half its size."
  1533. *
  1534. * $options['preprocess'] should be only set to TRUE when a file is required for
  1535. * all typical visitors and most pages of a site. It is critical that all
  1536. * preprocessed files are added unconditionally on every page, even if the
  1537. * files do not happen to be needed on a page. This is normally done by calling
  1538. * drupal_add_css() in a hook_page_build() implementation.
  1539. *
  1540. * Non-preprocessed files should only be added to the page when they are
  1541. * actually needed.
  1542. *
  1543. * @param $data
  1544. * (optional) The stylesheet data to be added, depending on what is passed
  1545. * through to the $options['type'] parameter:
  1546. * - 'file': The path to the CSS file relative to the base_path(), or a
  1547. * stream wrapper URI. For example: "modules/devel/devel.css" or
  1548. * "public://generated_css/stylesheet_1.css". Note that Modules should
  1549. * always prefix the names of their CSS files with the module name; for
  1550. * example, system-menus.css rather than simply menus.css. Themes can
  1551. * override module-supplied CSS files based on their filenames, and this
  1552. * prefixing helps prevent confusing name collisions for theme developers.
  1553. * See drupal_get_css() where the overrides are performed. Also, if the
  1554. * direction of the current language is right-to-left (Hebrew, Arabic,
  1555. * etc.), the function will also look for an RTL CSS file and append it to
  1556. * the list. The name of this file should have an '-rtl.css' suffix. For
  1557. * example, a CSS file called 'mymodule-name.css' will have a
  1558. * 'mymodule-name-rtl.css' file added to the list, if exists in the same
  1559. * directory. This CSS file should contain overrides for properties which
  1560. * should be reversed or otherwise different in a right-to-left display.
  1561. * - 'inline': A string of CSS that should be placed in the given scope. Note
  1562. * that it is better practice to use 'file' stylesheets, rather than
  1563. * 'inline', as the CSS would then be aggregated and cached.
  1564. * - 'external': The absolute path to an external CSS file that is not hosted
  1565. * on the local server. These files will not be aggregated if CSS
  1566. * aggregation is enabled.
  1567. * @param $options
  1568. * (optional) A string defining the 'type' of CSS that is being added in the
  1569. * $data parameter ('file', 'inline', or 'external'), or an array which can
  1570. * have any or all of the following keys:
  1571. * - 'type': The type of stylesheet being added. Available options are 'file',
  1572. * 'inline' or 'external'. Defaults to 'file'.
  1573. * - 'basename': Force a basename for the file being added. Modules are
  1574. * expected to use stylesheets with unique filenames, but integration of
  1575. * external libraries may make this impossible. The basename of
  1576. * 'core/modules/node/node.css' is 'node.css'. If the external library
  1577. * "node.js" ships with a 'node.css', then a different, unique basename
  1578. * would be 'node.js.css'.
  1579. * - 'group': A number identifying the aggregation group in which to add the
  1580. * stylesheet. Available constants are:
  1581. * - CSS_AGGREGATE_DEFAULT: (default) Any module-layer CSS.
  1582. * - CSS_AGGREGATE_THEME: Any theme-layer CSS.
  1583. * The aggregate group number affects load order and the CSS cascade.
  1584. * Stylesheets in an aggregate with a lower group number will be output to
  1585. * the page before stylesheets in an aggregate with a higher group number,
  1586. * so CSS within higher aggregate groups can take precendence over CSS
  1587. * within lower aggregate groups.
  1588. * - 'every_page': For optimal front-end performance when aggregation is
  1589. * enabled, this should be set to TRUE if the stylesheet is present on every
  1590. * page of the website for users for whom it is present at all. This
  1591. * defaults to FALSE. It is set to TRUE for stylesheets added via module and
  1592. * theme .info.yml files. Modules that add stylesheets within
  1593. * hook_page_build() implementations, or from other code that ensures that
  1594. * the stylesheet is added to all website pages, should also set this flag
  1595. * to TRUE. All stylesheets within the same group that have the 'every_page'
  1596. * flag set to TRUE and do not have 'preprocess' set to FALSE are aggregated
  1597. * together into a single aggregate file, and that aggregate file can be
  1598. * reused across a user's entire site visit, leading to faster navigation
  1599. * between pages.
  1600. * However, stylesheets that are only needed on pages less frequently
  1601. * visited, can be added by code that only runs for those particular pages,
  1602. * and that code should not set the 'every_page' flag. This minimizes the
  1603. * size of the aggregate file that the user needs to download when first
  1604. * visiting the website. Stylesheets without the 'every_page' flag are
  1605. * aggregated into a separate aggregate file. This other aggregate file is
  1606. * likely to change from page to page, and each new aggregate file needs to
  1607. * be downloaded when first encountered, so it should be kept relatively
  1608. * small by ensuring that most commonly needed stylesheets are added to
  1609. * every page.
  1610. * - 'weight': The weight of the stylesheet specifies the order in which the
  1611. * CSS will appear relative to other stylesheets with the same aggregate
  1612. * group and 'every_page' flag. The exact ordering of stylesheets is as
  1613. * follows:
  1614. * - First by aggregate group.
  1615. * - Then by the 'every_page' flag, with TRUE coming before FALSE.
  1616. * - Then by weight.
  1617. * - Then by the order in which the CSS was added. For example, all else
  1618. * being the same, a stylesheet added by a call to drupal_add_css() that
  1619. * happened later in the page request gets added to the page after one for
  1620. * which drupal_add_css() happened earlier in the page request.
  1621. * Available constants are:
  1622. * - CSS_BASE: Styles for HTML elements ("base" styles).
  1623. * - CSS_LAYOUT: Styles that layout a page.
  1624. * - CSS_COMPONENT: Styles for design components (and their associated
  1625. * states and skins.)
  1626. * - CSS_STATE: Styles for states that are not included with components.
  1627. * - CSS_SKIN: Styles for skins that are not included with components.
  1628. * The weight numbers follow the SMACSS convention of CSS categorization.
  1629. * See http://drupal.org/node/1887922
  1630. * - 'media': The media type for the stylesheet, e.g., all, print, screen.
  1631. * Defaults to 'all'. It is extremely important to leave this set to 'all'
  1632. * or it will negatively impact front-end peformance. Instead add a @media
  1633. * block to the included CSS file.
  1634. * - 'preprocess': If TRUE and CSS aggregation/compression is enabled, the
  1635. * styles will be aggregated and compressed. Defaults to TRUE.
  1636. * - 'browsers': An array containing information specifying which browsers
  1637. * should load the CSS item. See drupal_pre_render_conditional_comments()
  1638. * for details.
  1639. *
  1640. * @return
  1641. * An array of queued cascading stylesheets.
  1642. *
  1643. * @see drupal_get_css()
  1644. */
  1645. function drupal_add_css($data = NULL, $options = NULL) {
  1646. $css = &drupal_static(__FUNCTION__, array());
  1647. // Construct the options, taking the defaults into consideration.
  1648. if (isset($options)) {
  1649. if (!is_array($options)) {
  1650. $options = array('type' => $options);
  1651. }
  1652. }
  1653. else {
  1654. $options = array();
  1655. }
  1656. // Create an array of CSS files for each media type first, since each type needs to be served
  1657. // to the browser differently.
  1658. if (isset($data)) {
  1659. $options += array(
  1660. 'type' => 'file',
  1661. 'group' => CSS_AGGREGATE_DEFAULT,
  1662. 'weight' => 0,
  1663. 'every_page' => FALSE,
  1664. 'media' => 'all',
  1665. 'preprocess' => TRUE,
  1666. 'data' => $data,
  1667. 'browsers' => array(),
  1668. );
  1669. $options['browsers'] += array(
  1670. 'IE' => TRUE,
  1671. '!IE' => TRUE,
  1672. );
  1673. // Files with a query string cannot be preprocessed.
  1674. if ($options['type'] === 'file' && $options['preprocess'] && strpos($options['data'], '?') !== FALSE) {
  1675. $options['preprocess'] = FALSE;
  1676. }
  1677. // Always add a tiny value to the weight, to conserve the insertion order.
  1678. $options['weight'] += count($css) / 1000;
  1679. // Add the data to the CSS array depending on the type.
  1680. switch ($options['type']) {
  1681. case 'inline':
  1682. // For inline stylesheets, we don't want to use the $data as the array
  1683. // key as $data could be a very long string of CSS.
  1684. $css[] = $options;
  1685. break;
  1686. case 'file':
  1687. // Local CSS files are keyed by basename; if a file with the same
  1688. // basename is added more than once, it gets overridden.
  1689. // By default, take over the filename as basename.
  1690. if (!isset($options['basename'])) {
  1691. $options['basename'] = drupal_basename($data);
  1692. }
  1693. $css[$options['basename']] = $options;
  1694. break;
  1695. default:
  1696. // External files are keyed by their full URI, so the same CSS file is
  1697. // not added twice.
  1698. $css[$data] = $options;
  1699. }
  1700. }
  1701. return $css;
  1702. }
  1703. /**
  1704. * Returns a themed representation of all stylesheets to attach to the page.
  1705. *
  1706. * It loads the CSS in order, with 'module' first, then 'theme' afterwards.
  1707. * This ensures proper cascading of styles so themes can easily override
  1708. * module styles through CSS selectors.
  1709. *
  1710. * Themes may replace module-defined CSS files by adding a stylesheet with the
  1711. * same filename. For example, themes/bartik/system-menus.css would replace
  1712. * modules/system/system-menus.css. This allows themes to override complete
  1713. * CSS files, rather than specific selectors, when necessary.
  1714. *
  1715. * If the original CSS file is being overridden by a theme, the theme is
  1716. * responsible for supplying an accompanying RTL CSS file to replace the
  1717. * module's.
  1718. *
  1719. * @param $css
  1720. * (optional) An array of CSS files. If no array is provided, the default
  1721. * stylesheets array is used instead.
  1722. * @param $skip_alter
  1723. * (optional) If set to TRUE, this function skips calling drupal_alter() on
  1724. * $css, useful when the calling function passes a $css array that has already
  1725. * been altered.
  1726. *
  1727. * @return
  1728. * A string of XHTML CSS tags.
  1729. *
  1730. * @see drupal_add_css()
  1731. */
  1732. function drupal_get_css($css = NULL, $skip_alter = FALSE) {
  1733. global $theme_info;
  1734. if (!isset($css)) {
  1735. $css = drupal_add_css();
  1736. }
  1737. // Allow modules and themes to alter the CSS items.
  1738. if (!$skip_alter) {
  1739. drupal_alter('css', $css);
  1740. }
  1741. // Sort CSS items, so that they appear in the correct order.
  1742. uasort($css, 'drupal_sort_css_js');
  1743. // Allow themes to remove CSS files by basename.
  1744. if (!empty($theme_info->stylesheets_remove)) {
  1745. foreach ($css as $key => $options) {
  1746. if (isset($options['basename']) && isset($theme_info->stylesheets_remove[$options['basename']])) {
  1747. unset($css[$key]);
  1748. }
  1749. }
  1750. }
  1751. // Allow themes to conditionally override CSS files by basename.
  1752. if (!empty($theme_info->stylesheets_override)) {
  1753. foreach ($css as $key => $options) {
  1754. if (isset($options['basename']) && isset($theme_info->stylesheets_override[$options['basename']])) {
  1755. $css[$key]['data'] = $theme_info->stylesheets_override[$options['basename']];
  1756. }
  1757. }
  1758. }
  1759. // Render the HTML needed to load the CSS.
  1760. $styles = array(
  1761. '#type' => 'styles',
  1762. '#items' => $css,
  1763. );
  1764. if (!empty($setting)) {
  1765. $styles['#attached']['js'][] = array('type' => 'setting', 'data' => $setting);
  1766. }
  1767. return drupal_render($styles);
  1768. }
  1769. /**
  1770. * Sorts CSS and JavaScript resources.
  1771. *
  1772. * Callback for uasort() within:
  1773. * - drupal_get_css()
  1774. * - drupal_get_js()
  1775. *
  1776. * This sort order helps optimize front-end performance while providing modules
  1777. * and themes with the necessary control for ordering the CSS and JavaScript
  1778. * appearing on a page.
  1779. *
  1780. * @param $a
  1781. * First item for comparison. The compared items should be associative arrays
  1782. * of member items from drupal_add_css() or drupal_add_js().
  1783. * @param $b
  1784. * Second item for comparison.
  1785. *
  1786. * @see drupal_add_css()
  1787. * @see drupal_add_js()
  1788. */
  1789. function drupal_sort_css_js($a, $b) {
  1790. // First order by group, so that all items in the CSS_AGGREGATE_DEFAULT group
  1791. // appear before items in the CSS_AGGREGATE_THEME group. Modules may create
  1792. // additional groups by defining their own constants.
  1793. if ($a['group'] < $b['group']) {
  1794. return -1;
  1795. }
  1796. elseif ($a['group'] > $b['group']) {
  1797. return 1;
  1798. }
  1799. // Within a group, order all infrequently needed, page-specific files after
  1800. // common files needed throughout the website. Separating this way allows for
  1801. // the aggregate file generated for all of the common files to be reused
  1802. // across a site visit without being cut by a page using a less common file.
  1803. elseif ($a['every_page'] && !$b['every_page']) {
  1804. return -1;
  1805. }
  1806. elseif (!$a['every_page'] && $b['every_page']) {
  1807. return 1;
  1808. }
  1809. // Finally, order by weight.
  1810. elseif ($a['weight'] < $b['weight']) {
  1811. return -1;
  1812. }
  1813. elseif ($a['weight'] > $b['weight']) {
  1814. return 1;
  1815. }
  1816. else {
  1817. return 0;
  1818. }
  1819. }
  1820. /**
  1821. * Grouping callback: Groups CSS items by their types, media, and browsers.
  1822. *
  1823. * This function arranges the CSS items that are in the #items property of the
  1824. * styles element into groups. Arranging the CSS items into groups serves two
  1825. * purposes. When aggregation is enabled, files within a group are aggregated
  1826. * into a single file, significantly improving page loading performance by
  1827. * minimizing network traffic overhead. When aggregation is disabled, grouping
  1828. * allows multiple files to be loaded from a single STYLE tag, enabling sites
  1829. * with many modules enabled or a complex theme being used to stay within IE's
  1830. * 31 CSS inclusion tag limit: http://drupal.org/node/228818.
  1831. *
  1832. * This function puts multiple items into the same group if they are groupable
  1833. * and if they are for the same 'media' and 'browsers'. Items of the 'file' type
  1834. * are groupable if their 'preprocess' flag is TRUE, items of the 'inline' type
  1835. * are always groupable, and items of the 'external' type are never groupable.
  1836. * This function also ensures that the process of grouping items does not change
  1837. * their relative order. This requirement may result in multiple groups for the
  1838. * same type, media, and browsers, if needed to accommodate other items in
  1839. * between.
  1840. *
  1841. * @param $css
  1842. * An array of CSS items, as returned by drupal_add_css(), but after
  1843. * alteration performed by drupal_get_css().
  1844. *
  1845. * @return
  1846. * An array of CSS groups. Each group contains the same keys (e.g., 'media',
  1847. * 'data', etc.) as a CSS item from the $css parameter, with the value of
  1848. * each key applying to the group as a whole. Each group also contains an
  1849. * 'items' key, which is the subset of items from $css that are in the group.
  1850. *
  1851. * @see drupal_pre_render_styles()
  1852. * @see system_element_info()
  1853. */
  1854. function drupal_group_css($css) {
  1855. $groups = array();
  1856. // If a group can contain multiple items, we track the information that must
  1857. // be the same for each item in the group, so that when we iterate the next
  1858. // item, we can determine if it can be put into the current group, or if a
  1859. // new group needs to be made for it.
  1860. $current_group_keys = NULL;
  1861. // When creating a new group, we pre-increment $i, so by initializing it to
  1862. // -1, the first group will have index 0.
  1863. $i = -1;
  1864. foreach ($css as $item) {
  1865. // The browsers for which the CSS item needs to be loaded is part of the
  1866. // information that determines when a new group is needed, but the order of
  1867. // keys in the array doesn't matter, and we don't want a new group if all
  1868. // that's different is that order.
  1869. ksort($item['browsers']);
  1870. // If the item can be grouped with other items, set $group_keys to an array
  1871. // of information that must be the same for all items in its group. If the
  1872. // item can't be grouped with other items, set $group_keys to FALSE. We
  1873. // put items into a group that can be aggregated together: whether they will
  1874. // be aggregated is up to the _drupal_css_aggregate() function or an
  1875. // override of that function specified in hook_css_alter(), but regardless
  1876. // of the details of that function, a group represents items that can be
  1877. // aggregated. Since a group may be rendered with a single HTML tag, all
  1878. // items in the group must share the same information that would need to be
  1879. // part of that HTML tag.
  1880. switch ($item['type']) {
  1881. case 'file':
  1882. // Group file items if their 'preprocess' flag is TRUE.
  1883. // Help ensure maximum reuse of aggregate files by only grouping
  1884. // together items that share the same 'group' value and 'every_page'
  1885. // flag. See drupal_add_css() for details about that.
  1886. $group_keys = $item['preprocess'] ? array($item['type'], $item['group'], $item['every_page'], $item['media'], $item['browsers']) : FALSE;
  1887. break;
  1888. case 'inline':
  1889. // Always group inline items.
  1890. $group_keys = array($item['type'], $item['media'], $item['browsers']);
  1891. break;
  1892. case 'external':
  1893. // Do not group external items.
  1894. $group_keys = FALSE;
  1895. break;
  1896. }
  1897. // If the group keys don't match the most recent group we're working with,
  1898. // then a new group must be made.
  1899. if ($group_keys !== $current_group_keys) {
  1900. $i++;
  1901. // Initialize the new group with the same properties as the first item
  1902. // being placed into it. The item's 'data' and 'weight' properties are
  1903. // unique to the item and should not be carried over to the group.
  1904. $groups[$i] = $item;
  1905. unset($groups[$i]['data'], $groups[$i]['weight']);
  1906. $groups[$i]['items'] = array();
  1907. $current_group_keys = $group_keys ? $group_keys : NULL;
  1908. }
  1909. // Add the item to the current group.
  1910. $groups[$i]['items'][] = $item;
  1911. }
  1912. return $groups;
  1913. }
  1914. /**
  1915. * Aggregation callback: Aggregates CSS files and inline content.
  1916. *
  1917. * Having the browser load fewer CSS files results in much faster page loads
  1918. * than when it loads many small files. This function aggregates files within
  1919. * the same group into a single file unless the site-wide setting to do so is
  1920. * disabled (commonly the case during site development). To optimize download,
  1921. * it also compresses the aggregate files by removing comments, whitespace, and
  1922. * other unnecessary content. Additionally, this functions aggregates inline
  1923. * content together, regardless of the site-wide aggregation setting.
  1924. *
  1925. * @param $css_groups
  1926. * An array of CSS groups as returned by drupal_group_css(). This function
  1927. * modifies the group's 'data' property for each group that is aggregated.
  1928. *
  1929. * @see drupal_group_css()
  1930. * @see drupal_pre_render_styles()
  1931. * @see system_element_info()
  1932. */
  1933. function drupal_aggregate_css(&$css_groups) {
  1934. // Only aggregate during normal site operation.
  1935. if (defined('MAINTENANCE_MODE')) {
  1936. $preprocess_css = FALSE;
  1937. }
  1938. else {
  1939. $config = config('system.performance');
  1940. $preprocess_css = $config->get('css.preprocess');
  1941. }
  1942. // For each group that needs aggregation, aggregate its items.
  1943. foreach ($css_groups as $key => $group) {
  1944. switch ($group['type']) {
  1945. // If a file group can be aggregated into a single file, do so, and set
  1946. // the group's data property to the file path of the aggregate file.
  1947. case 'file':
  1948. if ($group['preprocess'] && $preprocess_css) {
  1949. $css_groups[$key]['data'] = drupal_build_css_cache($group['items']);
  1950. }
  1951. break;
  1952. // Aggregate all inline CSS content into the group's data property.
  1953. case 'inline':
  1954. $css_groups[$key]['data'] = '';
  1955. foreach ($group['items'] as $item) {
  1956. $css_groups[$key]['data'] .= drupal_load_stylesheet_content($item['data'], $item['preprocess']);
  1957. }
  1958. break;
  1959. }
  1960. }
  1961. }
  1962. /**
  1963. * Pre-render callback: Adds the elements needed for CSS tags to be rendered.
  1964. *
  1965. * For production websites, LINK tags are preferable to STYLE tags with @import
  1966. * statements, because:
  1967. * - They are the standard tag intended for linking to a resource.
  1968. * - On Firefox 2 and perhaps other browsers, CSS files included with @import
  1969. * statements don't get saved when saving the complete web page for offline
  1970. * use: http://drupal.org/node/145218.
  1971. * - On IE, if only LINK tags and no @import statements are used, all the CSS
  1972. * files are downloaded in parallel, resulting in faster page load, but if
  1973. * @import statements are used and span across multiple STYLE tags, all the
  1974. * ones from one STYLE tag must be downloaded before downloading begins for
  1975. * the next STYLE tag. Furthermore, IE7 does not support media declaration on
  1976. * the @import statement, so multiple STYLE tags must be used when different
  1977. * files are for different media types. Non-IE browsers always download in
  1978. * parallel, so this is an IE-specific performance quirk:
  1979. * http://www.stevesouders.com/blog/2009/04/09/dont-use-import/.
  1980. *
  1981. * However, IE has an annoying limit of 31 total CSS inclusion tags
  1982. * (http://drupal.org/node/228818) and LINK tags are limited to one file per
  1983. * tag, whereas STYLE tags can contain multiple @import statements allowing
  1984. * multiple files to be loaded per tag. When CSS aggregation is disabled, a
  1985. * Drupal site can easily have more than 31 CSS files that need to be loaded, so
  1986. * using LINK tags exclusively would result in a site that would display
  1987. * incorrectly in IE. Depending on different needs, different strategies can be
  1988. * employed to decide when to use LINK tags and when to use STYLE tags.
  1989. *
  1990. * The strategy employed by this function is to use LINK tags for all aggregate
  1991. * files and for all files that cannot be aggregated (e.g., if 'preprocess' is
  1992. * set to FALSE or the type is 'external'), and to use STYLE tags for groups
  1993. * of files that could be aggregated together but aren't (e.g., if the site-wide
  1994. * aggregation setting is disabled). This results in all LINK tags when
  1995. * aggregation is enabled, a guarantee that as many or only slightly more tags
  1996. * are used with aggregation disabled than enabled (so that if the limit were to
  1997. * be crossed with aggregation enabled, the site developer would also notice the
  1998. * problem while aggregation is disabled), and an easy way for a developer to
  1999. * view HTML source while aggregation is disabled and know what files will be
  2000. * aggregated together when aggregation becomes enabled.
  2001. *
  2002. * This function evaluates the aggregation enabled/disabled condition on a group
  2003. * by group basis by testing whether an aggregate file has been made for the
  2004. * group rather than by testing the site-wide aggregation setting. This allows
  2005. * this function to work correctly even if modules have implemented custom
  2006. * logic for grouping and aggregating files.
  2007. *
  2008. * @param $element
  2009. * A render array containing:
  2010. * - '#items': The CSS items as returned by drupal_add_css() and altered by
  2011. * drupal_get_css().
  2012. * - '#group_callback': A function to call to group #items to enable the use
  2013. * of fewer tags by aggregating files and/or using multiple @import
  2014. * statements within a single tag.
  2015. * - '#aggregate_callback': A function to call to aggregate the items within
  2016. * the groups arranged by the #group_callback function.
  2017. *
  2018. * @return
  2019. * A render array that will render to a string of XHTML CSS tags.
  2020. *
  2021. * @see drupal_get_css()
  2022. */
  2023. function drupal_pre_render_styles($elements) {
  2024. // Group and aggregate the items.
  2025. if (isset($elements['#group_callback'])) {
  2026. $elements['#groups'] = $elements['#group_callback']($elements['#items']);
  2027. }
  2028. if (isset($elements['#aggregate_callback'])) {
  2029. $elements['#aggregate_callback']($elements['#groups']);
  2030. }
  2031. // A dummy query-string is added to filenames, to gain control over
  2032. // browser-caching. The string changes on every update or full cache
  2033. // flush, forcing browsers to load a new copy of the files, as the
  2034. // URL changed.
  2035. $query_string = variable_get('css_js_query_string', '0');
  2036. // For inline CSS to validate as XHTML, all CSS containing XHTML needs to be
  2037. // wrapped in CDATA. To make that backwards compatible with HTML 4, we need to
  2038. // comment out the CDATA-tag.
  2039. $embed_prefix = "\n/* <![CDATA[ */\n";
  2040. $embed_suffix = "\n/* ]]> */\n";
  2041. // Defaults for LINK and STYLE elements.
  2042. $link_element_defaults = array(
  2043. '#type' => 'html_tag',
  2044. '#tag' => 'link',
  2045. '#attributes' => array(
  2046. 'rel' => 'stylesheet',
  2047. ),
  2048. );
  2049. $style_element_defaults = array(
  2050. '#type' => 'html_tag',
  2051. '#tag' => 'style',
  2052. );
  2053. // Loop through each group.
  2054. foreach ($elements['#groups'] as $group) {
  2055. switch ($group['type']) {
  2056. // For file items, there are three possibilites.
  2057. // - The group has been aggregated: in this case, output a LINK tag for
  2058. // the aggregate file.
  2059. // - The group can be aggregated but has not been (most likely because
  2060. // the site administrator disabled the site-wide setting): in this case,
  2061. // output as few STYLE tags for the group as possible, using @import
  2062. // statement for each file in the group. This enables us to stay within
  2063. // IE's limit of 31 total CSS inclusion tags.
  2064. // - The group contains items not eligible for aggregation (their
  2065. // 'preprocess' flag has been set to FALSE): in this case, output a LINK
  2066. // tag for each file.
  2067. case 'file':
  2068. // The group has been aggregated into a single file: output a LINK tag
  2069. // for the aggregate file.
  2070. if (isset($group['data'])) {
  2071. $element = $link_element_defaults;
  2072. $element['#attributes']['href'] = file_create_url($group['data']);
  2073. $element['#attributes']['media'] = $group['media'];
  2074. $element['#browsers'] = $group['browsers'];
  2075. $elements[] = $element;
  2076. }
  2077. // The group can be aggregated, but hasn't been: combine multiple items
  2078. // into as few STYLE tags as possible.
  2079. elseif ($group['preprocess']) {
  2080. $import = array();
  2081. foreach ($group['items'] as $item) {
  2082. // The dummy query string needs to be added to the URL to control
  2083. // browser-caching. IE7 does not support a media type on the
  2084. // @import statement, so we instead specify the media for the
  2085. // group on the STYLE tag.
  2086. $import[] = '@import url("' . check_plain(file_create_url($item['data']) . '?' . $query_string) . '");';
  2087. }
  2088. // In addition to IE's limit of 31 total CSS inclusion tags, it also
  2089. // has a limit of 31 @import statements per STYLE tag.
  2090. while (!empty($import)) {
  2091. $import_batch = array_slice($import, 0, 31);
  2092. $import = array_slice($import, 31);
  2093. $element = $style_element_defaults;
  2094. // This simplifies the JavaScript regex, allowing each line
  2095. // (separated by \n) to be treated as a completely different string.
  2096. // This means that we can use ^ and $ on one line at a time, and not
  2097. // worry about style tags since they'll never match the regex.
  2098. $element['#value'] = "\n" . implode("\n", $import_batch) . "\n";
  2099. $element['#attributes']['media'] = $group['media'];
  2100. $element['#browsers'] = $group['browsers'];
  2101. $elements[] = $element;
  2102. }
  2103. }
  2104. // The group contains items ineligible for aggregation: output a LINK
  2105. // tag for each file.
  2106. else {
  2107. foreach ($group['items'] as $item) {
  2108. $element = $link_element_defaults;
  2109. // The dummy query string needs to be added to the URL to control
  2110. // browser-caching.
  2111. $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
  2112. $element['#attributes']['href'] = file_create_url($item['data']) . $query_string_separator . $query_string;
  2113. $element['#attributes']['media'] = $item['media'];
  2114. $element['#browsers'] = $group['browsers'];
  2115. $elements[] = $element;
  2116. }
  2117. }
  2118. break;
  2119. // For inline content, the 'data' property contains the CSS content. If
  2120. // the group's 'data' property is set, then output it in a single STYLE
  2121. // tag. Otherwise, output a separate STYLE tag for each item.
  2122. case 'inline':
  2123. if (isset($group['data'])) {
  2124. $element = $style_element_defaults;
  2125. $element['#value'] = $group['data'];
  2126. $element['#value_prefix'] = $embed_prefix;
  2127. $element['#value_suffix'] = $embed_suffix;
  2128. $element['#attributes']['media'] = $group['media'];
  2129. $element['#browsers'] = $group['browsers'];
  2130. $elements[] = $element;
  2131. }
  2132. else {
  2133. foreach ($group['items'] as $item) {
  2134. $element = $style_element_defaults;
  2135. $element['#value'] = $item['data'];
  2136. $element['#value_prefix'] = $embed_prefix;
  2137. $element['#value_suffix'] = $embed_suffix;
  2138. $element['#attributes']['media'] = $item['media'];
  2139. $element['#browsers'] = $group['browsers'];
  2140. $elements[] = $element;
  2141. }
  2142. }
  2143. break;
  2144. // Output a LINK tag for each external item. The item's 'data' property
  2145. // contains the full URL.
  2146. case 'external':
  2147. foreach ($group['items'] as $item) {
  2148. $element = $link_element_defaults;
  2149. $element['#attributes']['href'] = $item['data'];
  2150. $element['#attributes']['media'] = $item['media'];
  2151. $element['#browsers'] = $group['browsers'];
  2152. $elements[] = $element;
  2153. }
  2154. break;
  2155. }
  2156. }
  2157. return $elements;
  2158. }
  2159. /**
  2160. * Aggregates and optimizes CSS files into a cache file in the files directory.
  2161. *
  2162. * The file name for the CSS cache file is generated from the hash of the
  2163. * aggregated contents of the files in $css. This forces proxies and browsers
  2164. * to download new CSS when the CSS changes.
  2165. *
  2166. * The cache file name is retrieved on a page load via a lookup variable that
  2167. * contains an associative array. The array key is the hash of the file names
  2168. * in $css while the value is the cache file name. The cache file is generated
  2169. * in two cases. First, if there is no file name value for the key, which will
  2170. * happen if a new file name has been added to $css or after the lookup
  2171. * variable is emptied to force a rebuild of the cache. Second, the cache file
  2172. * is generated if it is missing on disk. Old cache files are not deleted
  2173. * immediately when the lookup variable is emptied, but are deleted after a set
  2174. * period by drupal_delete_file_if_stale(). This ensures that files referenced
  2175. * by a cached page will still be available.
  2176. *
  2177. * @param $css
  2178. * An array of CSS files to aggregate and compress into one file.
  2179. *
  2180. * @return
  2181. * The URI of the CSS cache file, or FALSE if the file could not be saved.
  2182. */
  2183. function drupal_build_css_cache($css) {
  2184. $data = '';
  2185. $uri = '';
  2186. $map = Drupal::state()->get('drupal_css_cache_files') ?: array();
  2187. // Create a new array so that only the file names are used to create the hash.
  2188. // This prevents new aggregates from being created unnecessarily.
  2189. $css_data = array();
  2190. foreach ($css as $css_file) {
  2191. $css_data[] = $css_file['data'];
  2192. }
  2193. $key = hash('sha256', serialize($css_data));
  2194. if (isset($map[$key])) {
  2195. $uri = $map[$key];
  2196. }
  2197. if (empty($uri) || !file_exists($uri)) {
  2198. // Build aggregate CSS file.
  2199. foreach ($css as $stylesheet) {
  2200. // Only 'file' stylesheets can be aggregated.
  2201. if ($stylesheet['type'] == 'file') {
  2202. $contents = drupal_load_stylesheet($stylesheet['data'], TRUE);
  2203. // Get the parent directory of this file, relative to the Drupal root.
  2204. $css_base_url = substr($stylesheet['data'], 0, strrpos($stylesheet['data'], '/'));
  2205. _drupal_build_css_path(NULL, $css_base_url . '/');
  2206. // Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
  2207. $data .= preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);
  2208. }
  2209. }
  2210. // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
  2211. // @import rules must proceed any other style, so we move those to the top.
  2212. $regexp = '/@import[^;]+;/i';
  2213. preg_match_all($regexp, $data, $matches);
  2214. $data = preg_replace($regexp, '', $data);
  2215. $data = implode('', $matches[0]) . $data;
  2216. // Prefix filename to prevent blocking by firewalls which reject files
  2217. // starting with "ad*".
  2218. $filename = 'css_' . Crypt::hashBase64($data) . '.css';
  2219. // Create the css/ within the files folder.
  2220. $csspath = 'public://css';
  2221. $uri = $csspath . '/' . $filename;
  2222. // Create the CSS file.
  2223. file_prepare_directory($csspath, FILE_CREATE_DIRECTORY);
  2224. if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
  2225. return FALSE;
  2226. }
  2227. // If CSS gzip compression is enabled and the zlib extension is available
  2228. // then create a gzipped version of this file. This file is served
  2229. // conditionally to browsers that accept gzip using .htaccess rules.
  2230. // It's possible that the rewrite rules in .htaccess aren't working on this
  2231. // server, but there's no harm (other than the time spent generating the
  2232. // file) in generating the file anyway. Sites on servers where rewrite rules
  2233. // aren't working can set css.gzip to FALSE in order to skip
  2234. // generating a file that won't be used.
  2235. if (config('system.performance')->get('css.gzip') && extension_loaded('zlib')) {
  2236. if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
  2237. return FALSE;
  2238. }
  2239. }
  2240. // Save the updated map.
  2241. $map[$key] = $uri;
  2242. Drupal::state()->set('drupal_css_cache_files', $map);
  2243. }
  2244. return $uri;
  2245. }
  2246. /**
  2247. * Prefixes all paths within a CSS file for drupal_build_css_cache().
  2248. */
  2249. function _drupal_build_css_path($matches, $base = NULL) {
  2250. $_base = &drupal_static(__FUNCTION__);
  2251. // Store base path for preg_replace_callback.
  2252. if (isset($base)) {
  2253. $_base = $base;
  2254. }
  2255. // Prefix with base and remove '../' segments where possible.
  2256. $path = $_base . $matches[1];
  2257. $last = '';
  2258. while ($path != $last) {
  2259. $last = $path;
  2260. $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
  2261. }
  2262. return 'url(' . file_create_url($path) . ')';
  2263. }
  2264. /**
  2265. * Loads the stylesheet and resolves all @import commands.
  2266. *
  2267. * Loads a stylesheet and replaces @import commands with the contents of the
  2268. * imported file. Use this instead of file_get_contents when processing
  2269. * stylesheets.
  2270. *
  2271. * The returned contents are compressed removing white space and comments only
  2272. * when CSS aggregation is enabled. This optimization will not apply for
  2273. * color.module enabled themes with CSS aggregation turned off.
  2274. *
  2275. * @param $file
  2276. * Name of the stylesheet to be processed.
  2277. * @param $optimize
  2278. * Defines if CSS contents should be compressed or not.
  2279. * @param $reset_basepath
  2280. * Used internally to facilitate recursive resolution of @import commands.
  2281. *
  2282. * @return
  2283. * Contents of the stylesheet, including any resolved @import commands.
  2284. */
  2285. function drupal_load_stylesheet($file, $optimize = NULL, $reset_basepath = TRUE) {
  2286. // These statics are not cache variables, so we don't use drupal_static().
  2287. static $_optimize, $basepath;
  2288. if ($reset_basepath) {
  2289. $basepath = '';
  2290. }
  2291. // Store the value of $optimize for preg_replace_callback with nested
  2292. // @import loops.
  2293. if (isset($optimize)) {
  2294. $_optimize = $optimize;
  2295. }
  2296. // Stylesheets are relative one to each other. Start by adding a base path
  2297. // prefix provided by the parent stylesheet (if necessary).
  2298. if ($basepath && !file_uri_scheme($file)) {
  2299. $file = $basepath . '/' . $file;
  2300. }
  2301. $basepath = dirname($file);
  2302. // Load the CSS stylesheet. We suppress errors because themes may specify
  2303. // stylesheets in their .info.yml file that don't exist in the theme's path,
  2304. // but are merely there to disable certain module CSS files.
  2305. if ($contents = @file_get_contents($file)) {
  2306. // Return the processed stylesheet.
  2307. return drupal_load_stylesheet_content($contents, $_optimize);
  2308. }
  2309. return '';
  2310. }
  2311. /**
  2312. * Processes the contents of a stylesheet for aggregation.
  2313. *
  2314. * @param $contents
  2315. * The contents of the stylesheet.
  2316. * @param $optimize
  2317. * (optional) Boolean whether CSS contents should be minified. Defaults to
  2318. * FALSE.
  2319. *
  2320. * @return
  2321. * Contents of the stylesheet including the imported stylesheets.
  2322. */
  2323. function drupal_load_stylesheet_content($contents, $optimize = FALSE) {
  2324. // Remove multiple charset declarations for standards compliance (and fixing Safari problems).
  2325. $contents = preg_replace('/^@charset\s+[\'"](\S*)\b[\'"];/i', '', $contents);
  2326. if ($optimize) {
  2327. // Perform some safe CSS optimizations.
  2328. // Regexp to match comment blocks.
  2329. $comment = '/\*[^*]*\*+(?:[^/*][^*]*\*+)*/';
  2330. // Regexp to match double quoted strings.
  2331. $double_quot = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
  2332. // Regexp to match single quoted strings.
  2333. $single_quot = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'";
  2334. // Strip all comment blocks, but keep double/single quoted strings.
  2335. $contents = preg_replace(
  2336. "<($double_quot|$single_quot)|$comment>Ss",
  2337. "$1",
  2338. $contents
  2339. );
  2340. // Remove certain whitespace.
  2341. // There are different conditions for removing leading and trailing
  2342. // whitespace.
  2343. // @see http://php.net/manual/regexp.reference.subpatterns.php
  2344. $contents = preg_replace('<
  2345. # Strip leading and trailing whitespace.
  2346. \s*([@{};,])\s*
  2347. # Strip only leading whitespace from:
  2348. # - Closing parenthesis: Retain "@media (bar) and foo".
  2349. | \s+([\)])
  2350. # Strip only trailing whitespace from:
  2351. # - Opening parenthesis: Retain "@media (bar) and foo".
  2352. # - Colon: Retain :pseudo-selectors.
  2353. | ([\(:])\s+
  2354. >xS',
  2355. // Only one of the three capturing groups will match, so its reference
  2356. // will contain the wanted value and the references for the
  2357. // two non-matching groups will be replaced with empty strings.
  2358. '$1$2$3',
  2359. $contents
  2360. );
  2361. // End the file with a new line.
  2362. $contents = trim($contents);
  2363. $contents .= "\n";
  2364. }
  2365. // Replaces @import commands with the actual stylesheet content.
  2366. // This happens recursively but omits external files.
  2367. $contents = preg_replace_callback('/@import\s*(?:url\(\s*)?[\'"]?(?![a-z]+:)([^\'"\()]+)[\'"]?\s*\)?\s*;/', '_drupal_load_stylesheet', $contents);
  2368. return $contents;
  2369. }
  2370. /**
  2371. * Loads stylesheets recursively and returns contents with corrected paths.
  2372. *
  2373. * This function is used for recursive loading of stylesheets and
  2374. * returns the stylesheet content with all url() paths corrected.
  2375. */
  2376. function _drupal_load_stylesheet($matches) {
  2377. $filename = $matches[1];
  2378. // Load the imported stylesheet and replace @import commands in there as well.
  2379. $file = drupal_load_stylesheet($filename, NULL, FALSE);
  2380. // Determine the file's directory.
  2381. $directory = dirname($filename);
  2382. // If the file is in the current directory, make sure '.' doesn't appear in
  2383. // the url() path.
  2384. $directory = $directory == '.' ? '' : $directory .'/';
  2385. // Alter all internal url() paths. Leave external paths alone. We don't need
  2386. // to normalize absolute paths here (i.e. remove folder/... segments) because
  2387. // that will be done later.
  2388. return preg_replace('/url\(\s*([\'"]?)(?![a-z]+:|\/+)/i', 'url(\1'. $directory, $file);
  2389. }
  2390. /**
  2391. * Deletes old cached CSS files.
  2392. */
  2393. function drupal_clear_css_cache() {
  2394. Drupal::state()->delete('drupal_css_cache_files');
  2395. file_scan_directory('public://css', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
  2396. }
  2397. /**
  2398. * Deletes files modified more than a set time ago.
  2399. *
  2400. * Callback for file_scan_directory() within:
  2401. * - drupal_clear_css_cache()
  2402. * - drupal_clear_js_cache()
  2403. */
  2404. function drupal_delete_file_if_stale($uri) {
  2405. // Default stale file threshold is 30 days.
  2406. if (REQUEST_TIME - filemtime($uri) > config('system.performance')->get('stale_file_threshold')) {
  2407. file_unmanaged_delete($uri);
  2408. }
  2409. }
  2410. /**
  2411. * Prepares a string for use as a CSS identifier (element, class, or ID name).
  2412. *
  2413. * http://www.w3.org/TR/CSS21/syndata.html#characters shows the syntax for valid
  2414. * CSS identifiers (including element names, classes, and IDs in selectors.)
  2415. *
  2416. * @param $identifier
  2417. * The identifier to clean.
  2418. * @param $filter
  2419. * An array of string replacements to use on the identifier.
  2420. *
  2421. * @return
  2422. * The cleaned identifier.
  2423. */
  2424. function drupal_clean_css_identifier($identifier, $filter = array(' ' => '-', '_' => '-', '__' => '__', '/' => '-', '[' => '-', ']' => '')) {
  2425. // By default, we filter using Drupal's coding standards.
  2426. $identifier = strtr($identifier, $filter);
  2427. // Valid characters in a CSS identifier are:
  2428. // - the hyphen (U+002D)
  2429. // - a-z (U+0030 - U+0039)
  2430. // - A-Z (U+0041 - U+005A)
  2431. // - the underscore (U+005F)
  2432. // - 0-9 (U+0061 - U+007A)
  2433. // - ISO 10646 characters U+00A1 and higher
  2434. // We strip out any character not in the above list.
  2435. $identifier = preg_replace('/[^\x{002D}\x{0030}-\x{0039}\x{0041}-\x{005A}\x{005F}\x{0061}-\x{007A}\x{00A1}-\x{FFFF}]/u', '', $identifier);
  2436. return $identifier;
  2437. }
  2438. /**
  2439. * Prepares a string for use as a valid class name.
  2440. *
  2441. * Do not pass one string containing multiple classes as they will be
  2442. * incorrectly concatenated with dashes, i.e. "one two" will become "one-two".
  2443. *
  2444. * @param $class
  2445. * The class name to clean.
  2446. *
  2447. * @return
  2448. * The cleaned class name.
  2449. */
  2450. function drupal_html_class($class) {
  2451. // The output of this function will never change, so this uses a normal
  2452. // static instead of drupal_static().
  2453. static $classes = array();
  2454. if (!isset($classes[$class])) {
  2455. $classes[$class] = drupal_clean_css_identifier(drupal_strtolower($class));
  2456. }
  2457. return $classes[$class];
  2458. }
  2459. /**
  2460. * Prepares a string for use as a valid HTML ID and guarantees uniqueness.
  2461. *
  2462. * This function ensures that each passed HTML ID value only exists once on the
  2463. * page. By tracking the already returned ids, this function enables forms,
  2464. * blocks, and other content to be output multiple times on the same page,
  2465. * without breaking (X)HTML validation.
  2466. *
  2467. * For already existing IDs, a counter is appended to the ID string. Therefore,
  2468. * JavaScript and CSS code should not rely on any value that was generated by
  2469. * this function and instead should rely on manually added CSS classes or
  2470. * similarly reliable constructs.
  2471. *
  2472. * Two consecutive hyphens separate the counter from the original ID. To manage
  2473. * uniqueness across multiple Ajax requests on the same page, Ajax requests
  2474. * POST an array of all IDs currently present on the page, which are used to
  2475. * prime this function's cache upon first invocation.
  2476. *
  2477. * To allow reverse-parsing of IDs submitted via Ajax, any multiple consecutive
  2478. * hyphens in the originally passed $id are replaced with a single hyphen.
  2479. *
  2480. * @param $id
  2481. * The ID to clean.
  2482. *
  2483. * @return
  2484. * The cleaned ID.
  2485. */
  2486. function drupal_html_id($id) {
  2487. // If this is an Ajax request, then content returned by this page request will
  2488. // be merged with content already on the base page. The HTML IDs must be
  2489. // unique for the fully merged content. Therefore, initialize $seen_ids to
  2490. // take into account IDs that are already in use on the base page.
  2491. $seen_ids_init = &drupal_static(__FUNCTION__ . ':init');
  2492. if (!isset($seen_ids_init)) {
  2493. // Ideally, Drupal would provide an API to persist state information about
  2494. // prior page requests in the database, and we'd be able to add this
  2495. // function's $seen_ids static variable to that state information in order
  2496. // to have it properly initialized for this page request. However, no such
  2497. // page state API exists, so instead, ajax.js adds all of the in-use HTML
  2498. // IDs to the POST data of Ajax submissions. Direct use of $_POST is
  2499. // normally not recommended as it could open up security risks, but because
  2500. // the raw POST data is cast to a number before being returned by this
  2501. // function, this usage is safe.
  2502. if (empty($_POST['ajax_html_ids'])) {
  2503. $seen_ids_init = array();
  2504. }
  2505. else {
  2506. // This function ensures uniqueness by appending a counter to the base id
  2507. // requested by the calling function after the first occurrence of that
  2508. // requested id. $_POST['ajax_html_ids'] contains the ids as they were
  2509. // returned by this function, potentially with the appended counter, so
  2510. // we parse that to reconstruct the $seen_ids array.
  2511. $ajax_html_ids = explode(' ', $_POST['ajax_html_ids']);
  2512. foreach ($ajax_html_ids as $seen_id) {
  2513. // We rely on '--' being used solely for separating a base id from the
  2514. // counter, which this function ensures when returning an id.
  2515. $parts = explode('--', $seen_id, 2);
  2516. if (!empty($parts[1]) && is_numeric($parts[1])) {
  2517. list($seen_id, $i) = $parts;
  2518. }
  2519. else {
  2520. $i = 1;
  2521. }
  2522. if (!isset($seen_ids_init[$seen_id]) || ($i > $seen_ids_init[$seen_id])) {
  2523. $seen_ids_init[$seen_id] = $i;
  2524. }
  2525. }
  2526. }
  2527. }
  2528. $seen_ids = &drupal_static(__FUNCTION__, $seen_ids_init);
  2529. $id = strtr(drupal_strtolower($id), array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
  2530. // As defined in http://www.w3.org/TR/html4/types.html#type-name, HTML IDs can
  2531. // only contain letters, digits ([0-9]), hyphens ("-"), underscores ("_"),
  2532. // colons (":"), and periods ("."). We strip out any character not in that
  2533. // list. Note that the CSS spec doesn't allow colons or periods in identifiers
  2534. // (http://www.w3.org/TR/CSS21/syndata.html#characters), so we strip those two
  2535. // characters as well.
  2536. $id = preg_replace('/[^A-Za-z0-9\-_]/', '', $id);
  2537. // Removing multiple consecutive hyphens.
  2538. $id = preg_replace('/\-+/', '-', $id);
  2539. // Ensure IDs are unique by appending a counter after the first occurrence.
  2540. // The counter needs to be appended with a delimiter that does not exist in
  2541. // the base ID. Requiring a unique delimiter helps ensure that we really do
  2542. // return unique IDs and also helps us re-create the $seen_ids array during
  2543. // Ajax requests.
  2544. if (isset($seen_ids[$id])) {
  2545. $id = $id . '--' . ++$seen_ids[$id];
  2546. }
  2547. else {
  2548. $seen_ids[$id] = 1;
  2549. }
  2550. return $id;
  2551. }
  2552. /**
  2553. * Adds a JavaScript file, setting, or inline code to the page.
  2554. *
  2555. * The behavior of this function depends on the parameters it is called with.
  2556. * Generally, it handles the addition of JavaScript to the page, either as
  2557. * reference to an existing file or as inline code. The following actions can be
  2558. * performed using this function:
  2559. * - Add a file ('file'): Adds a reference to a JavaScript file to the page.
  2560. * - Add inline JavaScript code ('inline'): Executes a piece of JavaScript code
  2561. * on the current page by placing the code directly in the page (for example,
  2562. * to tell the user that a new message arrived, by opening a pop up, alert
  2563. * box, etc.). This should only be used for JavaScript that cannot be executed
  2564. * from a file. When adding inline code, make sure that you are not relying on
  2565. * $() being the jQuery function. Wrap your code in
  2566. * @code (function ($) {... })(jQuery); @endcode
  2567. * or use jQuery() instead of $().
  2568. * - Add external JavaScript ('external'): Allows the inclusion of external
  2569. * JavaScript files that are not hosted on the local server. Note that these
  2570. * external JavaScript references do not get aggregated when preprocessing is
  2571. * on.
  2572. * - Add settings ('setting'): Adds settings to Drupal's global storage of
  2573. * JavaScript settings. Per-page settings are required by some modules to
  2574. * function properly. All settings will be accessible at Drupal.settings.
  2575. *
  2576. * Examples:
  2577. * @code
  2578. * drupal_add_js('core/misc/collapse.js');
  2579. * drupal_add_js('core/misc/collapse.js', 'file');
  2580. * drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  2581. * drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
  2582. * array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
  2583. * );
  2584. * drupal_add_js('http://example.com/example.js', 'external');
  2585. * drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');
  2586. * @endcode
  2587. *
  2588. * Calling drupal_static_reset('drupal_add_js') will clear all JavaScript added
  2589. * so far.
  2590. *
  2591. * If JavaScript aggregation is enabled, all JavaScript files added with
  2592. * $options['preprocess'] set to TRUE will be merged into one aggregate file.
  2593. * Preprocessed inline JavaScript will not be aggregated into this single file.
  2594. * Externally hosted JavaScripts are never aggregated.
  2595. *
  2596. * The reason for aggregating the files is outlined quite thoroughly here:
  2597. * http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
  2598. * to request overhead, one bigger file just loads faster than two smaller ones
  2599. * half its size."
  2600. *
  2601. * $options['preprocess'] should be only set to TRUE when a file is required for
  2602. * all typical visitors and most pages of a site. It is critical that all
  2603. * preprocessed files are added unconditionally on every page, even if the
  2604. * files are not needed on a page. This is normally done by calling
  2605. * drupal_add_js() in a hook_page_build() implementation.
  2606. *
  2607. * Non-preprocessed files should only be added to the page when they are
  2608. * actually needed.
  2609. *
  2610. * @param $data
  2611. * (optional) If given, the value depends on the $options parameter, or
  2612. * $options['type'] if $options is passed as an associative array:
  2613. * - 'file': Path to the file relative to base_path().
  2614. * - 'inline': The JavaScript code that should be placed in the given scope.
  2615. * - 'external': The absolute path to an external JavaScript file that is not
  2616. * hosted on the local server. These files will not be aggregated if
  2617. * JavaScript aggregation is enabled.
  2618. * - 'setting': An associative array with configuration options. The array is
  2619. * merged directly into Drupal.settings. All modules should wrap their
  2620. * actual configuration settings in another variable to prevent conflicts in
  2621. * the Drupal.settings namespace. Items added with a string key will replace
  2622. * existing settings with that key; items with numeric array keys will be
  2623. * added to the existing settings array.
  2624. * @param $options
  2625. * (optional) A string defining the type of JavaScript that is being added in
  2626. * the $data parameter ('file'/'setting'/'inline'/'external'), or an
  2627. * associative array. JavaScript settings should always pass the string
  2628. * 'setting' only. Other types can have the following elements in the array:
  2629. * - type: The type of JavaScript that is to be added to the page. Allowed
  2630. * values are 'file', 'inline', 'external' or 'setting'. Defaults
  2631. * to 'file'.
  2632. * - scope: The location in which you want to place the script. Possible
  2633. * values are 'header' or 'footer'. If your theme implements different
  2634. * regions, you can also use these. Defaults to 'header'.
  2635. * - group: A number identifying the group in which to add the JavaScript.
  2636. * Available constants are:
  2637. * - JS_LIBRARY: Any libraries, settings, or jQuery plugins.
  2638. * - JS_DEFAULT: Any module-layer JavaScript.
  2639. * - JS_THEME: Any theme-layer JavaScript.
  2640. * The group number serves as a weight: JavaScript within a lower weight
  2641. * group is presented on the page before JavaScript within a higher weight
  2642. * group.
  2643. * - every_page: For optimal front-end performance when aggregation is
  2644. * enabled, this should be set to TRUE if the JavaScript is present on every
  2645. * page of the website for users for whom it is present at all. This
  2646. * defaults to FALSE. It is set to TRUE for JavaScript files that are added
  2647. * via module and theme .info.yml files. Modules that add JavaScript within
  2648. * hook_page_build() implementations, or from other code that ensures that
  2649. * the JavaScript is added to all website pages, should also set this flag
  2650. * to TRUE. All JavaScript files within the same group and that have the
  2651. * 'every_page' flag set to TRUE and do not have 'preprocess' set to FALSE
  2652. * are aggregated together into a single aggregate file, and that aggregate
  2653. * file can be reused across a user's entire site visit, leading to faster
  2654. * navigation between pages. However, JavaScript that is only needed on
  2655. * pages less frequently visited, can be added by code that only runs for
  2656. * those particular pages, and that code should not set the 'every_page'
  2657. * flag. This minimizes the size of the aggregate file that the user needs
  2658. * to download when first visiting the website. JavaScript without the
  2659. * 'every_page' flag is aggregated into a separate aggregate file. This
  2660. * other aggregate file is likely to change from page to page, and each new
  2661. * aggregate file needs to be downloaded when first encountered, so it
  2662. * should be kept relatively small by ensuring that most commonly needed
  2663. * JavaScript is added to every page.
  2664. * - weight: A number defining the order in which the JavaScript is added to
  2665. * the page relative to other JavaScript with the same 'scope', 'group',
  2666. * and 'every_page' value. In some cases, the order in which the JavaScript
  2667. * is presented on the page is very important. jQuery, for example, must be
  2668. * added to the page before any jQuery code is run, so jquery.js uses the
  2669. * JS_LIBRARY group and a weight of -20, jquery.once.js (a library drupal.js
  2670. * depends on) uses the JS_LIBRARY group and a weight of -19, drupal.js uses
  2671. * the JS_LIBRARY group and a weight of -1, other libraries use the
  2672. * JS_LIBRARY group and a weight of 0 or higher, and all other scripts use
  2673. * one of the other group constants. The exact ordering of JavaScript is as
  2674. * follows:
  2675. * - First by scope, with 'header' first, 'footer' last, and any other
  2676. * scopes provided by a custom theme coming in between, as determined by
  2677. * the theme.
  2678. * - Then by group.
  2679. * - Then by the 'every_page' flag, with TRUE coming before FALSE.
  2680. * - Then by weight.
  2681. * - Then by the order in which the JavaScript was added. For example, all
  2682. * else being the same, JavaScript added by a call to drupal_add_js() that
  2683. * happened later in the page request gets added to the page after one for
  2684. * which drupal_add_js() happened earlier in the page request.
  2685. * - cache: If set to FALSE, the JavaScript file is loaded anew on every page
  2686. * call; in other words, it is not cached. Used only when 'type' references
  2687. * a JavaScript file. Defaults to TRUE.
  2688. * - preprocess: If TRUE and JavaScript aggregation is enabled, the script
  2689. * file will be aggregated. Defaults to TRUE.
  2690. * - attributes: An associative array of attributes for the <script> tag. This
  2691. * may be used to add 'defer', 'async', or custom attributes. Note that
  2692. * setting any attributes will disable preprocessing as though the
  2693. * 'preprocess' option was set to FALSE.
  2694. * - browsers: An array containing information specifying which browsers
  2695. * should load the JavaScript item. See
  2696. * drupal_pre_render_conditional_comments() for details.
  2697. *
  2698. * @return
  2699. * The current array of JavaScript files, settings, and in-line code,
  2700. * including Drupal defaults, anything previously added with calls to
  2701. * drupal_add_js(), and this function call's additions.
  2702. *
  2703. * @see drupal_get_js()
  2704. */
  2705. function drupal_add_js($data = NULL, $options = NULL) {
  2706. $javascript = &drupal_static(__FUNCTION__, array());
  2707. // Construct the options, taking the defaults into consideration.
  2708. if (isset($options)) {
  2709. if (!is_array($options)) {
  2710. $options = array('type' => $options);
  2711. }
  2712. }
  2713. else {
  2714. $options = array();
  2715. }
  2716. $options += drupal_js_defaults($data);
  2717. // Preprocess can only be set if caching is enabled and no attributes are set.
  2718. $options['preprocess'] = $options['cache'] && empty($options['attributes']) ? $options['preprocess'] : FALSE;
  2719. // Tweak the weight so that files of the same weight are included in the
  2720. // order of the calls to drupal_add_js().
  2721. $options['weight'] += count($javascript) / 1000;
  2722. if (isset($data)) {
  2723. switch ($options['type']) {
  2724. case 'setting':
  2725. // If the setting array doesn't exist, add defaults values.
  2726. if (!isset($javascript['settings'])) {
  2727. $javascript['settings'] = array(
  2728. 'type' => 'setting',
  2729. 'scope' => 'header',
  2730. 'group' => JS_SETTING,
  2731. 'every_page' => TRUE,
  2732. 'weight' => 0,
  2733. 'browsers' => array(),
  2734. );
  2735. // url() generates the script and prefix using hook_url_outbound_alter().
  2736. // Instead of running the hook_url_outbound_alter() again here, extract
  2737. // them from url().
  2738. // @todo Make this less hacky: http://drupal.org/node/1547376.
  2739. $scriptPath = $GLOBALS['script_path'];
  2740. $pathPrefix = '';
  2741. url('', array('script' => &$scriptPath, 'prefix' => &$pathPrefix));
  2742. $javascript['settings']['data'][] = array(
  2743. 'basePath' => base_path(),
  2744. 'scriptPath' => $scriptPath,
  2745. 'pathPrefix' => $pathPrefix,
  2746. 'currentPath' => current_path(),
  2747. );
  2748. }
  2749. // All JavaScript settings are placed in the header of the page with
  2750. // the library weight so that inline scripts appear afterwards.
  2751. $javascript['settings']['data'][] = $data;
  2752. break;
  2753. case 'inline':
  2754. $javascript[] = $options;
  2755. break;
  2756. default: // 'file' and 'external'
  2757. // Local and external files must keep their name as the associative key
  2758. // so the same JavaScript file is not added twice.
  2759. $javascript[$options['data']] = $options;
  2760. }
  2761. }
  2762. return $javascript;
  2763. }
  2764. /**
  2765. * Constructs an array of the defaults that are used for JavaScript items.
  2766. *
  2767. * @param $data
  2768. * (optional) The default data parameter for the JavaScript item array.
  2769. *
  2770. * @see drupal_get_js()
  2771. * @see drupal_add_js()
  2772. */
  2773. function drupal_js_defaults($data = NULL) {
  2774. return array(
  2775. 'type' => 'file',
  2776. 'group' => JS_DEFAULT,
  2777. 'every_page' => FALSE,
  2778. 'weight' => 0,
  2779. 'scope' => 'header',
  2780. 'cache' => TRUE,
  2781. 'preprocess' => TRUE,
  2782. 'attributes' => array(),
  2783. 'version' => NULL,
  2784. 'data' => $data,
  2785. 'browsers' => array(),
  2786. );
  2787. }
  2788. /**
  2789. * Returns a themed presentation of all JavaScript code for the current page.
  2790. *
  2791. * References to JavaScript files are placed in a certain order: first, all
  2792. * 'core' files, then all 'module' and finally all 'theme' JavaScript files
  2793. * are added to the page. Then, all settings are output, followed by 'inline'
  2794. * JavaScript code. If running update.php, all preprocessing is disabled.
  2795. *
  2796. * Note that hook_js_alter(&$javascript) is called during this function call
  2797. * to allow alterations of the JavaScript during its presentation. Calls to
  2798. * drupal_add_js() from hook_js_alter() will not be added to the output
  2799. * presentation. The correct way to add JavaScript during hook_js_alter()
  2800. * is to add another element to the $javascript array, deriving from
  2801. * drupal_js_defaults(). See locale_js_alter() for an example of this.
  2802. *
  2803. * @param $scope
  2804. * (optional) The scope for which the JavaScript rules should be returned.
  2805. * Defaults to 'header'.
  2806. * @param $javascript
  2807. * (optional) An array with all JavaScript code. Defaults to the default
  2808. * JavaScript array for the given scope.
  2809. * @param $skip_alter
  2810. * (optional) If set to TRUE, this function skips calling drupal_alter() on
  2811. * $javascript, useful when the calling function passes a $javascript array
  2812. * that has already been altered.
  2813. *
  2814. * @return
  2815. * All JavaScript code segments and includes for the scope as HTML tags.
  2816. *
  2817. * @see drupal_add_js()
  2818. * @see locale_js_alter()
  2819. * @see drupal_js_defaults()
  2820. */
  2821. function drupal_get_js($scope = 'header', $javascript = NULL, $skip_alter = FALSE) {
  2822. if (!isset($javascript)) {
  2823. $javascript = drupal_add_js();
  2824. }
  2825. if (empty($javascript)) {
  2826. return '';
  2827. }
  2828. // Allow modules to alter the JavaScript.
  2829. if (!$skip_alter) {
  2830. drupal_alter('js', $javascript);
  2831. }
  2832. // Filter out elements of the given scope.
  2833. $items = array();
  2834. foreach ($javascript as $key => $item) {
  2835. if ($item['scope'] == $scope) {
  2836. $items[$key] = $item;
  2837. }
  2838. }
  2839. if (!empty($items)) {
  2840. // Sort the JavaScript files so that they appear in the correct order.
  2841. uasort($items, 'drupal_sort_css_js');
  2842. // Don't add settings if there is no other JavaScript on the page, unless
  2843. // this is an AJAX request.
  2844. // @todo Clean up container call.
  2845. $container = drupal_container();
  2846. if ($container->has('content_negotiation') && $container->isScopeActive('request')) {
  2847. $type = $container->get('content_negotiation')->getContentType($container->get('request'));
  2848. }
  2849. if (!empty($items['settings']) || (!empty($type) && $type == 'ajax')) {
  2850. global $theme_key;
  2851. // Provide the page with information about the theme that's used, so that
  2852. // a later AJAX request can be rendered using the same theme.
  2853. // @see ajax_base_page_theme()
  2854. $setting['ajaxPageState']['theme'] = $theme_key;
  2855. // Checks that the DB is available before filling theme_token.
  2856. if (!defined('MAINTENANCE_MODE')) {
  2857. $setting['ajaxPageState']['theme_token'] = drupal_get_token($theme_key);
  2858. }
  2859. // Provide the page with information about the individual JavaScript files
  2860. // used, information not otherwise available when aggregation is enabled.
  2861. $setting['ajaxPageState']['js'] = array_fill_keys(array_keys($javascript), 1);
  2862. unset($setting['ajaxPageState']['js']['settings']);
  2863. // Provide the page with information about the individual CSS files used,
  2864. // information not otherwise available when CSS aggregation is enabled.
  2865. // The setting is attached later in this function, but is set here, so
  2866. // that CSS files removed in drupal_process_attached() are still
  2867. // considered "used" and prevented from being added in a later AJAX
  2868. // request.
  2869. // Skip if no files were added to the page otherwise jQuery.extend() will
  2870. // overwrite the Drupal.settings.ajaxPageState.css object with an empty
  2871. // array.
  2872. $css = drupal_add_css();
  2873. if (!empty($css)) {
  2874. // Cast the array to an object to be on the safe side even if not empty.
  2875. $setting['ajaxPageState']['css'] = (object) array_fill_keys(array_keys($css), 1);
  2876. }
  2877. drupal_add_js($setting, 'setting');
  2878. // If we're outputting the header scope, then this might be the final time
  2879. // that drupal_get_js() is running, so add the settings to this output as well
  2880. // as to the drupal_add_js() cache. If $items['settings'] doesn't exist, it's
  2881. // because drupal_get_js() was intentionally passed a $javascript argument
  2882. // stripped of settings, potentially in order to override how settings get
  2883. // output, so in this case, do not add the setting to this output.
  2884. if ($scope == 'header' && isset($items['settings'])) {
  2885. $items['settings']['data'][] = $setting;
  2886. }
  2887. }
  2888. }
  2889. // Render the HTML needed to load the JavaScript.
  2890. $elements = array(
  2891. '#type' => 'scripts',
  2892. '#items' => $items,
  2893. );
  2894. return drupal_render($elements);
  2895. }
  2896. /**
  2897. * Merges an array of settings arrays into a single settings array.
  2898. *
  2899. * This function merges the items in the same way that
  2900. *
  2901. * @code
  2902. * jQuery.extend(true, {}, $settings_items[0], $settings_items[1], ...)
  2903. * @endcode
  2904. *
  2905. * would. This means integer indices are preserved just like string indices are,
  2906. * rather than re-indexed as is common in PHP array merging.
  2907. *
  2908. * Example:
  2909. * @code
  2910. * function module1_page_build(&$page) {
  2911. * $page['#attached']['js'][] = array(
  2912. * 'type' => 'setting',
  2913. * 'data' => array('foo' => array('a', 'b', 'c')),
  2914. * );
  2915. * }
  2916. * function module2_page_build(&$page) {
  2917. * $page['#attached']['js'][] = array(
  2918. * 'type' => 'setting',
  2919. * 'data' => array('foo' => array('d')),
  2920. * );
  2921. * }
  2922. * // When the page is rendered after the above code, and the browser runs the
  2923. * // resulting <SCRIPT> tags, the value of drupalSettings.foo is
  2924. * // ['d', 'b', 'c'], not ['a', 'b', 'c', 'd'].
  2925. * @endcode
  2926. *
  2927. * By following jQuery.extend() merge logic rather than common PHP array merge
  2928. * logic, the following are ensured:
  2929. * - drupal_add_js() is idempotent: calling it twice with the same parameters
  2930. * does not change the output sent to the browser.
  2931. * - If pieces of the page are rendered in separate PHP requests and the
  2932. * returned settings are merged by JavaScript, the resulting settings are the
  2933. * same as if rendered in one PHP request and merged by PHP.
  2934. *
  2935. * @param $settings_items
  2936. * An array of settings arrays, as returned by:
  2937. * @code
  2938. * $js = drupal_add_js();
  2939. * $settings_items = $js['settings']['data'];
  2940. * @endcode
  2941. *
  2942. * @return
  2943. * A merged $settings array, suitable for JSON encoding and returning to the
  2944. * browser.
  2945. *
  2946. * @see drupal_add_js()
  2947. * @see drupal_pre_render_scripts()
  2948. */
  2949. function drupal_merge_js_settings($settings_items) {
  2950. return NestedArray::mergeDeepArray($settings_items, TRUE);
  2951. }
  2952. /**
  2953. * #pre_render callback to add the elements needed for JavaScript tags to be rendered.
  2954. *
  2955. * This function evaluates the aggregation enabled/disabled condition on a group
  2956. * by group basis by testing whether an aggregate file has been made for the
  2957. * group rather than by testing the site-wide aggregation setting. This allows
  2958. * this function to work correctly even if modules have implemented custom
  2959. * logic for grouping and aggregating files.
  2960. *
  2961. * @param $element
  2962. * A render array containing:
  2963. * - #items: The JavaScript items as returned by drupal_add_js() and
  2964. * altered by drupal_get_js().
  2965. * - #group_callback: A function to call to group #items. Following
  2966. * this function, #aggregate_callback is called to aggregate items within
  2967. * the same group into a single file.
  2968. * - #aggregate_callback: A function to call to aggregate the items within
  2969. * the groups arranged by the #group_callback function.
  2970. *
  2971. * @return
  2972. * A render array that will render to a string of JavaScript tags.
  2973. *
  2974. * @see drupal_get_js()
  2975. */
  2976. function drupal_pre_render_scripts($elements) {
  2977. // Group and aggregate the items.
  2978. if (isset($elements['#group_callback'])) {
  2979. $elements['#groups'] = $elements['#group_callback']($elements['#items']);
  2980. }
  2981. if (isset($elements['#aggregate_callback'])) {
  2982. $elements['#aggregate_callback']($elements['#groups']);
  2983. }
  2984. // A dummy query-string is added to filenames, to gain control over
  2985. // browser-caching. The string changes on every update or full cache
  2986. // flush, forcing browsers to load a new copy of the files, as the
  2987. // URL changed. Files that should not be cached (see drupal_add_js())
  2988. // get REQUEST_TIME as query-string instead, to enforce reload on every
  2989. // page request.
  2990. $default_query_string = variable_get('css_js_query_string', '0');
  2991. // For inline JavaScript to validate as XHTML, all JavaScript containing
  2992. // XHTML needs to be wrapped in CDATA. To make that backwards compatible
  2993. // with HTML 4, we need to comment out the CDATA-tag.
  2994. $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
  2995. $embed_suffix = "\n//--><!]]>\n";
  2996. // Since JavaScript may look for arguments in the URL and act on them, some
  2997. // third-party code might require the use of a different query string.
  2998. $js_version_string = variable_get('drupal_js_version_query_string', 'v=');
  2999. // Defaults for each SCRIPT element.
  3000. $element_defaults = array(
  3001. '#type' => 'html_tag',
  3002. '#tag' => 'script',
  3003. '#value' => '',
  3004. );
  3005. // Loop through each group.
  3006. foreach ($elements['#groups'] as $group) {
  3007. // If a group of files has been aggregated into a single file,
  3008. // $group['data'] contains the URI of the aggregate file. Add a single
  3009. // script element for this file.
  3010. if ($group['type'] == 'file' && isset($group['data'])) {
  3011. $element = $element_defaults;
  3012. $element['#attributes']['src'] = file_create_url($group['data']);
  3013. $element['#browsers'] = $group['browsers'];
  3014. $elements[] = $element;
  3015. }
  3016. // For non-file types, and non-aggregated files, add a script element per
  3017. // item.
  3018. else {
  3019. foreach ($group['items'] as $item) {
  3020. // Element properties that do not depend on item type.
  3021. $element = $element_defaults;
  3022. $element['#browsers'] = $item['browsers'];
  3023. // Element properties that depend on item type.
  3024. switch ($item['type']) {
  3025. case 'setting':
  3026. $element['#value_prefix'] = $embed_prefix;
  3027. $element['#value'] = 'var drupalSettings = ' . drupal_json_encode(drupal_merge_js_settings($item['data'])) . ";";
  3028. $element['#value_suffix'] = $embed_suffix;
  3029. break;
  3030. case 'inline':
  3031. $element['#value_prefix'] = $embed_prefix;
  3032. $element['#value'] = $item['data'];
  3033. $element['#value_suffix'] = $embed_suffix;
  3034. break;
  3035. case 'file':
  3036. $query_string = empty($item['version']) ? $default_query_string : $js_version_string . $item['version'];
  3037. $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
  3038. $element['#attributes']['src'] = file_create_url($item['data']) . $query_string_separator . ($item['cache'] ? $query_string : REQUEST_TIME);
  3039. break;
  3040. case 'external':
  3041. $element['#attributes']['src'] = $item['data'];
  3042. break;
  3043. }
  3044. // Attributes may only be set if this script is output independently.
  3045. if (!empty($element['#attributes']['src']) && !empty($item['attributes'])) {
  3046. $element['#attributes'] += $item['attributes'];
  3047. }
  3048. $elements[] = $element;
  3049. }
  3050. }
  3051. }
  3052. return $elements;
  3053. }
  3054. /**
  3055. * Default callback to group JavaScript items.
  3056. *
  3057. * This function arranges the JavaScript items that are in the #items property
  3058. * of the scripts element into groups. When aggregation is enabled, files within
  3059. * a group are aggregated into a single file, significantly improving page
  3060. * loading performance by minimizing network traffic overhead.
  3061. *
  3062. * This function puts multiple items into the same group if they are groupable
  3063. * and if they are for the same browsers. Items of the 'file' type are groupable
  3064. * if their 'preprocess' flag is TRUE. Items of the 'inline', 'settings', or
  3065. * 'external' type are not groupable.
  3066. *
  3067. * This function also ensures that the process of grouping items does not change
  3068. * their relative order. This requirement may result in multiple groups for the
  3069. * same type and browsers, if needed to accommodate other items in
  3070. * between.
  3071. *
  3072. * @param $javascript
  3073. * An array of JavaScript items, as returned by drupal_add_js(), but after
  3074. * alteration performed by drupal_get_js().
  3075. *
  3076. * @return
  3077. * An array of JavaScript groups. Each group contains the same keys (e.g.,
  3078. * 'data', etc.) as a JavaScript item from the $javascript parameter, with the
  3079. * value of each key applying to the group as a whole. Each group also
  3080. * contains an 'items' key, which is the subset of items from $javascript that
  3081. * are in the group.
  3082. *
  3083. * @see drupal_pre_render_scripts()
  3084. */
  3085. function drupal_group_js($javascript) {
  3086. $groups = array();
  3087. // If a group can contain multiple items, we track the information that must
  3088. // be the same for each item in the group, so that when we iterate the next
  3089. // item, we can determine if it can be put into the current group, or if a
  3090. // new group needs to be made for it.
  3091. $current_group_keys = NULL;
  3092. $index = -1;
  3093. foreach ($javascript as $item) {
  3094. // The browsers for which the JavaScript item needs to be loaded is part of
  3095. // the information that determines when a new group is needed, but the order
  3096. // of keys in the array doesn't matter, and we don't want a new group if all
  3097. // that's different is that order.
  3098. ksort($item['browsers']);
  3099. switch ($item['type']) {
  3100. case 'file':
  3101. // Group file items if their 'preprocess' flag is TRUE.
  3102. // Help ensure maximum reuse of aggregate files by only grouping
  3103. // together items that share the same 'group' value and 'every_page'
  3104. // flag. See drupal_add_js() for details about that.
  3105. $group_keys = $item['preprocess'] ? array($item['type'], $item['group'], $item['every_page'], $item['browsers']) : FALSE;
  3106. break;
  3107. case 'external':
  3108. case 'setting':
  3109. case 'inline':
  3110. // Do not group external, settings, and inline items.
  3111. $group_keys = FALSE;
  3112. break;
  3113. }
  3114. // If the group keys don't match the most recent group we're working with,
  3115. // then a new group must be made.
  3116. if ($group_keys !== $current_group_keys) {
  3117. $index++;
  3118. // Initialize the new group with the same properties as the first item
  3119. // being placed into it. The item's 'data' and 'weight' properties are
  3120. // unique to the item and should not be carried over to the group.
  3121. $groups[$index] = $item;
  3122. unset($groups[$index]['data'], $groups[$index]['weight']);
  3123. $groups[$index]['items'] = array();
  3124. $current_group_keys = $group_keys ? $group_keys : NULL;
  3125. }
  3126. // Add the item to the current group.
  3127. $groups[$index]['items'][] = $item;
  3128. }
  3129. return $groups;
  3130. }
  3131. /**
  3132. * Default callback to aggregate JavaScript files.
  3133. *
  3134. * Having the browser load fewer JavaScript files results in much faster page
  3135. * loads than when it loads many small files. This function aggregates files
  3136. * within the same group into a single file unless the site-wide setting to do
  3137. * so is disabled (commonly the case during site development). To optimize
  3138. * download, it also compresses the aggregate files by removing comments,
  3139. * whitespace, and other unnecessary content.
  3140. *
  3141. * @param $js_groups
  3142. * An array of JavaScript groups as returned by drupal_group_js(). For each
  3143. * group that is aggregated, this function sets the value of the group's
  3144. * 'data' key to the URI of the aggregate file.
  3145. *
  3146. * @see drupal_group_js()
  3147. * @see drupal_pre_render_scripts()
  3148. */
  3149. function drupal_aggregate_js(&$js_groups) {
  3150. // Only aggregate during normal site operation.
  3151. if (defined('MAINTENANCE_MODE')) {
  3152. $preprocess_js = FALSE;
  3153. }
  3154. else {
  3155. $config = config('system.performance');
  3156. $preprocess_js = $config->get('js.preprocess');
  3157. }
  3158. if ($preprocess_js) {
  3159. foreach ($js_groups as $key => $group) {
  3160. if ($group['type'] == 'file' && $group['preprocess']) {
  3161. $js_groups[$key]['data'] = drupal_build_js_cache($group['items']);
  3162. }
  3163. }
  3164. }
  3165. }
  3166. /**
  3167. * Adds attachments to a render() structure.
  3168. *
  3169. * Libraries, JavaScript, CSS and other types of custom structures are attached
  3170. * to elements using the #attached property. The #attached property is an
  3171. * associative array, where the keys are the the attachment types and the values
  3172. * are the attached data. For example:
  3173. * @code
  3174. * $build['#attached'] = array(
  3175. * 'library' => array(array('taxonomy', 'taxonomy')),
  3176. * 'css' => array(drupal_get_path('module', 'taxonomy') . '/css/taxonomy.module.css'),
  3177. * );
  3178. * @endcode
  3179. *
  3180. * 'js', 'css', and 'library' are types that get special handling. For any
  3181. * other kind of attached data, the array key must be the full name of the
  3182. * callback function and each value an array of arguments. For example:
  3183. * @code
  3184. * $build['#attached']['drupal_add_http_header'] = array(
  3185. * array('Content-Type', 'application/rss+xml; charset=utf-8'),
  3186. * );
  3187. * @endcode
  3188. *
  3189. * External 'js' and 'css' files can also be loaded. For example:
  3190. * @code
  3191. * $build['#attached']['js'] = array(
  3192. * 'http://code.jquery.com/jquery-1.4.2.min.js' => array(
  3193. * 'type' => 'external',
  3194. * ),
  3195. * );
  3196. * @endcode
  3197. *
  3198. * @param $elements
  3199. * The structured array describing the data being rendered.
  3200. * @param $dependency_check
  3201. * When TRUE, will exit if a given library's dependencies are missing. When
  3202. * set to FALSE, will continue to add the libraries, even though one or more
  3203. * dependencies are missing. Defaults to FALSE.
  3204. *
  3205. * @return
  3206. * FALSE if there were any missing library dependencies; TRUE if all library
  3207. * dependencies were met.
  3208. *
  3209. * @see drupal_add_library()
  3210. * @see drupal_add_js()
  3211. * @see drupal_add_css()
  3212. * @see drupal_render()
  3213. */
  3214. function drupal_process_attached($elements, $dependency_check = FALSE) {
  3215. // Add defaults to the special attached structures that should be processed differently.
  3216. $elements['#attached'] += array(
  3217. 'library' => array(),
  3218. 'js' => array(),
  3219. 'css' => array(),
  3220. );
  3221. // Add the libraries first.
  3222. $success = TRUE;
  3223. foreach ($elements['#attached']['library'] as $library) {
  3224. if (drupal_add_library($library[0], $library[1]) === FALSE) {
  3225. $success = FALSE;
  3226. // Exit if the dependency is missing.
  3227. if ($dependency_check) {
  3228. return $success;
  3229. }
  3230. }
  3231. }
  3232. unset($elements['#attached']['library']);
  3233. // Add both the JavaScript and the CSS.
  3234. // The parameters for drupal_add_js() and drupal_add_css() require special
  3235. // handling.
  3236. foreach (array('js', 'css') as $type) {
  3237. foreach ($elements['#attached'][$type] as $data => $options) {
  3238. // If the value is not an array, it's a filename and passed as first
  3239. // (and only) argument.
  3240. if (!is_array($options)) {
  3241. $data = $options;
  3242. $options = NULL;
  3243. }
  3244. // In some cases, the first parameter ($data) is an array. Arrays can't be
  3245. // passed as keys in PHP, so we have to get $data from the value array.
  3246. if (is_numeric($data)) {
  3247. $data = $options['data'];
  3248. unset($options['data']);
  3249. }
  3250. call_user_func('drupal_add_' . $type, $data, $options);
  3251. }
  3252. unset($elements['#attached'][$type]);
  3253. }
  3254. // Add additional types of attachments specified in the render() structure.
  3255. // Libraries, JavaScript and CSS have been added already, as they require
  3256. // special handling.
  3257. foreach ($elements['#attached'] as $callback => $options) {
  3258. foreach ($elements['#attached'][$callback] as $args) {
  3259. call_user_func_array($callback, $args);
  3260. }
  3261. }
  3262. return $success;
  3263. }
  3264. /**
  3265. * Adds JavaScript to change the state of an element based on another element.
  3266. *
  3267. * A "state" means a certain property on a DOM element, such as "visible" or
  3268. * "checked". A state can be applied to an element, depending on the state of
  3269. * another element on the page. In general, states depend on HTML attributes and
  3270. * DOM element properties, which change due to user interaction.
  3271. *
  3272. * Since states are driven by JavaScript only, it is important to understand
  3273. * that all states are applied on presentation only, none of the states force
  3274. * any server-side logic, and that they will not be applied for site visitors
  3275. * without JavaScript support. All modules implementing states have to make
  3276. * sure that the intended logic also works without JavaScript being enabled.
  3277. *
  3278. * #states is an associative array in the form of:
  3279. * @code
  3280. * array(
  3281. * STATE1 => CONDITIONS_ARRAY1,
  3282. * STATE2 => CONDITIONS_ARRAY2,
  3283. * ...
  3284. * )
  3285. * @endcode
  3286. * Each key is the name of a state to apply to the element, such as 'visible'.
  3287. * Each value is a list of conditions that denote when the state should be
  3288. * applied.
  3289. *
  3290. * Multiple different states may be specified to act on complex conditions:
  3291. * @code
  3292. * array(
  3293. * 'visible' => CONDITIONS,
  3294. * 'checked' => OTHER_CONDITIONS,
  3295. * )
  3296. * @endcode
  3297. *
  3298. * Every condition is a key/value pair, whose key is a jQuery selector that
  3299. * denotes another element on the page, and whose value is an array of
  3300. * conditions, which must bet met on that element:
  3301. * @code
  3302. * array(
  3303. * 'visible' => array(
  3304. * JQUERY_SELECTOR => REMOTE_CONDITIONS,
  3305. * JQUERY_SELECTOR => REMOTE_CONDITIONS,
  3306. * ...
  3307. * ),
  3308. * )
  3309. * @endcode
  3310. * All conditions must be met for the state to be applied.
  3311. *
  3312. * Each remote condition is a key/value pair specifying conditions on the other
  3313. * element that need to be met to apply the state to the element:
  3314. * @code
  3315. * array(
  3316. * 'visible' => array(
  3317. * ':input[name="remote_checkbox"]' => array('checked' => TRUE),
  3318. * ),
  3319. * )
  3320. * @endcode
  3321. *
  3322. * For example, to show a textfield only when a checkbox is checked:
  3323. * @code
  3324. * $form['toggle_me'] = array(
  3325. * '#type' => 'checkbox',
  3326. * '#title' => t('Tick this box to type'),
  3327. * );
  3328. * $form['settings'] = array(
  3329. * '#type' => 'textfield',
  3330. * '#states' => array(
  3331. * // Only show this field when the 'toggle_me' checkbox is enabled.
  3332. * 'visible' => array(
  3333. * ':input[name="toggle_me"]' => array('checked' => TRUE),
  3334. * ),
  3335. * ),
  3336. * );
  3337. * @endcode
  3338. *
  3339. * The following states may be applied to an element:
  3340. * - enabled
  3341. * - disabled
  3342. * - required
  3343. * - optional
  3344. * - visible
  3345. * - invisible
  3346. * - checked
  3347. * - unchecked
  3348. * - expanded
  3349. * - collapsed
  3350. *
  3351. * The following states may be used in remote conditions:
  3352. * - empty
  3353. * - filled
  3354. * - checked
  3355. * - unchecked
  3356. * - expanded
  3357. * - collapsed
  3358. * - value
  3359. *
  3360. * The following states exist for both elements and remote conditions, but are
  3361. * not fully implemented and may not change anything on the element:
  3362. * - relevant
  3363. * - irrelevant
  3364. * - valid
  3365. * - invalid
  3366. * - touched
  3367. * - untouched
  3368. * - readwrite
  3369. * - readonly
  3370. *
  3371. * When referencing select lists and radio buttons in remote conditions, a
  3372. * 'value' condition must be used:
  3373. * @code
  3374. * '#states' => array(
  3375. * // Show the settings if 'bar' has been selected for 'foo'.
  3376. * 'visible' => array(
  3377. * ':input[name="foo"]' => array('value' => 'bar'),
  3378. * ),
  3379. * ),
  3380. * @endcode
  3381. *
  3382. * @param $elements
  3383. * A renderable array element having a #states property as described above.
  3384. *
  3385. * @see form_example_states_form()
  3386. */
  3387. function drupal_process_states(&$elements) {
  3388. $elements['#attached']['library'][] = array('system', 'drupal.states');
  3389. $elements['#attached']['js'][] = array(
  3390. 'type' => 'setting',
  3391. 'data' => array('states' => array('#' . $elements['#id'] => $elements['#states'])),
  3392. );
  3393. }
  3394. /**
  3395. * Adds multiple JavaScript or CSS files at the same time.
  3396. *
  3397. * A library defines a set of JavaScript and/or CSS files, optionally using
  3398. * settings, and optionally requiring another library. For example, a library
  3399. * can be a jQuery plugin, a JavaScript framework, or a CSS framework. This
  3400. * function allows modules to load a library defined/shipped by itself or a
  3401. * depending module, without having to add all files of the library separately.
  3402. * Each library is only loaded once.
  3403. *
  3404. * @param $module
  3405. * The name of the module that registered the library.
  3406. * @param $name
  3407. * The name of the library to add.
  3408. * @param $every_page
  3409. * Set to TRUE if this library is added to every page on the site.
  3410. *
  3411. * @return
  3412. * TRUE if the library was successfully added; FALSE if the library or one of
  3413. * its dependencies could not be added.
  3414. *
  3415. * @see drupal_get_library()
  3416. * @see hook_library_info()
  3417. * @see hook_library_info_alter()
  3418. */
  3419. function drupal_add_library($module, $name, $every_page = NULL) {
  3420. $added = &drupal_static(__FUNCTION__, array());
  3421. // Only process the library if it exists and it was not added already.
  3422. if (!isset($added[$module][$name])) {
  3423. if ($library = drupal_get_library($module, $name)) {
  3424. // Add all components within the library.
  3425. $elements['#attached'] = array(
  3426. 'library' => $library['dependencies'],
  3427. 'js' => $library['js'],
  3428. 'css' => $library['css'],
  3429. );
  3430. foreach (array('js', 'css') as $type) {
  3431. foreach ($elements['#attached'][$type] as $data => $options) {
  3432. // Apply the JS_LIBRARY group if it isn't explicitly given.
  3433. if ($type == 'js' && !isset($options['group'])) {
  3434. $elements['#attached']['js'][$data]['group'] = JS_LIBRARY;
  3435. }
  3436. // Set the every_page flag if one was passed.
  3437. if (isset($every_page)) {
  3438. $elements['#attached'][$type][$data]['every_page'] = $every_page;
  3439. }
  3440. }
  3441. }
  3442. $added[$module][$name] = drupal_process_attached($elements, TRUE);
  3443. }
  3444. else {
  3445. // Requested library does not exist.
  3446. $added[$module][$name] = FALSE;
  3447. }
  3448. }
  3449. return $added[$module][$name];
  3450. }
  3451. /**
  3452. * Retrieves information for a JavaScript/CSS library.
  3453. *
  3454. * Library information is statically cached. Libraries are keyed by module for
  3455. * several reasons:
  3456. * - Libraries are not unique. Multiple modules might ship with the same library
  3457. * in a different version or variant. This registry cannot (and does not
  3458. * attempt to) prevent library conflicts.
  3459. * - Modules implementing and thereby depending on a library that is registered
  3460. * by another module can only rely on that module's library.
  3461. * - Two (or more) modules can still register the same library and use it
  3462. * without conflicts in case the libraries are loaded on certain pages only.
  3463. *
  3464. * @param $module
  3465. * The name of a module that registered a library.
  3466. * @param $name
  3467. * (optional) The name of a registered library to retrieve. By default, all
  3468. * libraries registered by $module are returned.
  3469. *
  3470. * @return
  3471. * The definition of the requested library, if $name was passed and it exists,
  3472. * or FALSE if it does not exist. If no $name was passed, an associative array
  3473. * of libraries registered by $module is returned (which may be empty).
  3474. *
  3475. * @see drupal_add_library()
  3476. * @see hook_library_info()
  3477. * @see hook_library_info_alter()
  3478. *
  3479. * @todo The purpose of drupal_get_*() is completely different to other page
  3480. * requisite API functions; find and use a different name.
  3481. */
  3482. function drupal_get_library($module, $name = NULL) {
  3483. $libraries = &drupal_static(__FUNCTION__, array());
  3484. if (!isset($libraries[$module])) {
  3485. // Retrieve all libraries associated with the module.
  3486. $module_libraries = module_invoke($module, 'library_info');
  3487. if (empty($module_libraries)) {
  3488. $module_libraries = array();
  3489. }
  3490. // Allow modules to alter the module's registered libraries.
  3491. drupal_alter('library_info', $module_libraries, $module);
  3492. foreach ($module_libraries as $key => $data) {
  3493. if (is_array($data)) {
  3494. // Add default elements to allow for easier processing.
  3495. $module_libraries[$key] += array('dependencies' => array(), 'js' => array(), 'css' => array());
  3496. foreach ($module_libraries[$key]['js'] as $file => $options) {
  3497. if (is_scalar($options)) {
  3498. // The JavaScript or CSS file has been specified in shorthand
  3499. // format, without an array of options. In this case $options is the
  3500. // filename.
  3501. $file = $options;
  3502. $options = array();
  3503. }
  3504. $module_libraries[$key]['js'][$file]['version'] = $module_libraries[$key]['version'];
  3505. }
  3506. }
  3507. }
  3508. $libraries[$module] = $module_libraries;
  3509. }
  3510. if (isset($name)) {
  3511. if (!isset($libraries[$module][$name])) {
  3512. $libraries[$module][$name] = FALSE;
  3513. }
  3514. return $libraries[$module][$name];
  3515. }
  3516. return $libraries[$module];
  3517. }
  3518. /**
  3519. * Assists in adding the tableDrag JavaScript behavior to a themed table.
  3520. *
  3521. * Draggable tables should be used wherever an outline or list of sortable items
  3522. * needs to be arranged by an end-user. Draggable tables are very flexible and
  3523. * can manipulate the value of form elements placed within individual columns.
  3524. *
  3525. * To set up a table to use drag and drop in place of weight select-lists or in
  3526. * place of a form that contains parent relationships, the form must be themed
  3527. * into a table. The table must have an ID attribute set. If using
  3528. * theme_table(), the ID may be set as follows:
  3529. * @code
  3530. * $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'my-module-table')));
  3531. * return $output;
  3532. * @endcode
  3533. *
  3534. * In the theme function for the form, a special class must be added to each
  3535. * form element within the same column, "grouping" them together.
  3536. *
  3537. * In a situation where a single weight column is being sorted in the table, the
  3538. * classes could be added like this (in the theme function):
  3539. * @code
  3540. * $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
  3541. * @endcode
  3542. *
  3543. * Each row of the table must also have a class of "draggable" in order to
  3544. * enable the drag handles:
  3545. * @code
  3546. * $row = array(...);
  3547. * $rows[] = array(
  3548. * 'data' => $row,
  3549. * 'class' => array('draggable'),
  3550. * );
  3551. * @endcode
  3552. *
  3553. * When tree relationships are present, the two additional classes
  3554. * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
  3555. * - Rows with the 'tabledrag-leaf' class cannot have child rows.
  3556. * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
  3557. *
  3558. * Calling drupal_add_tabledrag() would then be written as such:
  3559. * @code
  3560. * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
  3561. * @endcode
  3562. *
  3563. * In a more complex case where there are several groups in one column (such as
  3564. * the block regions on the admin/structure/block page), a separate subgroup
  3565. * class must also be added to differentiate the groups.
  3566. * @code
  3567. * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
  3568. * @endcode
  3569. *
  3570. * $group is still 'my-element-weight', and the additional $subgroup variable
  3571. * will be passed in as 'my-elements-weight-' . $region. This also means that
  3572. * you'll need to call drupal_add_tabledrag() once for every region added.
  3573. *
  3574. * @code
  3575. * foreach ($regions as $region) {
  3576. * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight', 'my-elements-weight-' . $region);
  3577. * }
  3578. * @endcode
  3579. *
  3580. * In a situation where tree relationships are present, adding multiple
  3581. * subgroups is not necessary, because the table will contain indentations that
  3582. * provide enough information about the sibling and parent relationships. See
  3583. * theme_menu_overview_form() for an example creating a table containing parent
  3584. * relationships.
  3585. *
  3586. * Note that this function should be called from the theme layer, such as in a
  3587. * .tpl.php file, theme_ function, or in a template_preprocess function, not in
  3588. * a form declaration. Though the same JavaScript could be added to the page
  3589. * using drupal_add_js() directly, this function helps keep template files
  3590. * clean and readable. It also prevents tabledrag.js from being added twice
  3591. * accidentally.
  3592. *
  3593. * @param $table_id
  3594. * String containing the target table's id attribute. If the table does not
  3595. * have an id, one will need to be set, such as <table id="my-module-table">.
  3596. * @param $action
  3597. * String describing the action to be done on the form item. Either 'match'
  3598. * 'depth', or 'order'. Match is typically used for parent relationships.
  3599. * Order is typically used to set weights on other form elements with the same
  3600. * group. Depth updates the target element with the current indentation.
  3601. * @param $relationship
  3602. * String describing where the $action variable should be performed. Either
  3603. * 'parent', 'sibling', 'group', or 'self'. Parent will only look for fields
  3604. * up the tree. Sibling will look for fields in the same group in rows above
  3605. * and below it. Self affects the dragged row itself. Group affects the
  3606. * dragged row, plus any children below it (the entire dragged group).
  3607. * @param $group
  3608. * A class name applied on all related form elements for this action.
  3609. * @param $subgroup
  3610. * (optional) If the group has several subgroups within it, this string should
  3611. * contain the class name identifying fields in the same subgroup.
  3612. * @param $source
  3613. * (optional) If the $action is 'match', this string should contain the class
  3614. * name identifying what field will be used as the source value when matching
  3615. * the value in $subgroup.
  3616. * @param $hidden
  3617. * (optional) The column containing the field elements may be entirely hidden
  3618. * from view dynamically when the JavaScript is loaded. Set to FALSE if the
  3619. * column should not be hidden.
  3620. * @param $limit
  3621. * (optional) Limit the maximum amount of parenting in this table.
  3622. * @see block-admin-display-form.tpl.php
  3623. * @see theme_menu_overview_form()
  3624. */
  3625. function drupal_add_tabledrag($table_id, $action, $relationship, $group, $subgroup = NULL, $source = NULL, $hidden = TRUE, $limit = 0) {
  3626. $js_added = &drupal_static(__FUNCTION__, FALSE);
  3627. $tabledrag_id = &drupal_static(__FUNCTION__ . '_setting', FALSE);
  3628. $tabledrag_id = (!isset($tabledrag_id)) ? 0 : $tabledrag_id + 1;
  3629. if (!$js_added) {
  3630. // Add the table drag JavaScript to the page before the module JavaScript
  3631. // to ensure that table drag behaviors are registered before any module
  3632. // uses it.
  3633. drupal_add_library('system', 'drupal.tabledrag');
  3634. $js_added = TRUE;
  3635. }
  3636. // If a subgroup or source isn't set, assume it is the same as the group.
  3637. $target = isset($subgroup) ? $subgroup : $group;
  3638. $source = isset($source) ? $source : $target;
  3639. $settings['tableDrag'][$table_id][$group][$tabledrag_id] = array(
  3640. 'target' => $target,
  3641. 'source' => $source,
  3642. 'relationship' => $relationship,
  3643. 'action' => $action,
  3644. 'hidden' => $hidden,
  3645. 'limit' => $limit,
  3646. );
  3647. drupal_add_js($settings, 'setting');
  3648. }
  3649. /**
  3650. * Aggregates JavaScript files into a cache file in the files directory.
  3651. *
  3652. * The file name for the JavaScript cache file is generated from the hash of
  3653. * the aggregated contents of the files in $files. This forces proxies and
  3654. * browsers to download new JavaScript when the JavaScript changes.
  3655. *
  3656. * The cache file name is retrieved on a page load via a lookup variable that
  3657. * contains an associative array. The array key is the hash of the names in
  3658. * $files while the value is the cache file name. The cache file is generated
  3659. * in two cases. First, if there is no file name value for the key, which will
  3660. * happen if a new file name has been added to $files or after the lookup
  3661. * variable is emptied to force a rebuild of the cache. Second, the cache file
  3662. * is generated if it is missing on disk. Old cache files are not deleted
  3663. * immediately when the lookup variable is emptied, but are deleted after a set
  3664. * period by drupal_delete_file_if_stale(). This ensures that files referenced
  3665. * by a cached page will still be available.
  3666. *
  3667. * @param $files
  3668. * An array of JavaScript files to aggregate and compress into one file.
  3669. *
  3670. * @return
  3671. * The URI of the cache file, or FALSE if the file could not be saved.
  3672. */
  3673. function drupal_build_js_cache($files) {
  3674. $contents = '';
  3675. $uri = '';
  3676. $map = Drupal::state()->get('system.js_cache_files') ?: array();
  3677. // Create a new array so that only the file names are used to create the hash.
  3678. // This prevents new aggregates from being created unnecessarily.
  3679. $js_data = array();
  3680. foreach ($files as $file) {
  3681. $js_data[] = $file['data'];
  3682. }
  3683. $key = hash('sha256', serialize($js_data));
  3684. if (isset($map[$key])) {
  3685. $uri = $map[$key];
  3686. }
  3687. if (empty($uri) || !file_exists($uri)) {
  3688. // Build aggregate JS file.
  3689. foreach ($files as $info) {
  3690. if ($info['preprocess']) {
  3691. // Append a ';' and a newline after each JS file to prevent them from running together.
  3692. $contents .= file_get_contents($info['data']) . ";\n";
  3693. }
  3694. }
  3695. // Prefix filename to prevent blocking by firewalls which reject files
  3696. // starting with "ad*".
  3697. $filename = 'js_' . Crypt::hashBase64($contents) . '.js';
  3698. // Create the js/ within the files folder.
  3699. $jspath = 'public://js';
  3700. $uri = $jspath . '/' . $filename;
  3701. // Create the JS file.
  3702. file_prepare_directory($jspath, FILE_CREATE_DIRECTORY);
  3703. if (!file_exists($uri) && !file_unmanaged_save_data($contents, $uri, FILE_EXISTS_REPLACE)) {
  3704. return FALSE;
  3705. }
  3706. // If JS gzip compression is enabled and the zlib extension is available
  3707. // then create a gzipped version of this file. This file is served
  3708. // conditionally to browsers that accept gzip using .htaccess rules.
  3709. // It's possible that the rewrite rules in .htaccess aren't working on this
  3710. // server, but there's no harm (other than the time spent generating the
  3711. // file) in generating the file anyway. Sites on servers where rewrite rules
  3712. // aren't working can set js.gzip to FALSE in order to skip
  3713. // generating a file that won't be used.
  3714. if (config('system.performance')->get('js.gzip') && extension_loaded('zlib')) {
  3715. if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($contents, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
  3716. return FALSE;
  3717. }
  3718. }
  3719. $map[$key] = $uri;
  3720. Drupal::state()->set('system.js_cache_files', $map);
  3721. }
  3722. return $uri;
  3723. }
  3724. /**
  3725. * Deletes old cached JavaScript files and variables.
  3726. */
  3727. function drupal_clear_js_cache() {
  3728. Drupal::state()->delete('system.javascript_parsed');
  3729. Drupal::state()->delete('system.js_cache_files');
  3730. file_scan_directory('public://js', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
  3731. }
  3732. /**
  3733. * Converts a PHP variable into its JavaScript equivalent.
  3734. *
  3735. * We use HTML-safe strings, with several characters escaped.
  3736. *
  3737. * @see drupal_json_decode()
  3738. * @ingroup php_wrappers
  3739. */
  3740. function drupal_json_encode($var) {
  3741. // Encode <, >, ', &, and " using the json_encode() options parameter.
  3742. return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
  3743. }
  3744. /**
  3745. * Converts an HTML-safe JSON string into its PHP equivalent.
  3746. *
  3747. * @see drupal_json_encode()
  3748. * @ingroup php_wrappers
  3749. */
  3750. function drupal_json_decode($var) {
  3751. return json_decode($var, TRUE);
  3752. }
  3753. /**
  3754. * Ensures the private key variable used to generate tokens is set.
  3755. *
  3756. * @return
  3757. * The private key.
  3758. */
  3759. function drupal_get_private_key() {
  3760. if (!($key = Drupal::state()->get('system.private_key'))) {
  3761. $key = Crypt::randomStringHashed(55);
  3762. Drupal::state()->set('system.private_key', $key);
  3763. }
  3764. return $key;
  3765. }
  3766. /**
  3767. * Generates a token based on $value, the user session, and the private key.
  3768. *
  3769. * @param $value
  3770. * An additional value to base the token on.
  3771. *
  3772. * @return string
  3773. * A 43-character URL-safe token for validation, based on the user session ID,
  3774. * the hash salt provided from drupal_get_hash_salt(), and the
  3775. * 'drupal_private_key' configuration variable.
  3776. *
  3777. * @see drupal_get_hash_salt()
  3778. */
  3779. function drupal_get_token($value = '') {
  3780. return Crypt::hmacBase64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());
  3781. }
  3782. /**
  3783. * Validates a token based on $value, the user session, and the private key.
  3784. *
  3785. * @param $token
  3786. * The token to be validated.
  3787. * @param $value
  3788. * An additional value to base the token on.
  3789. * @param $skip_anonymous
  3790. * Set to true to skip token validation for anonymous users.
  3791. *
  3792. * @return
  3793. * True for a valid token, false for an invalid token. When $skip_anonymous
  3794. * is true, the return value will always be true for anonymous users.
  3795. */
  3796. function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
  3797. global $user;
  3798. return (($skip_anonymous && $user->uid == 0) || ($token == drupal_get_token($value)));
  3799. }
  3800. /**
  3801. * Loads code for subsystems and modules, and registers stream wrappers.
  3802. */
  3803. function _drupal_bootstrap_code() {
  3804. require_once __DIR__ . '/../../' . settings()->get('path_inc', 'core/includes/path.inc');
  3805. require_once __DIR__ . '/theme.inc';
  3806. require_once __DIR__ . '/pager.inc';
  3807. require_once __DIR__ . '/../../' . settings()->get('menu_inc', 'core/includes/menu.inc');
  3808. require_once __DIR__ . '/tablesort.inc';
  3809. require_once __DIR__ . '/file.inc';
  3810. require_once __DIR__ . '/unicode.inc';
  3811. require_once __DIR__ . '/image.inc';
  3812. require_once __DIR__ . '/form.inc';
  3813. require_once __DIR__ . '/mail.inc';
  3814. require_once __DIR__ . '/ajax.inc';
  3815. require_once __DIR__ . '/errors.inc';
  3816. require_once __DIR__ . '/schema.inc';
  3817. require_once __DIR__ . '/entity.inc';
  3818. // Load all enabled modules
  3819. Drupal::moduleHandler()->loadAll();
  3820. // Make sure all stream wrappers are registered.
  3821. file_get_stream_wrappers();
  3822. // Now that stream wrappers are registered, log fatal errors from a simpletest
  3823. // child site to a test specific file directory.
  3824. $test_info = &$GLOBALS['drupal_test_info'];
  3825. if (!empty($test_info['in_child_site'])) {
  3826. ini_set('log_errors', 1);
  3827. ini_set('error_log', 'public://error.log');
  3828. }
  3829. // Set the allowed protocols once we have the config available.
  3830. $allowed_protocols = \Drupal::config('system.filter')->get('protocols');
  3831. if (!isset($allowed_protocols)) {
  3832. // filter_xss_admin() is called by the installer and update.php, in which
  3833. // case the configuration may not exist (yet). Provide a minimal default set
  3834. // of allowed protocols for these cases.
  3835. $allowed_protocols = array('http', 'https');
  3836. }
  3837. UrlValidator::setAllowedProtocols($allowed_protocols);
  3838. }
  3839. /**
  3840. * Temporary BC function for scripts not using DrupalKernel.
  3841. *
  3842. * DrupalKernel skips this and replicates it via event listeners.
  3843. *
  3844. * @see Drupal\Core\EventSubscriber\PathSubscriber;
  3845. * @see Drupal\Core\EventSubscriber\LegacyRequestSubscriber;
  3846. */
  3847. function _drupal_bootstrap_full($skip = FALSE) {
  3848. static $called = FALSE;
  3849. if ($called || $skip) {
  3850. $called = TRUE;
  3851. return;
  3852. }
  3853. // Initialize language (which can strip path prefix) prior to initializing
  3854. // current_path().
  3855. drupal_language_initialize();
  3856. // Let all modules take action before the menu system handles the request.
  3857. // We do not want this while running update.php.
  3858. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
  3859. menu_set_custom_theme();
  3860. drupal_theme_initialize();
  3861. }
  3862. }
  3863. /**
  3864. * Stores the current page in the cache.
  3865. *
  3866. * If page_compression is enabled, a gzipped version of the page is stored in
  3867. * the cache to avoid compressing the output on each request. The cache entry
  3868. * is unzipped in the relatively rare event that the page is requested by a
  3869. * client without gzip support.
  3870. *
  3871. * Page compression requires the PHP zlib extension
  3872. * (http://php.net/manual/ref.zlib.php).
  3873. *
  3874. * @param $body
  3875. * The response body.
  3876. * @return
  3877. * The cached object or NULL if the page cache was not set.
  3878. *
  3879. * @see drupal_page_header()
  3880. */
  3881. function drupal_page_set_cache(Response $response, Request $request) {
  3882. global $base_root;
  3883. if (drupal_page_is_cacheable()) {
  3884. $cache = (object) array(
  3885. 'cid' => $base_root . $request->getRequestUri(),
  3886. 'data' => array(
  3887. 'path' => $request->attributes->get('system_path'),
  3888. 'body' => $response->getContent(),
  3889. 'title' => drupal_get_title(),
  3890. 'headers' => array(),
  3891. ),
  3892. 'tags' => array('content' => TRUE),
  3893. 'expire' => CacheBackendInterface::CACHE_PERMANENT,
  3894. 'created' => REQUEST_TIME,
  3895. );
  3896. $cache->data['headers'] = $response->headers->all();
  3897. // Hack: exclude the x-drupal-cache header; it may make it in here because
  3898. // of awkwardness in how we defer sending it over in _drupal_page_get_cache.
  3899. if (isset($cache->data['headers']['x-drupal-cache'])) {
  3900. unset($cache->data['headers']['x-drupal-cache']);
  3901. }
  3902. // Use the actual timestamp from an Expires header, if available.
  3903. if ($date = $response->getExpires()) {
  3904. $date = new DrupalDateTime($date);
  3905. $cache->expire = $date->getTimestamp();
  3906. }
  3907. if ($cache->data['body']) {
  3908. if (config('system.performance')->get('response.gzip') && extension_loaded('zlib')) {
  3909. $cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
  3910. }
  3911. cache('page')->set($cache->cid, $cache->data, $cache->expire, $cache->tags);
  3912. }
  3913. return $cache;
  3914. }
  3915. }
  3916. /**
  3917. * Executes a cron run when called.
  3918. *
  3919. * Do not call this function from a test. Use $this->cronRun() instead.
  3920. *
  3921. * @return
  3922. * TRUE if cron ran successfully.
  3923. */
  3924. function drupal_cron_run() {
  3925. // Allow execution to continue even if the request gets canceled.
  3926. @ignore_user_abort(TRUE);
  3927. // Prevent session information from being saved while cron is running.
  3928. $original_session_saving = drupal_save_session();
  3929. drupal_save_session(FALSE);
  3930. // Force the current user to anonymous to ensure consistent permissions on
  3931. // cron runs.
  3932. $original_user = $GLOBALS['user'];
  3933. $GLOBALS['user'] = drupal_anonymous_user();
  3934. // Try to allocate enough time to run all the hook_cron implementations.
  3935. drupal_set_time_limit(240);
  3936. $return = FALSE;
  3937. // Grab the defined cron queues.
  3938. $queues = module_invoke_all('queue_info');
  3939. drupal_alter('queue_info', $queues);
  3940. // Try to acquire cron lock.
  3941. if (!lock()->acquire('cron', 240.0)) {
  3942. // Cron is still running normally.
  3943. watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
  3944. }
  3945. else {
  3946. // Make sure every queue exists. There is no harm in trying to recreate an
  3947. // existing queue.
  3948. foreach ($queues as $queue_name => $info) {
  3949. if (isset($info['cron'])) {
  3950. Drupal::queue($queue_name)->createQueue();
  3951. }
  3952. }
  3953. // Iterate through the modules calling their cron handlers (if any):
  3954. foreach (module_implements('cron') as $module) {
  3955. // Do not let an exception thrown by one module disturb another.
  3956. try {
  3957. module_invoke($module, 'cron');
  3958. }
  3959. catch (Exception $e) {
  3960. watchdog_exception('cron', $e);
  3961. }
  3962. }
  3963. // Record cron time.
  3964. Drupal::state()->set('system.cron_last', REQUEST_TIME);
  3965. watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
  3966. // Release cron lock.
  3967. lock()->release('cron');
  3968. // Return TRUE so other functions can check if it did run successfully
  3969. $return = TRUE;
  3970. }
  3971. foreach ($queues as $queue_name => $info) {
  3972. if (isset($info['cron'])) {
  3973. $callback = $info['worker callback'];
  3974. $end = time() + (isset($info['cron']['time']) ? $info['cron']['time'] : 15);
  3975. $queue = Drupal::queue($queue_name);
  3976. while (time() < $end && ($item = $queue->claimItem())) {
  3977. call_user_func_array($callback, array($item->data));
  3978. $queue->deleteItem($item);
  3979. }
  3980. }
  3981. }
  3982. // Restore the user.
  3983. $GLOBALS['user'] = $original_user;
  3984. drupal_save_session($original_session_saving);
  3985. return $return;
  3986. }
  3987. /**
  3988. * This function is kept only for backward compatibility.
  3989. *
  3990. * @see \Drupal\Core\SystemListing::scan().
  3991. */
  3992. function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
  3993. // As SystemListing is required to build a dependency injection container
  3994. // from scratch and SystemListingInfo only extends SystemLising, this
  3995. // class needs to be hardwired.
  3996. $listing = new SystemListingInfo();
  3997. return $listing->scan($mask, $directory, $key, $min_depth);
  3998. }
  3999. /**
  4000. * Sets the main page content value for later use.
  4001. *
  4002. * Given the nature of the Drupal page handling, this will be called once with
  4003. * a string or array. We store that and return it later as the block is being
  4004. * displayed.
  4005. *
  4006. * @param $content
  4007. * A string or renderable array representing the body of the page.
  4008. *
  4009. * @return
  4010. * If called without $content, a renderable array representing the body of
  4011. * the page.
  4012. */
  4013. function drupal_set_page_content($content = NULL) {
  4014. $content_block = &drupal_static(__FUNCTION__, NULL);
  4015. $main_content_display = &drupal_static('system_main_content_added', FALSE);
  4016. // Filter out each empty value, though allow '0' and 0, which would be
  4017. // filtered out by empty().
  4018. if ($content !== NULL && $content !== '') {
  4019. $content_block = (is_array($content) ? $content : array('main' => array('#markup' => $content)));
  4020. }
  4021. else {
  4022. // Indicate that the main content has been requested. We assume that
  4023. // the module requesting the content will be adding it to the page.
  4024. // A module can indicate that it does not handle the content by setting
  4025. // the static variable back to FALSE after calling this function.
  4026. $main_content_display = TRUE;
  4027. return $content_block;
  4028. }
  4029. }
  4030. /**
  4031. * Pre-render callback: Renders #browsers into #prefix and #suffix.
  4032. *
  4033. * @param $elements
  4034. * A render array with a '#browsers' property. The '#browsers' property can
  4035. * contain any or all of the following keys:
  4036. * - 'IE': If FALSE, the element is not rendered by Internet Explorer. If
  4037. * TRUE, the element is rendered by Internet Explorer. Can also be a string
  4038. * containing an expression for Internet Explorer to evaluate as part of a
  4039. * conditional comment. For example, this can be set to 'lt IE 7' for the
  4040. * element to be rendered in Internet Explorer 6, but not in Internet
  4041. * Explorer 7 or higher. Defaults to TRUE.
  4042. * - '!IE': If FALSE, the element is not rendered by browsers other than
  4043. * Internet Explorer. If TRUE, the element is rendered by those browsers.
  4044. * Defaults to TRUE.
  4045. * Examples:
  4046. * - To render an element in all browsers, '#browsers' can be left out or set
  4047. * to array('IE' => TRUE, '!IE' => TRUE).
  4048. * - To render an element in Internet Explorer only, '#browsers' can be set
  4049. * to array('!IE' => FALSE).
  4050. * - To render an element in Internet Explorer 6 only, '#browsers' can be set
  4051. * to array('IE' => 'lt IE 7', '!IE' => FALSE).
  4052. * - To render an element in Internet Explorer 8 and higher and in all other
  4053. * browsers, '#browsers' can be set to array('IE' => 'gte IE 8').
  4054. *
  4055. * @return
  4056. * The passed-in element with markup for conditional comments potentially
  4057. * added to '#prefix' and '#suffix'.
  4058. */
  4059. function drupal_pre_render_conditional_comments($elements) {
  4060. $browsers = isset($elements['#browsers']) ? $elements['#browsers'] : array();
  4061. $browsers += array(
  4062. 'IE' => TRUE,
  4063. '!IE' => TRUE,
  4064. );
  4065. // If rendering in all browsers, no need for conditional comments.
  4066. if ($browsers['IE'] === TRUE && $browsers['!IE']) {
  4067. return $elements;
  4068. }
  4069. // Determine the conditional comment expression for Internet Explorer to
  4070. // evaluate.
  4071. if ($browsers['IE'] === TRUE) {
  4072. $expression = 'IE';
  4073. }
  4074. elseif ($browsers['IE'] === FALSE) {
  4075. $expression = '!IE';
  4076. }
  4077. else {
  4078. $expression = $browsers['IE'];
  4079. }
  4080. // Wrap the element's potentially existing #prefix and #suffix properties with
  4081. // conditional comment markup. The conditional comment expression is evaluated
  4082. // by Internet Explorer only. To control the rendering by other browsers,
  4083. // either the "downlevel-hidden" or "downlevel-revealed" technique must be
  4084. // used. See http://en.wikipedia.org/wiki/Conditional_comment for details.
  4085. $elements += array(
  4086. '#prefix' => '',
  4087. '#suffix' => '',
  4088. );
  4089. if (!$browsers['!IE']) {
  4090. // "downlevel-hidden".
  4091. $elements['#prefix'] = "\n<!--[if $expression]>\n" . $elements['#prefix'];
  4092. $elements['#suffix'] .= "<![endif]-->\n";
  4093. }
  4094. else {
  4095. // "downlevel-revealed".
  4096. $elements['#prefix'] = "\n<!--[if $expression]><!-->\n" . $elements['#prefix'];
  4097. $elements['#suffix'] .= "<!--<![endif]-->\n";
  4098. }
  4099. return $elements;
  4100. }
  4101. /**
  4102. * Pre-render callback: Renders a generic HTML tag with attributes into #markup.
  4103. *
  4104. * @param array $element
  4105. * An associative array containing:
  4106. * - #tag: The tag name to output. Typical tags added to the HTML HEAD:
  4107. * - meta: To provide meta information, such as a page refresh.
  4108. * - link: To refer to stylesheets and other contextual information.
  4109. * - script: To load JavaScript.
  4110. * - #attributes: (optional) An array of HTML attributes to apply to the
  4111. * tag.
  4112. * - #value: (optional) A string containing tag content, such as inline
  4113. * CSS.
  4114. * - #value_prefix: (optional) A string to prepend to #value, e.g. a CDATA
  4115. * wrapper prefix.
  4116. * - #value_suffix: (optional) A string to append to #value, e.g. a CDATA
  4117. * wrapper suffix.
  4118. */
  4119. function drupal_pre_render_html_tag($element) {
  4120. $attributes = isset($element['#attributes']) ? new Attribute($element['#attributes']) : '';
  4121. if (!isset($element['#value'])) {
  4122. $markup = '<' . $element['#tag'] . $attributes . " />\n";
  4123. }
  4124. else {
  4125. $markup = '<' . $element['#tag'] . $attributes . '>';
  4126. if (isset($element['#value_prefix'])) {
  4127. $markup .= $element['#value_prefix'];
  4128. }
  4129. $markup .= $element['#value'];
  4130. if (isset($element['#value_suffix'])) {
  4131. $markup .= $element['#value_suffix'];
  4132. }
  4133. $markup .= '</' . $element['#tag'] . ">\n";
  4134. }
  4135. $element['#markup'] = $markup;
  4136. return $element;
  4137. }
  4138. /**
  4139. * Pre-render callback: Renders a link into #markup.
  4140. *
  4141. * Doing so during pre_render gives modules a chance to alter the link parts.
  4142. *
  4143. * @param $elements
  4144. * A structured array whose keys form the arguments to l():
  4145. * - #title: The link text to pass as argument to l().
  4146. * - #href: The URL path component to pass as argument to l().
  4147. * - #options: (optional) An array of options to pass to l().
  4148. *
  4149. * @return
  4150. * The passed-in elements containing a rendered link in '#markup'.
  4151. */
  4152. function drupal_pre_render_link($element) {
  4153. // By default, link options to pass to l() are normally set in #options.
  4154. $element += array('#options' => array());
  4155. // However, within the scope of renderable elements, #attributes is a valid
  4156. // way to specify attributes, too. Take them into account, but do not override
  4157. // attributes from #options.
  4158. if (isset($element['#attributes'])) {
  4159. $element['#options'] += array('attributes' => array());
  4160. $element['#options']['attributes'] += $element['#attributes'];
  4161. }
  4162. // This #pre_render callback can be invoked from inside or outside of a Form
  4163. // API context, and depending on that, a HTML ID may be already set in
  4164. // different locations. #options should have precedence over Form API's #id.
  4165. // #attributes have been taken over into #options above already.
  4166. if (isset($element['#options']['attributes']['id'])) {
  4167. $element['#id'] = $element['#options']['attributes']['id'];
  4168. }
  4169. elseif (isset($element['#id'])) {
  4170. $element['#options']['attributes']['id'] = $element['#id'];
  4171. }
  4172. // Conditionally invoke ajax_pre_render_element(), if #ajax is set.
  4173. if (isset($element['#ajax']) && !isset($element['#ajax_processed'])) {
  4174. // If no HTML ID was found above, automatically create one.
  4175. if (!isset($element['#id'])) {
  4176. $element['#id'] = $element['#options']['attributes']['id'] = drupal_html_id('ajax-link');
  4177. }
  4178. // If #ajax['path] was not specified, use the href as Ajax request URL.
  4179. if (!isset($element['#ajax']['path'])) {
  4180. $element['#ajax']['path'] = $element['#href'];
  4181. $element['#ajax']['options'] = $element['#options'];
  4182. }
  4183. $element = ajax_pre_render_element($element);
  4184. }
  4185. $element['#markup'] = l($element['#title'], $element['#href'], $element['#options']);
  4186. return $element;
  4187. }
  4188. /**
  4189. * Pre-render callback: Collects child links into a single array.
  4190. *
  4191. * This function can be added as a pre_render callback for a renderable array,
  4192. * usually one which will be themed by theme_links(). It iterates through all
  4193. * unrendered children of the element, collects any #links properties it finds,
  4194. * merges them into the parent element's #links array, and prevents those
  4195. * children from being rendered separately.
  4196. *
  4197. * The purpose of this is to allow links to be logically grouped into related
  4198. * categories, so that each child group can be rendered as its own list of
  4199. * links if drupal_render() is called on it, but calling drupal_render() on the
  4200. * parent element will still produce a single list containing all the remaining
  4201. * links, regardless of what group they were in.
  4202. *
  4203. * A typical example comes from node links, which are stored in a renderable
  4204. * array similar to this:
  4205. * @code
  4206. * $node->content['links'] = array(
  4207. * '#theme' => 'links__node',
  4208. * '#pre_render' => array('drupal_pre_render_links'),
  4209. * 'comment' => array(
  4210. * '#theme' => 'links__node__comment',
  4211. * '#links' => array(
  4212. * // An array of links associated with node comments, suitable for
  4213. * // passing in to theme_links().
  4214. * ),
  4215. * ),
  4216. * 'statistics' => array(
  4217. * '#theme' => 'links__node__statistics',
  4218. * '#links' => array(
  4219. * // An array of links associated with node statistics, suitable for
  4220. * // passing in to theme_links().
  4221. * ),
  4222. * ),
  4223. * 'translation' => array(
  4224. * '#theme' => 'links__node__translation',
  4225. * '#links' => array(
  4226. * // An array of links associated with node translation, suitable for
  4227. * // passing in to theme_links().
  4228. * ),
  4229. * ),
  4230. * );
  4231. * @endcode
  4232. *
  4233. * In this example, the links are grouped by functionality, which can be
  4234. * helpful to themers who want to display certain kinds of links independently.
  4235. * For example, adding this code to node.html.twig will result in the comment
  4236. * links being rendered as a single list:
  4237. * @code
  4238. * print render($content['links']['comment']);
  4239. * @endcode
  4240. *
  4241. * (where $node->content has been transformed into $content before handing
  4242. * control to the node.html.twig template).
  4243. *
  4244. * The pre_render function defined here allows the above flexibility, but also
  4245. * allows the following code to be used to render all remaining links into a
  4246. * single list, regardless of their group:
  4247. * @code
  4248. * print render($content['links']);
  4249. * @endcode
  4250. *
  4251. * In the above example, this will result in the statistics and translation
  4252. * links being rendered together in a single list (but not the comment links,
  4253. * which were rendered previously on their own).
  4254. *
  4255. * Because of the way this function works, the individual properties of each
  4256. * group (for example, a group-specific #theme property such as
  4257. * 'links__node__comment' in the example above, or any other property such as
  4258. * #attributes or #pre_render that is attached to it) are only used when that
  4259. * group is rendered on its own. When the group is rendered together with other
  4260. * children, these child-specific properties are ignored, and only the overall
  4261. * properties of the parent are used.
  4262. */
  4263. function drupal_pre_render_links($element) {
  4264. $element += array('#links' => array());
  4265. foreach (element_children($element) as $key) {
  4266. $child = &$element[$key];
  4267. // If the child has links which have not been printed yet and the user has
  4268. // access to it, merge its links in to the parent.
  4269. if (isset($child['#links']) && empty($child['#printed']) && (!isset($child['#access']) || $child['#access'])) {
  4270. $element['#links'] += $child['#links'];
  4271. // Mark the child as having been printed already (so that its links
  4272. // cannot be mistakenly rendered twice).
  4273. $child['#printed'] = TRUE;
  4274. }
  4275. }
  4276. return $element;
  4277. }
  4278. /**
  4279. * Pre-render callback: Attaches the dropbutton library and required markup.
  4280. */
  4281. function drupal_pre_render_dropbutton($element) {
  4282. $element['#attached']['library'][] = array('system', 'drupal.dropbutton');
  4283. $element['#attributes']['class'][] = 'dropbutton';
  4284. if (!isset($element['#theme_wrappers'])) {
  4285. $element['#theme_wrappers'] = array();
  4286. }
  4287. array_unshift($element['#theme_wrappers'], 'dropbutton_wrapper');
  4288. // Enable targeted theming of specific dropbuttons (e.g., 'operations' or
  4289. // 'operations__node').
  4290. if (isset($element['#subtype'])) {
  4291. $element['#theme'] .= '__' . $element['#subtype'];
  4292. }
  4293. return $element;
  4294. }
  4295. /**
  4296. * Renders the page, including all theming.
  4297. *
  4298. * @param $page
  4299. * A string or array representing the content of a page. The array consists of
  4300. * the following keys:
  4301. * - #type: Value is always 'page'. This pushes the theming through
  4302. * the page template (required).
  4303. * - #show_messages: Suppress drupal_get_message() items. Used by Batch
  4304. * API (optional).
  4305. *
  4306. * @see hook_page_alter()
  4307. * @see element_info()
  4308. */
  4309. function drupal_render_page($page) {
  4310. $main_content_display = &drupal_static('system_main_content_added', FALSE);
  4311. // Allow menu callbacks to return strings or arbitrary arrays to render.
  4312. // If the array returned is not of #type page directly, we need to fill
  4313. // in the page with defaults.
  4314. if (is_string($page) || (is_array($page) && (!isset($page['#type']) || ($page['#type'] != 'page')))) {
  4315. drupal_set_page_content($page);
  4316. $page = element_info('page');
  4317. }
  4318. // Modules can add elements to $page as needed in hook_page_build().
  4319. foreach (module_implements('page_build') as $module) {
  4320. $function = $module . '_page_build';
  4321. $function($page);
  4322. }
  4323. // Modules alter the $page as needed. Blocks are populated into regions like
  4324. // 'sidebar_first', 'footer', etc.
  4325. drupal_alter('page', $page);
  4326. // If no module has taken care of the main content, add it to the page now.
  4327. // This allows the site to still be usable even if no modules that
  4328. // control page regions (for example, the Block module) are enabled.
  4329. if (!$main_content_display) {
  4330. $page['content']['system_main'] = drupal_set_page_content();
  4331. }
  4332. return drupal_render($page);
  4333. }
  4334. /**
  4335. * Renders HTML given a structured array tree.
  4336. *
  4337. * Recursively iterates over each of the array elements, generating HTML code.
  4338. *
  4339. * Renderable arrays have two kinds of key/value pairs: properties and
  4340. * children. Properties have keys starting with '#' and their values influence
  4341. * how the array will be rendered. Children are all elements whose keys do not
  4342. * start with a '#'. Their values should be renderable arrays themselves,
  4343. * which will be rendered during the rendering of the parent array. The markup
  4344. * provided by the children is typically inserted into the markup generated by
  4345. * the parent array.
  4346. *
  4347. * HTML generation for a renderable array, and the treatment of any children,
  4348. * is controlled by two properties containing theme functions, #theme and
  4349. * #theme_wrappers.
  4350. *
  4351. * #theme is the theme function called first. If it is set and the element has
  4352. * any children, it is the responsibility of the theme function to render
  4353. * these children. For elements that are not allowed to have any children,
  4354. * e.g. buttons or textfields, the theme function can be used to render the
  4355. * element itself. If #theme is not present and the element has children, each
  4356. * child is itself rendered by a call to drupal_render(), and the results are
  4357. * concatenated.
  4358. *
  4359. * The #theme_wrappers property contains an array of theme functions which will
  4360. * be called, in order, after #theme has run. These can be used to add further
  4361. * markup around the rendered children; e.g., details add the required markup
  4362. * for a details element around their rendered child elements. All wrapper theme
  4363. * functions have to include the element's #children property in their output,
  4364. * as it contains the output of the previous theme functions and the rendered
  4365. * children.
  4366. *
  4367. * For example, for the form element type, by default only the #theme_wrappers
  4368. * property is set, which adds the form markup around the rendered child
  4369. * elements of the form. This allows you to set the #theme property on a
  4370. * specific form to a custom theme function, giving you complete control over
  4371. * the placement of the form's children while not at all having to deal with
  4372. * the form markup itself.
  4373. *
  4374. * drupal_render() can optionally cache the rendered output of elements to
  4375. * improve performance. To use drupal_render() caching, set the element's #cache
  4376. * property to an associative array with one or several of the following keys:
  4377. * - 'keys': An array of one or more keys that identify the element. If 'keys'
  4378. * is set, the cache ID is created automatically from these keys. See
  4379. * drupal_render_cid_create().
  4380. * - 'granularity' (optional): Define the cache granularity using binary
  4381. * combinations of the cache granularity constants, e.g.
  4382. * DRUPAL_CACHE_PER_USER to cache for each user separately or
  4383. * DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE to cache separately for each
  4384. * page and role. If not specified the element is cached globally for each
  4385. * theme and language.
  4386. * - 'cid': Specify the cache ID directly. Either 'keys' or 'cid' is required.
  4387. * If 'cid' is set, 'keys' and 'granularity' are ignored. Use only if you
  4388. * have special requirements.
  4389. * - 'expire': Set to one of the cache lifetime constants.
  4390. * - 'bin': Specify a cache bin to cache the element in. Defaults to 'cache'.
  4391. *
  4392. * This function is usually called from within another function, like
  4393. * drupal_get_form() or a theme function. Elements are sorted internally
  4394. * using uasort(). Since this is expensive, when passing already sorted
  4395. * elements to drupal_render(), for example from a database query, set
  4396. * $elements['#sorted'] = TRUE to avoid sorting them a second time.
  4397. *
  4398. * drupal_render() flags each element with a '#printed' status to indicate that
  4399. * the element has been rendered, which allows individual elements of a given
  4400. * array to be rendered independently and prevents them from being rendered
  4401. * more than once on subsequent calls to drupal_render() (e.g., as part of a
  4402. * larger array). If the same array or array element is passed more than once
  4403. * to drupal_render(), it simply returns an empty string.
  4404. *
  4405. * @param array $elements
  4406. * The structured array describing the data to be rendered.
  4407. *
  4408. * @return string
  4409. * The rendered HTML.
  4410. */
  4411. function drupal_render(&$elements) {
  4412. // Early-return nothing if user does not have access.
  4413. if (empty($elements) || (isset($elements['#access']) && !$elements['#access'])) {
  4414. return '';
  4415. }
  4416. // Do not print elements twice.
  4417. if (!empty($elements['#printed'])) {
  4418. return '';
  4419. }
  4420. // Try to fetch the element's markup from cache and return.
  4421. if (isset($elements['#cache'])) {
  4422. $cached_output = drupal_render_cache_get($elements);
  4423. if ($cached_output !== FALSE) {
  4424. return $cached_output;
  4425. }
  4426. }
  4427. // If #markup is set, ensure #type is set. This allows to specify just #markup
  4428. // on an element without setting #type.
  4429. if (isset($elements['#markup']) && !isset($elements['#type'])) {
  4430. $elements['#type'] = 'markup';
  4431. }
  4432. // If the default values for this element have not been loaded yet, populate
  4433. // them.
  4434. if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
  4435. $elements += element_info($elements['#type']);
  4436. }
  4437. // Make any final changes to the element before it is rendered. This means
  4438. // that the $element or the children can be altered or corrected before the
  4439. // element is rendered into the final text.
  4440. if (isset($elements['#pre_render'])) {
  4441. foreach ($elements['#pre_render'] as $callable) {
  4442. $elements = call_user_func($callable, $elements);
  4443. }
  4444. }
  4445. // Allow #pre_render to abort rendering.
  4446. if (!empty($elements['#printed'])) {
  4447. return '';
  4448. }
  4449. // Get the children of the element, sorted by weight.
  4450. $children = element_children($elements, TRUE);
  4451. // Initialize this element's #children, unless a #pre_render callback already
  4452. // preset #children.
  4453. if (!isset($elements['#children'])) {
  4454. $elements['#children'] = '';
  4455. }
  4456. // Call the element's #theme function if it is set. Then any children of the
  4457. // element have to be rendered there. If the internal #render_children
  4458. // property is set, do not call the #theme function to prevent infinite
  4459. // recursion.
  4460. if (isset($elements['#theme']) && !isset($elements['#render_children'])) {
  4461. $elements['#children'] = theme($elements['#theme'], $elements);
  4462. }
  4463. // If #theme was not set and the element has children, render them now.
  4464. // This is the same process as drupal_render_children() but is inlined
  4465. // for speed.
  4466. if ($elements['#children'] === '') {
  4467. foreach ($children as $key) {
  4468. $elements['#children'] .= drupal_render($elements[$key]);
  4469. }
  4470. }
  4471. // If #theme was not set, but the element has raw #markup, prepend the content
  4472. // in #markup to #children. #children may contain the rendered content
  4473. // supplied by #theme, or the rendered child elements, as processed above. If
  4474. // both #theme and #markup are set, then #theme is responsible for rendering
  4475. // the element. Eventually assigned #theme_wrappers will expect both the
  4476. // element's #markup and the rendered content of child elements in #children.
  4477. if (!isset($elements['#theme']) && isset($elements['#markup'])) {
  4478. $elements['#children'] = $elements['#markup'] . $elements['#children'];
  4479. }
  4480. // Add any JavaScript state information associated with the element.
  4481. if (!empty($elements['#states'])) {
  4482. drupal_process_states($elements);
  4483. }
  4484. // Add additional libraries, CSS, JavaScript an other custom
  4485. // attached data associated with this element.
  4486. if (!empty($elements['#attached'])) {
  4487. drupal_process_attached($elements);
  4488. }
  4489. // Let the theme functions in #theme_wrappers add markup around the rendered
  4490. // children.
  4491. // #states and #attached have to be processed before #theme_wrappers, because
  4492. // the #type 'page' render array from drupal_render_page() would render the
  4493. // $page and wrap it into the html.tpl.php template without the attached
  4494. // assets otherwise.
  4495. // If the internal #render_children property is set, do not call the
  4496. // #theme_wrappers function(s) to prevent infinite recursion.
  4497. if (isset($elements['#theme_wrappers']) && !isset($elements['#render_children'])) {
  4498. foreach ($elements['#theme_wrappers'] as $theme_wrapper) {
  4499. $elements['#children'] = theme($theme_wrapper, $elements);
  4500. }
  4501. }
  4502. // Filter the outputted content and make any last changes before the
  4503. // content is sent to the browser. The changes are made on $content
  4504. // which allows the output'ed text to be filtered.
  4505. if (isset($elements['#post_render'])) {
  4506. foreach ($elements['#post_render'] as $callable) {
  4507. $elements['#children'] = call_user_func($callable, $elements['#children'], $elements);
  4508. }
  4509. }
  4510. $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
  4511. $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
  4512. $output = $prefix . $elements['#children'] . $suffix;
  4513. // Cache the processed element if #cache is set.
  4514. if (isset($elements['#cache'])) {
  4515. drupal_render_cache_set($output, $elements);
  4516. }
  4517. $elements['#printed'] = TRUE;
  4518. return $output;
  4519. }
  4520. /**
  4521. * Renders children of an element and concatenates them.
  4522. *
  4523. * This renders all children of an element using drupal_render() and then
  4524. * joins them together into a single string.
  4525. *
  4526. * @param $element
  4527. * The structured array whose children shall be rendered.
  4528. * @param $children_keys
  4529. * If the keys of the element's children are already known, they can be passed
  4530. * in to save another run of element_children().
  4531. */
  4532. function drupal_render_children(&$element, $children_keys = NULL) {
  4533. if ($children_keys === NULL) {
  4534. $children_keys = element_children($element);
  4535. }
  4536. $output = '';
  4537. foreach ($children_keys as $key) {
  4538. if (!empty($element[$key])) {
  4539. $output .= drupal_render($element[$key]);
  4540. }
  4541. }
  4542. return $output;
  4543. }
  4544. /**
  4545. * Renders an element.
  4546. *
  4547. * This function renders an element using drupal_render(). The top level
  4548. * element is shown with show() before rendering, so it will always be rendered
  4549. * even if hide() had been previously used on it.
  4550. *
  4551. * @param $element
  4552. * The element to be rendered.
  4553. *
  4554. * @return
  4555. * The rendered element.
  4556. *
  4557. * @see drupal_render()
  4558. * @see show()
  4559. * @see hide()
  4560. */
  4561. function render(&$element) {
  4562. if (!$element && $element !== 0) {
  4563. return NULL;
  4564. }
  4565. if (is_array($element)) {
  4566. show($element);
  4567. return drupal_render($element);
  4568. }
  4569. else {
  4570. // Safe-guard for inappropriate use of render() on flat variables: return
  4571. // the variable as-is.
  4572. return $element;
  4573. }
  4574. }
  4575. /**
  4576. * Hides an element from later rendering.
  4577. *
  4578. * The first time render() or drupal_render() is called on an element tree,
  4579. * as each element in the tree is rendered, it is marked with a #printed flag
  4580. * and the rendered children of the element are cached. Subsequent calls to
  4581. * render() or drupal_render() will not traverse the child tree of this element
  4582. * again: they will just use the cached children. So if you want to hide an
  4583. * element, be sure to call hide() on the element before its parent tree is
  4584. * rendered for the first time, as it will have no effect on subsequent
  4585. * renderings of the parent tree.
  4586. *
  4587. * @param $element
  4588. * The element to be hidden.
  4589. *
  4590. * @return
  4591. * The element.
  4592. *
  4593. * @see render()
  4594. * @see show()
  4595. */
  4596. function hide(&$element) {
  4597. $element['#printed'] = TRUE;
  4598. return $element;
  4599. }
  4600. /**
  4601. * Shows a hidden element for later rendering.
  4602. *
  4603. * You can also use render($element), which shows the element while rendering
  4604. * it.
  4605. *
  4606. * The first time render() or drupal_render() is called on an element tree,
  4607. * as each element in the tree is rendered, it is marked with a #printed flag
  4608. * and the rendered children of the element are cached. Subsequent calls to
  4609. * render() or drupal_render() will not traverse the child tree of this element
  4610. * again: they will just use the cached children. So if you want to show an
  4611. * element, be sure to call show() on the element before its parent tree is
  4612. * rendered for the first time, as it will have no effect on subsequent
  4613. * renderings of the parent tree.
  4614. *
  4615. * @param $element
  4616. * The element to be shown.
  4617. *
  4618. * @return
  4619. * The element.
  4620. *
  4621. * @see render()
  4622. * @see hide()
  4623. */
  4624. function show(&$element) {
  4625. $element['#printed'] = FALSE;
  4626. return $element;
  4627. }
  4628. /**
  4629. * Gets the rendered output of a renderable element from the cache.
  4630. *
  4631. * @param $elements
  4632. * A renderable array.
  4633. *
  4634. * @return
  4635. * A markup string containing the rendered content of the element, or FALSE
  4636. * if no cached copy of the element is available.
  4637. *
  4638. * @see drupal_render()
  4639. * @see drupal_render_cache_set()
  4640. */
  4641. function drupal_render_cache_get($elements) {
  4642. if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
  4643. return FALSE;
  4644. }
  4645. $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
  4646. if (!empty($cid) && $cache = cache($bin)->get($cid)) {
  4647. // Add additional libraries, JavaScript, CSS and other data attached
  4648. // to this element.
  4649. if (isset($cache->data['#attached'])) {
  4650. drupal_process_attached($cache->data);
  4651. }
  4652. // Return the rendered output.
  4653. return $cache->data['#markup'];
  4654. }
  4655. return FALSE;
  4656. }
  4657. /**
  4658. * Caches the rendered output of a renderable element.
  4659. *
  4660. * This is called by drupal_render() if the #cache property is set on an
  4661. * element.
  4662. *
  4663. * @param $markup
  4664. * The rendered output string of $elements.
  4665. * @param $elements
  4666. * A renderable array.
  4667. *
  4668. * @see drupal_render_cache_get()
  4669. */
  4670. function drupal_render_cache_set(&$markup, $elements) {
  4671. // Create the cache ID for the element.
  4672. if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
  4673. return FALSE;
  4674. }
  4675. // Cache implementations are allowed to modify the markup, to support
  4676. // replacing markup with edge-side include commands. The supporting cache
  4677. // backend will store the markup in some other key (like
  4678. // $data['#real-value']) and return an include command instead. When the
  4679. // ESI command is executed by the content accelerator, the real value can
  4680. // be retrieved and used.
  4681. $data['#markup'] = &$markup;
  4682. // Persist attached data associated with this element.
  4683. $attached = drupal_render_collect_attached($elements, TRUE);
  4684. if ($attached) {
  4685. $data['#attached'] = $attached;
  4686. }
  4687. $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
  4688. $expire = isset($elements['#cache']['expire']) ? $elements['#cache']['expire'] : CacheBackendInterface::CACHE_PERMANENT;
  4689. $tags = isset($elements['#cache']['tags']) ? $elements['#cache']['tags'] : array();
  4690. cache($bin)->set($cid, $data, $expire, $tags);
  4691. }
  4692. /**
  4693. * Collects #attached for an element and its children into a single array.
  4694. *
  4695. * When caching elements, it is necessary to collect all libraries, JavaScript
  4696. * and CSS into a single array, from both the element itself and all child
  4697. * elements. This allows drupal_render() to add these back to the page when the
  4698. * element is returned from cache.
  4699. *
  4700. * @param $elements
  4701. * The element to collect #attached from.
  4702. * @param $return
  4703. * Whether to return the attached elements and reset the internal static.
  4704. *
  4705. * @return
  4706. * The #attached array for this element and its descendants.
  4707. */
  4708. function drupal_render_collect_attached($elements, $return = FALSE) {
  4709. $attached = &drupal_static(__FUNCTION__, array());
  4710. // Collect all #attached for this element.
  4711. if (isset($elements['#attached'])) {
  4712. foreach ($elements['#attached'] as $key => $value) {
  4713. if (!isset($attached[$key])) {
  4714. $attached[$key] = array();
  4715. }
  4716. $attached[$key] = array_merge($attached[$key], $value);
  4717. }
  4718. }
  4719. if ($children = element_children($elements)) {
  4720. foreach ($children as $child) {
  4721. drupal_render_collect_attached($elements[$child]);
  4722. }
  4723. }
  4724. // If this was the first call to the function, return all attached elements
  4725. // and reset the static cache.
  4726. if ($return) {
  4727. $return = $attached;
  4728. $attached = array();
  4729. return $return;
  4730. }
  4731. }
  4732. /**
  4733. * Prepares an element for caching based on a query.
  4734. *
  4735. * This smart caching strategy saves Drupal from querying and rendering to HTML
  4736. * when the underlying query is unchanged.
  4737. *
  4738. * Expensive queries should use the query builder to create the query and then
  4739. * call this function. Executing the query and formatting results should happen
  4740. * in a #pre_render callback.
  4741. *
  4742. * @param $query
  4743. * A select query object as returned by db_select().
  4744. * @param $function
  4745. * The name of the function doing this caching. A _pre_render suffix will be
  4746. * added to this string and is also part of the cache key in
  4747. * drupal_render_cache_set() and drupal_render_cache_get().
  4748. * @param $expire
  4749. * The cache expire time, passed eventually to cache()->set().
  4750. * @param $granularity
  4751. * One or more granularity constants passed to drupal_render_cid_parts().
  4752. *
  4753. * @return
  4754. * A renderable array with the following keys and values:
  4755. * - #query: The passed-in $query.
  4756. * - #pre_render: $function with a _pre_render suffix.
  4757. * - #cache: An associative array prepared for drupal_render_cache_set().
  4758. */
  4759. function drupal_render_cache_by_query($query, $function, $expire = CacheBackendInterface::CACHE_PERMANENT, $granularity = NULL) {
  4760. $cache_keys = array_merge(array($function), drupal_render_cid_parts($granularity));
  4761. $query->preExecute();
  4762. $cache_keys[] = hash('sha256', serialize(array((string) $query, $query->getArguments())));
  4763. return array(
  4764. '#query' => $query,
  4765. '#pre_render' => array($function . '_pre_render'),
  4766. '#cache' => array(
  4767. 'keys' => $cache_keys,
  4768. 'expire' => $expire,
  4769. ),
  4770. );
  4771. }
  4772. /**
  4773. * Returns cache ID parts for building a cache ID.
  4774. *
  4775. * @param $granularity
  4776. * One or more cache granularity constants. For example, to cache separately
  4777. * for each user, use DRUPAL_CACHE_PER_USER. To cache separately for each
  4778. * page and role, use the expression:
  4779. * @code
  4780. * DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE
  4781. * @endcode
  4782. *
  4783. * @return
  4784. * An array of cache ID parts, always containing the active theme. If the
  4785. * locale module is enabled it also contains the active language. If
  4786. * $granularity was passed in, more parts are added.
  4787. */
  4788. function drupal_render_cid_parts($granularity = NULL) {
  4789. global $theme, $base_root, $user;
  4790. $cid_parts[] = $theme;
  4791. // If Locale is enabled but we have only one language we do not need it as cid
  4792. // part.
  4793. if (language_multilingual()) {
  4794. foreach (language_types_get_configurable() as $language_type) {
  4795. $cid_parts[] = language($language_type)->langcode;
  4796. }
  4797. }
  4798. if (!empty($granularity)) {
  4799. // 'PER_ROLE' and 'PER_USER' are mutually exclusive. 'PER_USER' can be a
  4800. // resource drag for sites with many users, so when a module is being
  4801. // equivocal, we favor the less expensive 'PER_ROLE' pattern.
  4802. if ($granularity & DRUPAL_CACHE_PER_ROLE) {
  4803. $cid_parts[] = 'r.' . implode(',', $user->roles);
  4804. }
  4805. elseif ($granularity & DRUPAL_CACHE_PER_USER) {
  4806. $cid_parts[] = "u.$user->uid";
  4807. }
  4808. if ($granularity & DRUPAL_CACHE_PER_PAGE) {
  4809. $cid_parts[] = $base_root . request_uri();
  4810. }
  4811. }
  4812. return $cid_parts;
  4813. }
  4814. /**
  4815. * Creates the cache ID for a renderable element.
  4816. *
  4817. * This creates the cache ID string, either by returning the #cache['cid']
  4818. * property if present or by building the cache ID out of the #cache['keys']
  4819. * and, optionally, the #cache['granularity'] properties.
  4820. *
  4821. * @param $elements
  4822. * A renderable array.
  4823. *
  4824. * @return
  4825. * The cache ID string, or FALSE if the element may not be cached.
  4826. */
  4827. function drupal_render_cid_create($elements) {
  4828. if (isset($elements['#cache']['cid'])) {
  4829. return $elements['#cache']['cid'];
  4830. }
  4831. elseif (isset($elements['#cache']['keys'])) {
  4832. $granularity = isset($elements['#cache']['granularity']) ? $elements['#cache']['granularity'] : NULL;
  4833. // Merge in additional cache ID parts based provided by drupal_render_cid_parts().
  4834. $cid_parts = array_merge($elements['#cache']['keys'], drupal_render_cid_parts($granularity));
  4835. return implode(':', $cid_parts);
  4836. }
  4837. return FALSE;
  4838. }
  4839. /**
  4840. * Sorts a structured array by '#weight' property.
  4841. *
  4842. * Callback for uasort() within element_children().
  4843. *
  4844. * @param $a
  4845. * First item for comparison. The compared items should be associative arrays
  4846. * that optionally include a '#weight' key.
  4847. * @param $b
  4848. * Second item for comparison.
  4849. */
  4850. function element_sort($a, $b) {
  4851. $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
  4852. $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
  4853. if ($a_weight == $b_weight) {
  4854. return 0;
  4855. }
  4856. return ($a_weight < $b_weight) ? -1 : 1;
  4857. }
  4858. /**
  4859. * Sorts a structured array by '#title' property.
  4860. *
  4861. * Callback for uasort() within:
  4862. * - system_modules()
  4863. * - theme_simpletest_test_table()
  4864. *
  4865. * @param $a
  4866. * First item for comparison. The compared items should be associative arrays
  4867. * that optionally include a '#title' key.
  4868. * @param $b
  4869. * Second item for comparison.
  4870. */
  4871. function element_sort_by_title($a, $b) {
  4872. $a_title = (is_array($a) && isset($a['#title'])) ? $a['#title'] : '';
  4873. $b_title = (is_array($b) && isset($b['#title'])) ? $b['#title'] : '';
  4874. return strnatcasecmp($a_title, $b_title);
  4875. }
  4876. /**
  4877. * Retrieves the default properties for the defined element type.
  4878. *
  4879. * @param $type
  4880. * An element type as defined by hook_element_info().
  4881. */
  4882. function element_info($type) {
  4883. // Use the advanced drupal_static() pattern, since this is called very often.
  4884. static $drupal_static_fast;
  4885. if (!isset($drupal_static_fast)) {
  4886. $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__);
  4887. }
  4888. $cache = &$drupal_static_fast['cache'];
  4889. if (!isset($cache)) {
  4890. $cache = module_invoke_all('element_info');
  4891. foreach ($cache as $element_type => $info) {
  4892. $cache[$element_type]['#type'] = $element_type;
  4893. }
  4894. // Allow modules to alter the element type defaults.
  4895. drupal_alter('element_info', $cache);
  4896. }
  4897. return isset($cache[$type]) ? $cache[$type] : array();
  4898. }
  4899. /**
  4900. * Retrieves a single property for the defined element type.
  4901. *
  4902. * @param $type
  4903. * An element type as defined by hook_element_info().
  4904. * @param $property_name
  4905. * The property within the element type that should be returned.
  4906. * @param $default
  4907. * (Optional) The value to return if the element type does not specify a
  4908. * value for the property. Defaults to NULL.
  4909. */
  4910. function element_info_property($type, $property_name, $default = NULL) {
  4911. return (($info = element_info($type)) && array_key_exists($property_name, $info)) ? $info[$property_name] : $default;
  4912. }
  4913. /**
  4914. * Sorts a structured array by the 'weight' element.
  4915. *
  4916. * Note that the sorting is by the 'weight' array element, not by the render
  4917. * element property '#weight'.
  4918. *
  4919. * Callback for uasort() used in various functions.
  4920. *
  4921. * @param $a
  4922. * First item for comparison. The compared items should be associative arrays
  4923. * that optionally include a 'weight' element. For items without a 'weight'
  4924. * element, a default value of 0 will be used.
  4925. * @param $b
  4926. * Second item for comparison.
  4927. */
  4928. function drupal_sort_weight($a, $b) {
  4929. $a_weight = (is_array($a) && isset($a['weight'])) ? $a['weight'] : 0;
  4930. $b_weight = (is_array($b) && isset($b['weight'])) ? $b['weight'] : 0;
  4931. if ($a_weight == $b_weight) {
  4932. return 0;
  4933. }
  4934. return ($a_weight < $b_weight) ? -1 : 1;
  4935. }
  4936. /**
  4937. * Sorts a structured array by 'title' key (no # prefix).
  4938. *
  4939. * Callback for uasort() within system_admin_index().
  4940. *
  4941. * @param $a
  4942. * First item for comparison. The compared items should be associative arrays
  4943. * that optionally include a 'title' key.
  4944. * @param $b
  4945. * Second item for comparison.
  4946. */
  4947. function drupal_sort_title($a, $b) {
  4948. if (!isset($b['title'])) {
  4949. return -1;
  4950. }
  4951. if (!isset($a['title'])) {
  4952. return 1;
  4953. }
  4954. return strcasecmp($a['title'], $b['title']);
  4955. }
  4956. /**
  4957. * Checks if the key is a property.
  4958. */
  4959. function element_property($key) {
  4960. return $key[0] == '#';
  4961. }
  4962. /**
  4963. * Gets properties of a structured array element (keys beginning with '#').
  4964. */
  4965. function element_properties($element) {
  4966. return array_filter(array_keys((array) $element), 'element_property');
  4967. }
  4968. /**
  4969. * Checks if the key is a child.
  4970. */
  4971. function element_child($key) {
  4972. return !isset($key[0]) || $key[0] != '#';
  4973. }
  4974. /**
  4975. * Identifies the children of an element array, optionally sorted by weight.
  4976. *
  4977. * The children of a element array are those key/value pairs whose key does
  4978. * not start with a '#'. See drupal_render() for details.
  4979. *
  4980. * @param $elements
  4981. * The element array whose children are to be identified.
  4982. * @param $sort
  4983. * Boolean to indicate whether the children should be sorted by weight.
  4984. *
  4985. * @return
  4986. * The array keys of the element's children.
  4987. */
  4988. function element_children(&$elements, $sort = FALSE) {
  4989. // Do not attempt to sort elements which have already been sorted.
  4990. $sort = isset($elements['#sorted']) ? !$elements['#sorted'] : $sort;
  4991. // Filter out properties from the element, leaving only children.
  4992. $children = array();
  4993. $sortable = FALSE;
  4994. foreach ($elements as $key => $value) {
  4995. if ($key === '' || $key[0] !== '#') {
  4996. if (is_array($value)) {
  4997. $children[$key] = $value;
  4998. if (isset($value['#weight'])) {
  4999. $sortable = TRUE;
  5000. }
  5001. }
  5002. // Only trigger an error if the value is not null.
  5003. // @see http://drupal.org/node/1283892
  5004. elseif (isset($value)) {
  5005. trigger_error(t('"@key" is an invalid render array key', array('@key' => $key)), E_USER_ERROR);
  5006. }
  5007. }
  5008. }
  5009. // Sort the children if necessary.
  5010. if ($sort && $sortable) {
  5011. uasort($children, 'element_sort');
  5012. // Put the sorted children back into $elements in the correct order, to
  5013. // preserve sorting if the same element is passed through
  5014. // element_children() twice.
  5015. foreach ($children as $key => $child) {
  5016. unset($elements[$key]);
  5017. $elements[$key] = $child;
  5018. }
  5019. $elements['#sorted'] = TRUE;
  5020. }
  5021. return array_keys($children);
  5022. }
  5023. /**
  5024. * Returns the visible children of an element.
  5025. *
  5026. * @param $elements
  5027. * The parent element.
  5028. *
  5029. * @return
  5030. * The array keys of the element's visible children.
  5031. */
  5032. function element_get_visible_children(array $elements) {
  5033. $visible_children = array();
  5034. foreach (element_children($elements) as $key) {
  5035. $child = $elements[$key];
  5036. // Skip un-accessible children.
  5037. if (isset($child['#access']) && !$child['#access']) {
  5038. continue;
  5039. }
  5040. // Skip value and hidden elements, since they are not rendered.
  5041. if (isset($child['#type']) && in_array($child['#type'], array('value', 'hidden'))) {
  5042. continue;
  5043. }
  5044. $visible_children[$key] = $child;
  5045. }
  5046. return array_keys($visible_children);
  5047. }
  5048. /**
  5049. * Sets HTML attributes based on element properties.
  5050. *
  5051. * @param $element
  5052. * The renderable element to process.
  5053. * @param $map
  5054. * An associative array whose keys are element property names and whose values
  5055. * are the HTML attribute names to set for corresponding the property; e.g.,
  5056. * array('#propertyname' => 'attributename'). If both names are identical
  5057. * except for the leading '#', then an attribute name value is sufficient and
  5058. * no property name needs to be specified.
  5059. */
  5060. function element_set_attributes(array &$element, array $map) {
  5061. foreach ($map as $property => $attribute) {
  5062. // If the key is numeric, the attribute name needs to be taken over.
  5063. if (is_int($property)) {
  5064. $property = '#' . $attribute;
  5065. }
  5066. // Do not overwrite already existing attributes.
  5067. if (isset($element[$property]) && !isset($element['#attributes'][$attribute])) {
  5068. $element['#attributes'][$attribute] = $element[$property];
  5069. }
  5070. }
  5071. }
  5072. /**
  5073. * Parses Drupal module and theme .info.yml files.
  5074. *
  5075. * Info files are NOT for placing arbitrary theme and module-specific settings.
  5076. * Use Config::get() and Config::set()->save() for that. Info files are
  5077. * formatted as YAML. If the 'version' key is set to 'VERSION' in any info file,
  5078. * then the value will be substituted with the current version of Drupal core.
  5079. *
  5080. * Information stored in a module .info.yml file:
  5081. * - name: The real name of the module for display purposes.
  5082. * - description: A brief description of the module.
  5083. * - dependencies: An array of shortnames of other modules this module requires.
  5084. * - package: The name of the package of modules this module belongs to.
  5085. *
  5086. * See forum.info.yml for an example of a module .info.yml file.
  5087. *
  5088. * Information stored in a theme .info.yml file:
  5089. * - name: The real name of the theme for display purposes.
  5090. * - description: Brief description.
  5091. * - screenshot: Path to screenshot relative to the theme's .info.yml file.
  5092. * - engine: Theme engine; typically twig.
  5093. * - base theme: Name of a base theme, if applicable.
  5094. * - regions: Listed regions.
  5095. * - features: Features available.
  5096. * - stylesheets: Theme stylesheets.
  5097. * - scripts: Theme scripts.
  5098. *
  5099. * See bartik.info.yml for an example of a theme .info.yml file.
  5100. *
  5101. * @param string $filename
  5102. * The file we are parsing. Accepts file with relative or absolute path.
  5103. *
  5104. * @return array
  5105. * The info array.
  5106. */
  5107. function drupal_parse_info_file($filename) {
  5108. $info = &drupal_static(__FUNCTION__, array());
  5109. if (!isset($info[$filename])) {
  5110. if (!file_exists($filename)) {
  5111. $info[$filename] = array();
  5112. }
  5113. else {
  5114. $parser = new Parser();
  5115. $info[$filename] = $parser->parse(file_get_contents($filename));
  5116. if (isset($info[$filename]['version']) && $info[$filename]['version'] === 'VERSION') {
  5117. $info[$filename]['version'] = VERSION;
  5118. }
  5119. }
  5120. }
  5121. return $info[$filename];
  5122. }
  5123. /**
  5124. * Returns a list of severity levels, as defined in RFC 3164.
  5125. *
  5126. * @return
  5127. * Array of the possible severity levels for log messages.
  5128. *
  5129. * @see http://www.ietf.org/rfc/rfc3164.txt
  5130. * @see watchdog()
  5131. * @ingroup logging_severity_levels
  5132. */
  5133. function watchdog_severity_levels() {
  5134. return array(
  5135. WATCHDOG_EMERGENCY => t('Emergency'),
  5136. WATCHDOG_ALERT => t('Alert'),
  5137. WATCHDOG_CRITICAL => t('Critical'),
  5138. WATCHDOG_ERROR => t('Error'),
  5139. WATCHDOG_WARNING => t('Warning'),
  5140. WATCHDOG_NOTICE => t('Notice'),
  5141. WATCHDOG_INFO => t('Info'),
  5142. WATCHDOG_DEBUG => t('Debug'),
  5143. );
  5144. }
  5145. /**
  5146. * Explodes a string of tags into an array.
  5147. *
  5148. * @see drupal_implode_tags()
  5149. * @see \Drupal\Component\Utility\String::explodeTags().
  5150. *
  5151. * @deprecated as of Drupal 8.0. Use Tags::explode() instead.
  5152. */
  5153. function drupal_explode_tags($tags) {
  5154. return Tags::explode($tags);
  5155. }
  5156. /**
  5157. * Implodes an array of tags into a string.
  5158. *
  5159. * @see drupal_explode_tags()
  5160. * @see \Drupal\Component\Utility\String::implodeTags().
  5161. *
  5162. * @deprecated as of Drupal 8.0. Use Tags::implode() instead.
  5163. */
  5164. function drupal_implode_tags($tags) {
  5165. return Tags::implode($tags);
  5166. }
  5167. /**
  5168. * Flushes all persistent caches, resets all variables, and rebuilds all data structures.
  5169. *
  5170. * At times, it is necessary to re-initialize the entire system to account for
  5171. * changed or new code. This function:
  5172. * - Clears all persistent caches:
  5173. * - The bootstrap cache bin containing base system, module system, and theme
  5174. * system information.
  5175. * - The common 'cache' cache bin containing arbitrary caches.
  5176. * - The page cache.
  5177. * - The URL alias path cache.
  5178. * - Resets all static variables that have been defined via drupal_static().
  5179. * - Clears asset (JS/CSS) file caches.
  5180. * - Updates the system with latest information about extensions (modules and
  5181. * themes).
  5182. * - Updates the bootstrap flag for modules implementing bootstrap_hooks().
  5183. * - Rebuilds the full database schema information (invoking hook_schema()).
  5184. * - Rebuilds data structures of all modules (invoking hook_rebuild()). In
  5185. * core this means
  5186. * - blocks, node types, date formats and actions are synchronized with the
  5187. * database
  5188. * - The 'active' status of fields is refreshed.
  5189. * - Rebuilds the menu router.
  5190. *
  5191. * This means the entire system is reset so all caches and static variables are
  5192. * effectively empty. After that is guaranteed, information about the currently
  5193. * active code is updated, and rebuild operations are successively called in
  5194. * order to synchronize the active system according to the current information
  5195. * defined in code.
  5196. *
  5197. * All modules need to ensure that all of their caches are flushed when
  5198. * hook_cache_flush() is invoked; any previously known information must no
  5199. * longer exist. All following hook_rebuild() operations must be based on fresh
  5200. * and current system data. All modules must be able to rely on this contract.
  5201. *
  5202. * @see \Drupal\Core\Cache\CacheHelper::getBins()
  5203. * @see hook_cache_flush()
  5204. * @see hook_rebuild()
  5205. *
  5206. * This function also resets the theme, which means it is not initialized
  5207. * anymore and all previously added JavaScript and CSS is gone. Normally, this
  5208. * function is called as an end-of-POST-request operation that is followed by a
  5209. * redirect, so this effect is not visible. Since the full reset is the whole
  5210. * point of this function, callers need to take care for backing up all needed
  5211. * variables and properly restoring or re-initializing them on their own. For
  5212. * convenience, this function automatically re-initializes the maintenance theme
  5213. * if it was initialized before.
  5214. *
  5215. * @todo Try to clear page/JS/CSS caches last, so cached pages can still be
  5216. * served during this possibly long-running operation. (Conflict on bootstrap
  5217. * cache though.)
  5218. * @todo Add a global lock to ensure that caches are not primed in concurrent
  5219. * requests.
  5220. */
  5221. function drupal_flush_all_caches() {
  5222. $module_handler = Drupal::moduleHandler();
  5223. // Flush all persistent caches.
  5224. // This is executed based on old/previously known information, which is
  5225. // sufficient, since new extensions cannot have any primed caches yet.
  5226. $module_handler->invokeAll('cache_flush');
  5227. foreach (Cache::getBins() as $service_id => $cache_backend) {
  5228. if ($service_id != 'cache.menu') {
  5229. $cache_backend->deleteAll();
  5230. }
  5231. }
  5232. // Flush asset file caches.
  5233. drupal_clear_css_cache();
  5234. drupal_clear_js_cache();
  5235. _drupal_flush_css_js();
  5236. // Reset all static caches.
  5237. drupal_static_reset();
  5238. // Clear all non-drupal_static() static caches.
  5239. Drupal::entityManager()->clearCachedDefinitions();
  5240. // Wipe the PHP Storage caches.
  5241. PhpStorageFactory::get('service_container')->deleteAll();
  5242. PhpStorageFactory::get('twig')->deleteAll();
  5243. // Rebuild module and theme data.
  5244. $module_data = system_rebuild_module_data();
  5245. system_rebuild_theme_data();
  5246. // Rebuild and reboot a new kernel. A simple DrupalKernel reboot is not
  5247. // sufficient, since the list of enabled modules might have been adjusted
  5248. // above due to changed code.
  5249. $files = array();
  5250. foreach ($module_data as $module => $data) {
  5251. if (isset($data->uri) && $data->status) {
  5252. $files[$module] = $data->uri;
  5253. }
  5254. }
  5255. Drupal::service('kernel')->updateModules($module_handler->getModuleList(), $files);
  5256. // New container, new module handler.
  5257. $module_handler = Drupal::moduleHandler();
  5258. // Ensure that all modules that are currently supposed to be enabled are
  5259. // actually loaded.
  5260. $module_handler->loadAll();
  5261. // Update the list of bootstrap modules.
  5262. // Allows developers to get new bootstrap hooks implementations registered
  5263. // without having to write a hook_update_N() function.
  5264. _system_update_bootstrap_status();
  5265. // Rebuild the schema and cache a fully-built schema based on new module data.
  5266. // This is necessary for any invocation of index.php, because setting cache
  5267. // table entries requires schema information and that occurs during bootstrap
  5268. // before any modules are loaded, so if there is no cached schema,
  5269. // drupal_get_schema() will try to generate one, but with no loaded modules,
  5270. // it will return nothing.
  5271. drupal_get_schema(NULL, TRUE);
  5272. // Rebuild all information based on new module data.
  5273. $module_handler->invokeAll('rebuild');
  5274. // Rebuild the menu router based on all rebuilt data.
  5275. // Important: This rebuild must happen last, so the menu router is guaranteed
  5276. // to be based on up to date information.
  5277. Drupal::service('router.builder')->rebuild();
  5278. menu_router_rebuild();
  5279. // Re-initialize the maintenance theme, if the current request attempted to
  5280. // use it. Unlike regular usages of this function, the installer and update
  5281. // scripts need to flush all caches during GET requests/page building.
  5282. if (function_exists('_drupal_maintenance_theme')) {
  5283. unset($GLOBALS['theme']);
  5284. drupal_maintenance_theme();
  5285. }
  5286. }
  5287. /**
  5288. * Changes the dummy query string added to all CSS and JavaScript files.
  5289. *
  5290. * Changing the dummy query string appended to CSS and JavaScript files forces
  5291. * all browsers to reload fresh files.
  5292. */
  5293. function _drupal_flush_css_js() {
  5294. // The timestamp is converted to base 36 in order to make it more compact.
  5295. variable_set('css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
  5296. }
  5297. /**
  5298. * Outputs debug information.
  5299. *
  5300. * The debug information is passed on to trigger_error() after being converted
  5301. * to a string using _drupal_debug_message().
  5302. *
  5303. * @param $data
  5304. * Data to be output.
  5305. * @param $label
  5306. * Label to prefix the data.
  5307. * @param $print_r
  5308. * Flag to switch between print_r() and var_export() for data conversion to
  5309. * string. Set $print_r to TRUE when dealing with a recursive data structure
  5310. * as var_export() will generate an error.
  5311. */
  5312. function debug($data, $label = NULL, $print_r = FALSE) {
  5313. // Print $data contents to string.
  5314. $string = check_plain($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
  5315. // Display values with pre-formatting to increase readability.
  5316. $string = '<pre>' . $string . '</pre>';
  5317. trigger_error(trim($label ? "$label: $string" : $string));
  5318. }
  5319. /**
  5320. * Checks whether a version is compatible with a given dependency.
  5321. *
  5322. * @param $v
  5323. * A parsed dependency structure e.g. from ModuleHandler::parseDependency().
  5324. * @param $current_version
  5325. * The version to check against (like 4.2).
  5326. *
  5327. * @return
  5328. * NULL if compatible, otherwise the original dependency version string that
  5329. * caused the incompatibility.
  5330. *
  5331. * @see \Drupal\Core\Extension\ModuleHandler::parseDependency()
  5332. */
  5333. function drupal_check_incompatibility($v, $current_version) {
  5334. if (!empty($v['versions'])) {
  5335. foreach ($v['versions'] as $required_version) {
  5336. if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
  5337. return $v['original_version'];
  5338. }
  5339. }
  5340. }
  5341. }
  5342. /**
  5343. * Returns a string of supported archive extensions.
  5344. *
  5345. * @return
  5346. * A space-separated string of extensions suitable for use by the file
  5347. * validation system.
  5348. */
  5349. function archiver_get_extensions() {
  5350. $valid_extensions = array();
  5351. foreach (Drupal::service('plugin.manager.archiver')->getDefinitions() as $archive) {
  5352. foreach ($archive['extensions'] as $extension) {
  5353. foreach (explode('.', $extension) as $part) {
  5354. if (!in_array($part, $valid_extensions)) {
  5355. $valid_extensions[] = $part;
  5356. }
  5357. }
  5358. }
  5359. }
  5360. return implode(' ', $valid_extensions);
  5361. }
  5362. /**
  5363. * Creates the appropriate archiver for the specified file.
  5364. *
  5365. * @param $file
  5366. * The full path of the archive file. Note that stream wrapper paths are
  5367. * supported, but not remote ones.
  5368. *
  5369. * @return
  5370. * A newly created instance of the archiver class appropriate
  5371. * for the specified file, already bound to that file.
  5372. * If no appropriate archiver class was found, will return FALSE.
  5373. */
  5374. function archiver_get_archiver($file) {
  5375. // Archivers can only work on local paths
  5376. $filepath = drupal_realpath($file);
  5377. if (!is_file($filepath)) {
  5378. throw new Exception(t('Archivers can only operate on local files: %file not supported', array('%file' => $file)));
  5379. }
  5380. return Drupal::service('plugin.manager.archiver')->getInstance(array('filepath' => $filepath));
  5381. }
  5382. /**
  5383. * Assembles the Drupal Updater registry.
  5384. *
  5385. * An Updater is a class that knows how to update various parts of the Drupal
  5386. * file system, for example to update modules that have newer releases, or to
  5387. * install a new theme.
  5388. *
  5389. * @return array
  5390. * The Drupal Updater class registry.
  5391. *
  5392. * @see Drupal\Core\Updater\Updater
  5393. * @see hook_updater_info()
  5394. * @see hook_updater_info_alter()
  5395. */
  5396. function drupal_get_updaters() {
  5397. $updaters = &drupal_static(__FUNCTION__);
  5398. if (!isset($updaters)) {
  5399. $updaters = module_invoke_all('updater_info');
  5400. drupal_alter('updater_info', $updaters);
  5401. uasort($updaters, 'drupal_sort_weight');
  5402. }
  5403. return $updaters;
  5404. }
  5405. /**
  5406. * Assembles the Drupal FileTransfer registry.
  5407. *
  5408. * @return
  5409. * The Drupal FileTransfer class registry.
  5410. *
  5411. * @see Drupal\Core\FileTransfer\FileTransfer
  5412. * @see hook_filetransfer_info()
  5413. * @see hook_filetransfer_info_alter()
  5414. */
  5415. function drupal_get_filetransfer_info() {
  5416. $info = &drupal_static(__FUNCTION__);
  5417. if (!isset($info)) {
  5418. $info = module_invoke_all('filetransfer_info');
  5419. drupal_alter('filetransfer_info', $info);
  5420. uasort($info, 'drupal_sort_weight');
  5421. }
  5422. return $info;
  5423. }
  5424. /**
  5425. * @defgroup queue Queue operations
  5426. * @{
  5427. * Queue items to allow later processing.
  5428. *
  5429. * The queue system allows placing items in a queue and processing them later.
  5430. * The system tries to ensure that only one consumer can process an item.
  5431. *
  5432. * Before a queue can be used it needs to be created by
  5433. * Drupal\Core\Queue\QueueInterface::createQueue().
  5434. *
  5435. * Items can be added to the queue by passing an arbitrary data object to
  5436. * Drupal\Core\Queue\QueueInterface::createItem().
  5437. *
  5438. * To process an item, call Drupal\Core\Queue\QueueInterface::claimItem() and
  5439. * specify how long you want to have a lease for working on that item.
  5440. * When finished processing, the item needs to be deleted by calling
  5441. * Drupal\Core\Queue\QueueInterface::deleteItem(). If the consumer dies, the
  5442. * item will be made available again by the Drupal\Core\Queue\QueueInterface
  5443. * implementation once the lease expires. Another consumer will then be able to
  5444. * receive it when calling Drupal\Core\Queue\QueueInterface::claimItem().
  5445. * Due to this, the processing code should be aware that an item might be handed
  5446. * over for processing more than once.
  5447. *
  5448. * The $item object used by the Drupal\Core\Queue\QueueInterface can contain
  5449. * arbitrary metadata depending on the implementation. Systems using the
  5450. * interface should only rely on the data property which will contain the
  5451. * information passed to Drupal\Core\Queue\QueueInterface::createItem().
  5452. * The full queue item returned by Drupal\Core\Queue\QueueInterface::claimItem()
  5453. * needs to be passed to Drupal\Core\Queue\QueueInterface::deleteItem() once
  5454. * processing is completed.
  5455. *
  5456. * There are two kinds of queue backends available: reliable, which preserves
  5457. * the order of messages and guarantees that every item will be executed at
  5458. * least once. The non-reliable kind only does a best effort to preserve order
  5459. * in messages and to execute them at least once but there is a small chance
  5460. * that some items get lost. For example, some distributed back-ends like
  5461. * Amazon SQS will be managing jobs for a large set of producers and consumers
  5462. * where a strict FIFO ordering will likely not be preserved. Another example
  5463. * would be an in-memory queue backend which might lose items if it crashes.
  5464. * However, such a backend would be able to deal with significantly more writes
  5465. * than a reliable queue and for many tasks this is more important. See
  5466. * aggregator_cron() for an example of how to effectively utilize a
  5467. * non-reliable queue. Another example is doing Twitter statistics -- the small
  5468. * possibility of losing a few items is insignificant next to power of the
  5469. * queue being able to keep up with writes. As described in the processing
  5470. * section, regardless of the queue being reliable or not, the processing code
  5471. * should be aware that an item might be handed over for processing more than
  5472. * once (because the processing code might time out before it finishes).
  5473. */
  5474. /**
  5475. * @} End of "defgroup queue".
  5476. */

Functions

Namesort descending Description
archiver_get_archiver Creates the appropriate archiver for the specified file.
archiver_get_extensions Returns a string of supported archive extensions.
base_path Returns the base URL path (i.e., directory) of the Drupal installation.
check_url Strips dangerous protocols from a URI and encodes it for output to HTML.
datetime_default_format_type Retrieves the correct datetime format type for this system.
date_iso8601 Returns an ISO8601 formatted date based on the given date.
debug Outputs debug information.
drupal_add_css Adds a cascading stylesheet to the stylesheet queue.
drupal_add_feed Adds a feed URL for the current page.
drupal_add_html_head Adds output to the HEAD tag of the HTML page.
drupal_add_html_head_link Adds a LINK tag with a distinct 'rel' attribute to the page's HEAD.
drupal_add_js Adds a JavaScript file, setting, or inline code to the page.
drupal_add_library Adds multiple JavaScript or CSS files at the same time.
drupal_add_region_content Adds content to a specified region.
drupal_add_tabledrag Assists in adding the tableDrag JavaScript behavior to a themed table.
drupal_aggregate_css Aggregation callback: Aggregates CSS files and inline content.
drupal_aggregate_js Default callback to aggregate JavaScript files.
drupal_build_css_cache Aggregates and optimizes CSS files into a cache file in the files directory.
drupal_build_js_cache Aggregates JavaScript files into a cache file in the files directory.
drupal_check_incompatibility Checks whether a version is compatible with a given dependency.
drupal_clean_css_identifier Prepares a string for use as a CSS identifier (element, class, or ID name).
drupal_clear_css_cache Deletes old cached CSS files.
drupal_clear_js_cache Deletes old cached JavaScript files and variables.
drupal_cron_run Executes a cron run when called.
drupal_delete_file_if_stale Deletes files modified more than a set time ago.
drupal_encode_path Encodes a Drupal path for use in a URL.
drupal_explode_tags Deprecated Explodes a string of tags into an array.
drupal_flush_all_caches Flushes all persistent caches, resets all variables, and rebuilds all data structures.
drupal_get_breadcrumb Gets the breadcrumb trail for the current page.
drupal_get_css Returns a themed representation of all stylesheets to attach to the page.
drupal_get_destination Prepares a 'destination' URL query parameter for use with drupal_goto().
drupal_get_feeds Gets the feed URLs for the current page.
drupal_get_filetransfer_info Assembles the Drupal FileTransfer registry.
drupal_get_html_head Retrieves output to be displayed in the HEAD tag of the HTML page.
drupal_get_js Returns a themed presentation of all JavaScript code for the current page.
drupal_get_library Retrieves information for a JavaScript/CSS library.
drupal_get_path Returns the path to a system item (module, theme, etc.).
drupal_get_private_key Ensures the private key variable used to generate tokens is set.
drupal_get_profile Gets the name of the currently active installation profile.
drupal_get_query_array Splits a URL-encoded query string into an array.
drupal_get_query_parameters Processes a URL query parameter array to remove unwanted elements.
drupal_get_region_content Gets assigned content for a given region.
drupal_get_token Generates a token based on $value, the user session, and the private key.
drupal_get_updaters Assembles the Drupal Updater registry.
drupal_goto Sends the user to a different Drupal page.
drupal_group_css Grouping callback: Groups CSS items by their types, media, and browsers.
drupal_group_js Default callback to group JavaScript items.
drupal_html_class Prepares a string for use as a valid class name.
drupal_html_id Prepares a string for use as a valid HTML ID and guarantees uniqueness.
drupal_http_build_query Deprecated Parses an array into a valid, rawurlencoded query string.
drupal_http_header_attributes Formats an attribute string for an HTTP header.
drupal_implode_tags Deprecated Implodes an array of tags into a string.
drupal_json_decode Converts an HTML-safe JSON string into its PHP equivalent.
drupal_json_encode Converts a PHP variable into its JavaScript equivalent.
drupal_js_defaults Constructs an array of the defaults that are used for JavaScript items.
drupal_load_stylesheet Loads the stylesheet and resolves all @import commands.
drupal_load_stylesheet_content Processes the contents of a stylesheet for aggregation.
drupal_map_assoc Forms an associative array from a linear array.
drupal_merge_js_settings Merges an array of settings arrays into a single settings array.
drupal_page_set_cache Stores the current page in the cache.
drupal_parse_info_file Parses Drupal module and theme .info.yml files.
drupal_parse_url Parses a system URL string into an associative array suitable for url().
drupal_pre_render_conditional_comments Pre-render callback: Renders #browsers into #prefix and #suffix.
drupal_pre_render_dropbutton Pre-render callback: Attaches the dropbutton library and required markup.
drupal_pre_render_html_tag Pre-render callback: Renders a generic HTML tag with attributes into #markup.
drupal_pre_render_link Pre-render callback: Renders a link into #markup.
drupal_pre_render_links Pre-render callback: Collects child links into a single array.
drupal_pre_render_scripts #pre_render callback to add the elements needed for JavaScript tags to be rendered.
drupal_pre_render_styles Pre-render callback: Adds the elements needed for CSS tags to be rendered.
drupal_process_attached Adds attachments to a render() structure.
drupal_process_states Adds JavaScript to change the state of an element based on another element.
drupal_render Renders HTML given a structured array tree.
drupal_render_cache_by_query Prepares an element for caching based on a query.
drupal_render_cache_get Gets the rendered output of a renderable element from the cache.
drupal_render_cache_set Caches the rendered output of a renderable element.
drupal_render_children Renders children of an element and concatenates them.
drupal_render_cid_create Creates the cache ID for a renderable element.
drupal_render_cid_parts Returns cache ID parts for building a cache ID.
drupal_render_collect_attached Collects #attached for an element and its children into a single array.
drupal_render_page Renders the page, including all theming.
drupal_set_breadcrumb Sets the breadcrumb trail for the current page.
drupal_set_page_content Sets the main page content value for later use.
drupal_set_time_limit Attempts to set the PHP maximum execution time.
drupal_sort_css_js Sorts CSS and JavaScript resources.
drupal_sort_title Sorts a structured array by 'title' key (no # prefix).
drupal_sort_weight Sorts a structured array by the 'weight' element.
drupal_strip_dangerous_protocols Strips dangerous protocols (e.g. 'javascript:') from a URI.
drupal_system_listing This function is kept only for backward compatibility.
drupal_valid_token Validates a token based on $value, the user session, and the private key.
element_child Checks if the key is a child.
element_children Identifies the children of an element array, optionally sorted by weight.
element_get_visible_children Returns the visible children of an element.
element_info Retrieves the default properties for the defined element type.
element_info_property Retrieves a single property for the defined element type.
element_properties Gets properties of a structured array element (keys beginning with '#').
element_property Checks if the key is a property.
element_set_attributes Sets HTML attributes based on element properties.
element_sort Sorts a structured array by '#weight' property.
element_sort_by_title Sorts a structured array by '#title' property.
filter_xss Filters HTML to prevent cross-site-scripting (XSS) vulnerabilities.
filter_xss_admin Applies a very permissive XSS/HTML filter for admin-only use.
filter_xss_bad_protocol Processes an HTML attribute value and strips dangerous protocols from URLs.
format_date Formats a date, using a date type or a custom date format string.
format_interval Formats a time interval with the requested granularity.
format_plural Formats a string containing a count of items.
format_rss_channel Formats an RSS channel.
format_rss_item Formats a single RSS item.
format_size Generates a string representation for the given byte count.
format_xml_elements Formats XML elements.
hide Hides an element from later rendering.
l Formats an internal or external URL link as an HTML anchor tag.
parse_size Parses a given byte count.
render Renders an element.
show Shows a hidden element for later rendering.
url Generates an internal or external URL.
url_is_external Returns TRUE if a path is external to Drupal (e.g. http://example.com).
valid_email_address Verifies the syntax of the given e-mail address.
valid_number_step Verifies that a number is a multiple of a given step.
valid_url Deprecated Verifies the syntax of the given URL.
watchdog_severity_levels Returns a list of severity levels, as defined in RFC 3164.
_drupal_bootstrap_code Loads code for subsystems and modules, and registers stream wrappers.
_drupal_bootstrap_full Temporary BC function for scripts not using DrupalKernel.
_drupal_build_css_path Prefixes all paths within a CSS file for drupal_build_css_cache().
_drupal_default_html_head Returns elements that are always displayed in the HEAD tag of the HTML page.
_drupal_flush_css_js Changes the dummy query string added to all CSS and JavaScript files.
_drupal_http_use_proxy Helper function for determining hosts excluded from needing a proxy.
_drupal_load_stylesheet Loads stylesheets recursively and returns contents with corrected paths.
_external_url_is_local Determines if an external URL points to this Drupal installation.
_format_date_callback Translates a formatted date string.

Constants

Namesort descending Description
CSS_AGGREGATE_DEFAULT The default aggregation group for CSS files added to the page.
CSS_AGGREGATE_THEME The default aggregation group for theme CSS files added to the page.
CSS_BASE The default weight for CSS rules that style HTML elements ("base" styles).
CSS_COMPONENT The default weight for CSS rules that style design components (and their associated states and skins.)
CSS_LAYOUT The default weight for CSS rules that layout a page.
CSS_SKIN The default weight for CSS rules that style skins and are not included with components.
CSS_STATE The default weight for CSS rules that style states and are not included with components.
DRUPAL_CACHE_CUSTOM The block is handling its own caching in its hook_block_view().
DRUPAL_CACHE_GLOBAL The block or element is the same for every user and page that it is visible.
DRUPAL_CACHE_PER_PAGE The block or element can change depending on the page being viewed.
DRUPAL_CACHE_PER_ROLE The block or element can change depending on the user's roles.
DRUPAL_CACHE_PER_USER The block or element can change depending on the user.
DRUPAL_NO_CACHE The block should not get cached.
JS_DEFAULT The default group for module JavaScript code added to the page.
JS_LIBRARY The default group for JavaScript and jQuery libraries added to the page.
JS_SETTING The default group for JavaScript settings added to the page.
JS_THEME The default group for theme JavaScript code added to the page.
LOCALE_PLURAL_DELIMITER The delimiter used to split plural strings.
SAVED_DELETED Return status for saving which deleted an existing item.
SAVED_NEW Return status for saving which involved creating a new item.
SAVED_UPDATED Return status for saving which involved an update to an existing item.