PageRenderTime 41ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/includes/common.inc

https://bitbucket.org/hjain/trinet
PHP | 7966 lines | 3275 code | 529 blank | 4162 comment | 622 complexity | e56cf64dca7391404a7e2f2571bd6d2d MD5 | raw file
Possible License(s): GPL-2.0, LGPL-3.0, AGPL-1.0
  1. <?php
  2. /**
  3. * @file
  4. * Common functions that many Drupal modules will need to reference.
  5. *
  6. * The functions that are critical and need to be available even when serving
  7. * a cached page are instead located in bootstrap.inc.
  8. */
  9. /**
  10. * @defgroup php_wrappers PHP wrapper functions
  11. * @{
  12. * Functions that are wrappers or custom implementations of PHP functions.
  13. *
  14. * Certain PHP functions should not be used in Drupal. Instead, Drupal's
  15. * replacement functions should be used.
  16. *
  17. * For example, for improved or more secure UTF8-handling, or RFC-compliant
  18. * handling of URLs in Drupal.
  19. *
  20. * For ease of use and memorizing, all these wrapper functions use the same name
  21. * as the original PHP function, but prefixed with "drupal_". Beware, however,
  22. * that not all wrapper functions support the same arguments as the original
  23. * functions.
  24. *
  25. * You should always use these wrapper functions in your code.
  26. *
  27. * Wrong:
  28. * @code
  29. * $my_substring = substr($original_string, 0, 5);
  30. * @endcode
  31. *
  32. * Correct:
  33. * @code
  34. * $my_substring = drupal_substr($original_string, 0, 5);
  35. * @endcode
  36. *
  37. * @}
  38. */
  39. /**
  40. * Return status for saving which involved creating a new item.
  41. */
  42. define('SAVED_NEW', 1);
  43. /**
  44. * Return status for saving which involved an update to an existing item.
  45. */
  46. define('SAVED_UPDATED', 2);
  47. /**
  48. * Return status for saving which deleted an existing item.
  49. */
  50. define('SAVED_DELETED', 3);
  51. /**
  52. * The default group for system CSS files added to the page.
  53. */
  54. define('CSS_SYSTEM', -100);
  55. /**
  56. * The default group for module CSS files added to the page.
  57. */
  58. define('CSS_DEFAULT', 0);
  59. /**
  60. * The default group for theme CSS files added to the page.
  61. */
  62. define('CSS_THEME', 100);
  63. /**
  64. * The default group for JavaScript and jQuery libraries added to the page.
  65. */
  66. define('JS_LIBRARY', -100);
  67. /**
  68. * The default group for module JavaScript code added to the page.
  69. */
  70. define('JS_DEFAULT', 0);
  71. /**
  72. * The default group for theme JavaScript code added to the page.
  73. */
  74. define('JS_THEME', 100);
  75. /**
  76. * Error code indicating that the request exceeded the specified timeout.
  77. *
  78. * @see drupal_http_request()
  79. */
  80. define('HTTP_REQUEST_TIMEOUT', -1);
  81. /**
  82. * Constants defining cache granularity for blocks and renderable arrays.
  83. *
  84. * Modules specify the caching patterns for their blocks using binary
  85. * combinations of these constants in their hook_block_info():
  86. * $block[delta]['cache'] = DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE;
  87. * DRUPAL_CACHE_PER_ROLE is used as a default when no caching pattern is
  88. * specified. Use DRUPAL_CACHE_CUSTOM to disable standard block cache and
  89. * implement
  90. *
  91. * The block cache is cleared in cache_clear_all(), and uses the same clearing
  92. * policy than page cache (node, comment, user, taxonomy added or updated...).
  93. * Blocks requiring more fine-grained clearing might consider disabling the
  94. * built-in block cache (DRUPAL_NO_CACHE) and roll their own.
  95. *
  96. * Note that user 1 is excluded from block caching.
  97. */
  98. /**
  99. * The block should not get cached.
  100. *
  101. * This setting should be used:
  102. * - For simple blocks (notably those that do not perform any db query), where
  103. * querying the db cache would be more expensive than directly generating the
  104. * content.
  105. * - For blocks that change too frequently.
  106. */
  107. define('DRUPAL_NO_CACHE', -1);
  108. /**
  109. * The block is handling its own caching in its hook_block_view().
  110. *
  111. * From the perspective of the block cache system, this is equivalent to
  112. * DRUPAL_NO_CACHE. Useful when time based expiration is needed or a site uses
  113. * a node access which invalidates standard block cache.
  114. */
  115. define('DRUPAL_CACHE_CUSTOM', -2);
  116. /**
  117. * The block or element can change depending on the user's roles.
  118. *
  119. * This is the default setting for blocks, used when the block does not specify
  120. * anything.
  121. */
  122. define('DRUPAL_CACHE_PER_ROLE', 0x0001);
  123. /**
  124. * The block or element can change depending on the user.
  125. *
  126. * This setting can be resource-consuming for sites with large number of users,
  127. * and thus should only be used when DRUPAL_CACHE_PER_ROLE is not sufficient.
  128. */
  129. define('DRUPAL_CACHE_PER_USER', 0x0002);
  130. /**
  131. * The block or element can change depending on the page being viewed.
  132. */
  133. define('DRUPAL_CACHE_PER_PAGE', 0x0004);
  134. /**
  135. * The block or element is the same for every user and page that it is visible.
  136. */
  137. define('DRUPAL_CACHE_GLOBAL', 0x0008);
  138. /**
  139. * Adds content to a specified region.
  140. *
  141. * @param $region
  142. * Page region the content is added to.
  143. * @param $data
  144. * Content to be added.
  145. */
  146. function drupal_add_region_content($region = NULL, $data = NULL) {
  147. static $content = array();
  148. if (isset($region) && isset($data)) {
  149. $content[$region][] = $data;
  150. }
  151. return $content;
  152. }
  153. /**
  154. * Gets assigned content for a given region.
  155. *
  156. * @param $region
  157. * A specified region to fetch content for. If NULL, all regions will be
  158. * returned.
  159. * @param $delimiter
  160. * Content to be inserted between imploded array elements.
  161. */
  162. function drupal_get_region_content($region = NULL, $delimiter = ' ') {
  163. $content = drupal_add_region_content();
  164. if (isset($region)) {
  165. if (isset($content[$region]) && is_array($content[$region])) {
  166. return implode($delimiter, $content[$region]);
  167. }
  168. }
  169. else {
  170. foreach (array_keys($content) as $region) {
  171. if (is_array($content[$region])) {
  172. $content[$region] = implode($delimiter, $content[$region]);
  173. }
  174. }
  175. return $content;
  176. }
  177. }
  178. /**
  179. * Gets the name of the currently active install profile.
  180. *
  181. * When this function is called during Drupal's initial installation process,
  182. * the name of the profile that's about to be installed is stored in the global
  183. * installation state. At all other times, the standard Drupal systems variable
  184. * table contains the name of the current profile, and we can call
  185. * variable_get() to determine what one is active.
  186. *
  187. * @return $profile
  188. * The name of the install profile.
  189. */
  190. function drupal_get_profile() {
  191. global $install_state;
  192. if (isset($install_state['parameters']['profile'])) {
  193. $profile = $install_state['parameters']['profile'];
  194. }
  195. else {
  196. $profile = variable_get('install_profile', 'standard');
  197. }
  198. return $profile;
  199. }
  200. /**
  201. * Sets the breadcrumb trail for the current page.
  202. *
  203. * @param $breadcrumb
  204. * Array of links, starting with "home" and proceeding up to but not including
  205. * the current page.
  206. */
  207. function drupal_set_breadcrumb($breadcrumb = NULL) {
  208. $stored_breadcrumb = &drupal_static(__FUNCTION__);
  209. if (isset($breadcrumb)) {
  210. $stored_breadcrumb = $breadcrumb;
  211. }
  212. return $stored_breadcrumb;
  213. }
  214. /**
  215. * Gets the breadcrumb trail for the current page.
  216. */
  217. function drupal_get_breadcrumb() {
  218. $breadcrumb = drupal_set_breadcrumb();
  219. if (!isset($breadcrumb)) {
  220. $breadcrumb = menu_get_active_breadcrumb();
  221. }
  222. return $breadcrumb;
  223. }
  224. /**
  225. * Returns a string containing RDF namespace declarations for use in XML and
  226. * XHTML output.
  227. */
  228. function drupal_get_rdf_namespaces() {
  229. $xml_rdf_namespaces = array();
  230. // Serializes the RDF namespaces in XML namespace syntax.
  231. if (function_exists('rdf_get_namespaces')) {
  232. foreach (rdf_get_namespaces() as $prefix => $uri) {
  233. $xml_rdf_namespaces[] = 'xmlns:' . $prefix . '="' . $uri . '"';
  234. }
  235. }
  236. return count($xml_rdf_namespaces) ? "\n " . implode("\n ", $xml_rdf_namespaces) : '';
  237. }
  238. /**
  239. * Adds output to the HEAD tag of the HTML page.
  240. *
  241. * This function can be called as long the headers aren't sent. Pass no
  242. * arguments (or NULL for both) to retrieve the currently stored elements.
  243. *
  244. * @param $data
  245. * A renderable array. If the '#type' key is not set then 'html_tag' will be
  246. * added as the default '#type'.
  247. * @param $key
  248. * A unique string key to allow implementations of hook_html_head_alter() to
  249. * identify the element in $data. Required if $data is not NULL.
  250. *
  251. * @return
  252. * An array of all stored HEAD elements.
  253. *
  254. * @see theme_html_tag()
  255. */
  256. function drupal_add_html_head($data = NULL, $key = NULL) {
  257. $stored_head = &drupal_static(__FUNCTION__);
  258. if (!isset($stored_head)) {
  259. // Make sure the defaults, including Content-Type, come first.
  260. $stored_head = _drupal_default_html_head();
  261. }
  262. if (isset($data) && isset($key)) {
  263. if (!isset($data['#type'])) {
  264. $data['#type'] = 'html_tag';
  265. }
  266. $stored_head[$key] = $data;
  267. }
  268. return $stored_head;
  269. }
  270. /**
  271. * Returns elements that are always displayed in the HEAD tag of the HTML page.
  272. */
  273. function _drupal_default_html_head() {
  274. // Add default elements. Make sure the Content-Type comes first because the
  275. // IE browser may be vulnerable to XSS via encoding attacks from any content
  276. // that comes before this META tag, such as a TITLE tag.
  277. $elements['system_meta_content_type'] = array(
  278. '#type' => 'html_tag',
  279. '#tag' => 'meta',
  280. '#attributes' => array(
  281. 'http-equiv' => 'Content-Type',
  282. 'content' => 'text/html; charset=utf-8',
  283. ),
  284. // Security: This always has to be output first.
  285. '#weight' => -1000,
  286. );
  287. // Show Drupal and the major version number in the META GENERATOR tag.
  288. // Get the major version.
  289. list($version, ) = explode('.', VERSION);
  290. $elements['system_meta_generator'] = array(
  291. '#type' => 'html_tag',
  292. '#tag' => 'meta',
  293. '#attributes' => array(
  294. 'name' => 'Generator',
  295. 'content' => 'Drupal ' . $version . ' (http://drupal.org)',
  296. ),
  297. );
  298. // Also send the generator in the HTTP header.
  299. $elements['system_meta_generator']['#attached']['drupal_add_http_header'][] = array('X-Generator', $elements['system_meta_generator']['#attributes']['content']);
  300. return $elements;
  301. }
  302. /**
  303. * Retrieves output to be displayed in the HEAD tag of the HTML page.
  304. */
  305. function drupal_get_html_head() {
  306. $elements = drupal_add_html_head();
  307. drupal_alter('html_head', $elements);
  308. return drupal_render($elements);
  309. }
  310. /**
  311. * Adds a feed URL for the current page.
  312. *
  313. * This function can be called as long the HTML header hasn't been sent.
  314. *
  315. * @param $url
  316. * An internal system path or a fully qualified external URL of the feed.
  317. * @param $title
  318. * The title of the feed.
  319. */
  320. function drupal_add_feed($url = NULL, $title = '') {
  321. $stored_feed_links = &drupal_static(__FUNCTION__, array());
  322. if (isset($url)) {
  323. $stored_feed_links[$url] = theme('feed_icon', array('url' => $url, 'title' => $title));
  324. drupal_add_html_head_link(array(
  325. 'rel' => 'alternate',
  326. 'type' => 'application/rss+xml',
  327. 'title' => $title,
  328. // Force the URL to be absolute, for consistency with other <link> tags
  329. // output by Drupal.
  330. 'href' => url($url, array('absolute' => TRUE)),
  331. ));
  332. }
  333. return $stored_feed_links;
  334. }
  335. /**
  336. * Gets the feed URLs for the current page.
  337. *
  338. * @param $delimiter
  339. * A delimiter to split feeds by.
  340. */
  341. function drupal_get_feeds($delimiter = "\n") {
  342. $feeds = drupal_add_feed();
  343. return implode($feeds, $delimiter);
  344. }
  345. /**
  346. * @defgroup http_handling HTTP handling
  347. * @{
  348. * Functions to properly handle HTTP responses.
  349. */
  350. /**
  351. * Processes a URL query parameter array to remove unwanted elements.
  352. *
  353. * @param $query
  354. * (optional) An array to be processed. Defaults to $_GET.
  355. * @param $exclude
  356. * (optional) A list of $query array keys to remove. Use "parent[child]" to
  357. * exclude nested items. Defaults to array('q').
  358. * @param $parent
  359. * Internal use only. Used to build the $query array key for nested items.
  360. *
  361. * @return
  362. * An array containing query parameters, which can be used for url().
  363. */
  364. function drupal_get_query_parameters(array $query = NULL, array $exclude = array('q'), $parent = '') {
  365. // Set defaults, if none given.
  366. if (!isset($query)) {
  367. $query = $_GET;
  368. }
  369. // If $exclude is empty, there is nothing to filter.
  370. if (empty($exclude)) {
  371. return $query;
  372. }
  373. elseif (!$parent) {
  374. $exclude = array_flip($exclude);
  375. }
  376. $params = array();
  377. foreach ($query as $key => $value) {
  378. $string_key = ($parent ? $parent . '[' . $key . ']' : $key);
  379. if (isset($exclude[$string_key])) {
  380. continue;
  381. }
  382. if (is_array($value)) {
  383. $params[$key] = drupal_get_query_parameters($value, $exclude, $string_key);
  384. }
  385. else {
  386. $params[$key] = $value;
  387. }
  388. }
  389. return $params;
  390. }
  391. /**
  392. * Splits a URL-encoded query string into an array.
  393. *
  394. * @param $query
  395. * The query string to split.
  396. *
  397. * @return
  398. * An array of url decoded couples $param_name => $value.
  399. */
  400. function drupal_get_query_array($query) {
  401. $result = array();
  402. if (!empty($query)) {
  403. foreach (explode('&', $query) as $param) {
  404. $param = explode('=', $param);
  405. $result[$param[0]] = isset($param[1]) ? rawurldecode($param[1]) : '';
  406. }
  407. }
  408. return $result;
  409. }
  410. /**
  411. * Parses an array into a valid, rawurlencoded query string.
  412. *
  413. * This differs from http_build_query() as we need to rawurlencode() (instead of
  414. * urlencode()) all query parameters.
  415. *
  416. * @param $query
  417. * The query parameter array to be processed, e.g. $_GET.
  418. * @param $parent
  419. * Internal use only. Used to build the $query array key for nested items.
  420. *
  421. * @return
  422. * A rawurlencoded string which can be used as or appended to the URL query
  423. * string.
  424. *
  425. * @see drupal_get_query_parameters()
  426. * @ingroup php_wrappers
  427. */
  428. function drupal_http_build_query(array $query, $parent = '') {
  429. $params = array();
  430. foreach ($query as $key => $value) {
  431. $key = ($parent ? $parent . '[' . rawurlencode($key) . ']' : rawurlencode($key));
  432. // Recurse into children.
  433. if (is_array($value)) {
  434. $params[] = drupal_http_build_query($value, $key);
  435. }
  436. // If a query parameter value is NULL, only append its key.
  437. elseif (!isset($value)) {
  438. $params[] = $key;
  439. }
  440. else {
  441. // For better readability of paths in query strings, we decode slashes.
  442. $params[] = $key . '=' . str_replace('%2F', '/', rawurlencode($value));
  443. }
  444. }
  445. return implode('&', $params);
  446. }
  447. /**
  448. * Prepares a 'destination' URL query parameter for use with drupal_goto().
  449. *
  450. * Used to direct the user back to the referring page after completing a form.
  451. * By default the current URL is returned. If a destination exists in the
  452. * previous request, that destination is returned. As such, a destination can
  453. * persist across multiple pages.
  454. *
  455. * @see drupal_goto()
  456. */
  457. function drupal_get_destination() {
  458. $destination = &drupal_static(__FUNCTION__);
  459. if (isset($destination)) {
  460. return $destination;
  461. }
  462. if (isset($_GET['destination'])) {
  463. $destination = array('destination' => $_GET['destination']);
  464. }
  465. else {
  466. $path = $_GET['q'];
  467. $query = drupal_http_build_query(drupal_get_query_parameters());
  468. if ($query != '') {
  469. $path .= '?' . $query;
  470. }
  471. $destination = array('destination' => $path);
  472. }
  473. return $destination;
  474. }
  475. /**
  476. * Parses a system URL string into an associative array suitable for url().
  477. *
  478. * This function should only be used for URLs that have been generated by the
  479. * system, resp. url(). It should not be used for URLs that come from external
  480. * sources, or URLs that link to external resources.
  481. *
  482. * The returned array contains a 'path' that may be passed separately to url().
  483. * For example:
  484. * @code
  485. * $options = drupal_parse_url($_GET['destination']);
  486. * $my_url = url($options['path'], $options);
  487. * $my_link = l('Example link', $options['path'], $options);
  488. * @endcode
  489. *
  490. * This is required, because url() does not support relative URLs containing a
  491. * query string or fragment in its $path argument. Instead, any query string
  492. * needs to be parsed into an associative query parameter array in
  493. * $options['query'] and the fragment into $options['fragment'].
  494. *
  495. * @param $url
  496. * The URL string to parse, f.e. $_GET['destination'].
  497. *
  498. * @return
  499. * An associative array containing the keys:
  500. * - 'path': The path of the URL. If the given $url is external, this includes
  501. * the scheme and host.
  502. * - 'query': An array of query parameters of $url, if existent.
  503. * - 'fragment': The fragment of $url, if existent.
  504. *
  505. * @see url()
  506. * @see drupal_goto()
  507. * @ingroup php_wrappers
  508. */
  509. function drupal_parse_url($url) {
  510. $options = array(
  511. 'path' => NULL,
  512. 'query' => array(),
  513. 'fragment' => '',
  514. );
  515. // External URLs: not using parse_url() here, so we do not have to rebuild
  516. // the scheme, host, and path without having any use for it.
  517. if (strpos($url, '://') !== FALSE) {
  518. // Split off everything before the query string into 'path'.
  519. $parts = explode('?', $url);
  520. $options['path'] = $parts[0];
  521. // If there is a query string, transform it into keyed query parameters.
  522. if (isset($parts[1])) {
  523. $query_parts = explode('#', $parts[1]);
  524. parse_str($query_parts[0], $options['query']);
  525. // Take over the fragment, if there is any.
  526. if (isset($query_parts[1])) {
  527. $options['fragment'] = $query_parts[1];
  528. }
  529. }
  530. }
  531. // Internal URLs.
  532. else {
  533. // parse_url() does not support relative URLs, so make it absolute. E.g. the
  534. // relative URL "foo/bar:1" isn't properly parsed.
  535. $parts = parse_url('http://example.com/' . $url);
  536. // Strip the leading slash that was just added.
  537. $options['path'] = substr($parts['path'], 1);
  538. if (isset($parts['query'])) {
  539. parse_str($parts['query'], $options['query']);
  540. }
  541. if (isset($parts['fragment'])) {
  542. $options['fragment'] = $parts['fragment'];
  543. }
  544. }
  545. // The 'q' parameter contains the path of the current page if clean URLs are
  546. // disabled. It overrides the 'path' of the URL when present, even if clean
  547. // URLs are enabled, due to how Apache rewriting rules work.
  548. if (isset($options['query']['q'])) {
  549. $options['path'] = $options['query']['q'];
  550. unset($options['query']['q']);
  551. }
  552. return $options;
  553. }
  554. /**
  555. * Encodes a Drupal path for use in a URL.
  556. *
  557. * For aesthetic reasons slashes are not escaped.
  558. *
  559. * Note that url() takes care of calling this function, so a path passed to that
  560. * function should not be encoded in advance.
  561. *
  562. * @param $path
  563. * The Drupal path to encode.
  564. */
  565. function drupal_encode_path($path) {
  566. return str_replace('%2F', '/', rawurlencode($path));
  567. }
  568. /**
  569. * Sends the user to a different Drupal page.
  570. *
  571. * This issues an on-site HTTP redirect. The function makes sure the redirected
  572. * URL is formatted correctly.
  573. *
  574. * Usually the redirected URL is constructed from this function's input
  575. * parameters. However you may override that behavior by setting a
  576. * destination in either the $_REQUEST-array (i.e. by using
  577. * the query string of an URI) This is used to direct the user back to
  578. * the proper page after completing a form. For example, after editing
  579. * a post on the 'admin/content'-page or after having logged on using the
  580. * 'user login'-block in a sidebar. The function drupal_get_destination()
  581. * can be used to help set the destination URL.
  582. *
  583. * Drupal will ensure that messages set by drupal_set_message() and other
  584. * session data are written to the database before the user is redirected.
  585. *
  586. * This function ends the request; use it instead of a return in your menu
  587. * callback.
  588. *
  589. * @param $path
  590. * A Drupal path or a full URL.
  591. * @param $options
  592. * An associative array of additional URL options to pass to url().
  593. * @param $http_response_code
  594. * Valid values for an actual "goto" as per RFC 2616 section 10.3 are:
  595. * - 301 Moved Permanently (the recommended value for most redirects)
  596. * - 302 Found (default in Drupal and PHP, sometimes used for spamming search
  597. * engines)
  598. * - 303 See Other
  599. * - 304 Not Modified
  600. * - 305 Use Proxy
  601. * - 307 Temporary Redirect (alternative to "503 Site Down for Maintenance")
  602. * Note: Other values are defined by RFC 2616, but are rarely used and poorly
  603. * supported.
  604. *
  605. * @see drupal_get_destination()
  606. * @see url()
  607. */
  608. function drupal_goto($path = '', array $options = array(), $http_response_code = 302) {
  609. // A destination in $_GET always overrides the function arguments.
  610. // We do not allow absolute URLs to be passed via $_GET, as this can be an attack vector.
  611. if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
  612. $destination = drupal_parse_url($_GET['destination']);
  613. $path = $destination['path'];
  614. $options['query'] = $destination['query'];
  615. $options['fragment'] = $destination['fragment'];
  616. }
  617. drupal_alter('drupal_goto', $path, $options, $http_response_code);
  618. // The 'Location' HTTP header must be absolute.
  619. $options['absolute'] = TRUE;
  620. $url = url($path, $options);
  621. header('Location: ' . $url, TRUE, $http_response_code);
  622. // The "Location" header sends a redirect status code to the HTTP daemon. In
  623. // some cases this can be wrong, so we make sure none of the code below the
  624. // drupal_goto() call gets executed upon redirection.
  625. drupal_exit($url);
  626. }
  627. /**
  628. * Delivers a "site is under maintenance" message to the browser.
  629. *
  630. * Page callback functions wanting to report a "site offline" message should
  631. * return MENU_SITE_OFFLINE instead of calling drupal_site_offline(). However,
  632. * functions that are invoked in contexts where that return value might not
  633. * bubble up to menu_execute_active_handler() should call drupal_site_offline().
  634. */
  635. function drupal_site_offline() {
  636. drupal_deliver_page(MENU_SITE_OFFLINE);
  637. }
  638. /**
  639. * Delivers a "page not found" error to the browser.
  640. *
  641. * Page callback functions wanting to report a "page not found" message should
  642. * return MENU_NOT_FOUND instead of calling drupal_not_found(). However,
  643. * functions that are invoked in contexts where that return value might not
  644. * bubble up to menu_execute_active_handler() should call drupal_not_found().
  645. */
  646. function drupal_not_found() {
  647. drupal_deliver_page(MENU_NOT_FOUND);
  648. }
  649. /**
  650. * Delivers an "access denied" error to the browser.
  651. *
  652. * Page callback functions wanting to report an "access denied" message should
  653. * return MENU_ACCESS_DENIED instead of calling drupal_access_denied(). However,
  654. * functions that are invoked in contexts where that return value might not
  655. * bubble up to menu_execute_active_handler() should call
  656. * drupal_access_denied().
  657. */
  658. function drupal_access_denied() {
  659. drupal_deliver_page(MENU_ACCESS_DENIED);
  660. }
  661. /**
  662. * Performs an HTTP request.
  663. *
  664. * This is a flexible and powerful HTTP client implementation. Correctly
  665. * handles GET, POST, PUT or any other HTTP requests. Handles redirects.
  666. *
  667. * @param $url
  668. * A string containing a fully qualified URI.
  669. * @param array $options
  670. * (optional) An array that can have one or more of the following elements:
  671. * - headers: An array containing request headers to send as name/value pairs.
  672. * - method: A string containing the request method. Defaults to 'GET'.
  673. * - data: A string containing the request body, formatted as
  674. * 'param=value&param=value&...'. Defaults to NULL.
  675. * - max_redirects: An integer representing how many times a redirect
  676. * may be followed. Defaults to 3.
  677. * - timeout: A float representing the maximum number of seconds the function
  678. * call may take. The default is 30 seconds. If a timeout occurs, the error
  679. * code is set to the HTTP_REQUEST_TIMEOUT constant.
  680. * - context: A context resource created with stream_context_create().
  681. *
  682. * @return object
  683. * An object that can have one or more of the following components:
  684. * - request: A string containing the request body that was sent.
  685. * - code: An integer containing the response status code, or the error code
  686. * if an error occurred.
  687. * - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
  688. * - status_message: The status message from the response, if a response was
  689. * received.
  690. * - redirect_code: If redirected, an integer containing the initial response
  691. * status code.
  692. * - redirect_url: If redirected, a string containing the URL of the redirect
  693. * target.
  694. * - error: If an error occurred, the error message. Otherwise not set.
  695. * - headers: An array containing the response headers as name/value pairs.
  696. * HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
  697. * easy access the array keys are returned in lower case.
  698. * - data: A string containing the response body that was received.
  699. */
  700. function drupal_http_request($url, array $options = array()) {
  701. $result = new stdClass();
  702. // Parse the URL and make sure we can handle the schema.
  703. $uri = @parse_url($url);
  704. if ($uri == FALSE) {
  705. $result->error = 'unable to parse URL';
  706. $result->code = -1001;
  707. return $result;
  708. }
  709. if (!isset($uri['scheme'])) {
  710. $result->error = 'missing schema';
  711. $result->code = -1002;
  712. return $result;
  713. }
  714. timer_start(__FUNCTION__);
  715. // Merge the default options.
  716. $options += array(
  717. 'headers' => array(),
  718. 'method' => 'GET',
  719. 'data' => NULL,
  720. 'max_redirects' => 3,
  721. 'timeout' => 30.0,
  722. 'context' => NULL,
  723. );
  724. // stream_socket_client() requires timeout to be a float.
  725. $options['timeout'] = (float) $options['timeout'];
  726. switch ($uri['scheme']) {
  727. case 'http':
  728. case 'feed':
  729. $port = isset($uri['port']) ? $uri['port'] : 80;
  730. $socket = 'tcp://' . $uri['host'] . ':' . $port;
  731. // RFC 2616: "non-standard ports MUST, default ports MAY be included".
  732. // We don't add the standard port to prevent from breaking rewrite rules
  733. // checking the host that do not take into account the port number.
  734. $options['headers']['Host'] = $uri['host'] . ($port != 80 ? ':' . $port : '');
  735. break;
  736. case 'https':
  737. // Note: Only works when PHP is compiled with OpenSSL support.
  738. $port = isset($uri['port']) ? $uri['port'] : 443;
  739. $socket = 'ssl://' . $uri['host'] . ':' . $port;
  740. $options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
  741. break;
  742. default:
  743. $result->error = 'invalid schema ' . $uri['scheme'];
  744. $result->code = -1003;
  745. return $result;
  746. }
  747. if (empty($options['context'])) {
  748. $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout']);
  749. }
  750. else {
  751. // Create a stream with context. Allows verification of a SSL certificate.
  752. $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
  753. }
  754. // Make sure the socket opened properly.
  755. if (!$fp) {
  756. // When a network error occurs, we use a negative number so it does not
  757. // clash with the HTTP status codes.
  758. $result->code = -$errno;
  759. $result->error = trim($errstr) ? trim($errstr) : t('Error opening socket @socket', array('@socket' => $socket));
  760. // Mark that this request failed. This will trigger a check of the web
  761. // server's ability to make outgoing HTTP requests the next time that
  762. // requirements checking is performed.
  763. // See system_requirements().
  764. variable_set('drupal_http_request_fails', TRUE);
  765. return $result;
  766. }
  767. // Construct the path to act on.
  768. $path = isset($uri['path']) ? $uri['path'] : '/';
  769. if (isset($uri['query'])) {
  770. $path .= '?' . $uri['query'];
  771. }
  772. // Merge the default headers.
  773. $options['headers'] += array(
  774. 'User-Agent' => 'Drupal (+http://drupal.org/)',
  775. );
  776. // Only add Content-Length if we actually have any content or if it is a POST
  777. // or PUT request. Some non-standard servers get confused by Content-Length in
  778. // at least HEAD/GET requests, and Squid always requires Content-Length in
  779. // POST/PUT requests.
  780. $content_length = strlen($options['data']);
  781. if ($content_length > 0 || $options['method'] == 'POST' || $options['method'] == 'PUT') {
  782. $options['headers']['Content-Length'] = $content_length;
  783. }
  784. // If the server URL has a user then attempt to use basic authentication.
  785. if (isset($uri['user'])) {
  786. $options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ''));
  787. }
  788. // If the database prefix is being used by SimpleTest to run the tests in a copied
  789. // database then set the user-agent header to the database prefix so that any
  790. // calls to other Drupal pages will run the SimpleTest prefixed database. The
  791. // user-agent is used to ensure that multiple testing sessions running at the
  792. // same time won't interfere with each other as they would if the database
  793. // prefix were stored statically in a file or database variable.
  794. $test_info = &$GLOBALS['drupal_test_info'];
  795. if (!empty($test_info['test_run_id'])) {
  796. $options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
  797. }
  798. $request = $options['method'] . ' ' . $path . " HTTP/1.0\r\n";
  799. foreach ($options['headers'] as $name => $value) {
  800. $request .= $name . ': ' . trim($value) . "\r\n";
  801. }
  802. $request .= "\r\n" . $options['data'];
  803. $result->request = $request;
  804. // Calculate how much time is left of the original timeout value.
  805. $timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
  806. if ($timeout > 0) {
  807. stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
  808. fwrite($fp, $request);
  809. }
  810. // Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
  811. // and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
  812. // instead must invoke stream_get_meta_data() each iteration.
  813. $info = stream_get_meta_data($fp);
  814. $alive = !$info['eof'] && !$info['timed_out'];
  815. $response = '';
  816. while ($alive) {
  817. // Calculate how much time is left of the original timeout value.
  818. $timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
  819. if ($timeout <= 0) {
  820. $info['timed_out'] = TRUE;
  821. break;
  822. }
  823. stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
  824. $chunk = fread($fp, 1024);
  825. $response .= $chunk;
  826. $info = stream_get_meta_data($fp);
  827. $alive = !$info['eof'] && !$info['timed_out'] && $chunk;
  828. }
  829. fclose($fp);
  830. if ($info['timed_out']) {
  831. $result->code = HTTP_REQUEST_TIMEOUT;
  832. $result->error = 'request timed out';
  833. return $result;
  834. }
  835. // Parse response headers from the response body.
  836. // Be tolerant of malformed HTTP responses that separate header and body with
  837. // \n\n or \r\r instead of \r\n\r\n.
  838. list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
  839. $response = preg_split("/\r\n|\n|\r/", $response);
  840. // Parse the response status line.
  841. list($protocol, $code, $status_message) = explode(' ', trim(array_shift($response)), 3);
  842. $result->protocol = $protocol;
  843. $result->status_message = $status_message;
  844. $result->headers = array();
  845. // Parse the response headers.
  846. while ($line = trim(array_shift($response))) {
  847. list($name, $value) = explode(':', $line, 2);
  848. $name = strtolower($name);
  849. if (isset($result->headers[$name]) && $name == 'set-cookie') {
  850. // RFC 2109: the Set-Cookie response header comprises the token Set-
  851. // Cookie:, followed by a comma-separated list of one or more cookies.
  852. $result->headers[$name] .= ',' . trim($value);
  853. }
  854. else {
  855. $result->headers[$name] = trim($value);
  856. }
  857. }
  858. $responses = array(
  859. 100 => 'Continue',
  860. 101 => 'Switching Protocols',
  861. 200 => 'OK',
  862. 201 => 'Created',
  863. 202 => 'Accepted',
  864. 203 => 'Non-Authoritative Information',
  865. 204 => 'No Content',
  866. 205 => 'Reset Content',
  867. 206 => 'Partial Content',
  868. 300 => 'Multiple Choices',
  869. 301 => 'Moved Permanently',
  870. 302 => 'Found',
  871. 303 => 'See Other',
  872. 304 => 'Not Modified',
  873. 305 => 'Use Proxy',
  874. 307 => 'Temporary Redirect',
  875. 400 => 'Bad Request',
  876. 401 => 'Unauthorized',
  877. 402 => 'Payment Required',
  878. 403 => 'Forbidden',
  879. 404 => 'Not Found',
  880. 405 => 'Method Not Allowed',
  881. 406 => 'Not Acceptable',
  882. 407 => 'Proxy Authentication Required',
  883. 408 => 'Request Time-out',
  884. 409 => 'Conflict',
  885. 410 => 'Gone',
  886. 411 => 'Length Required',
  887. 412 => 'Precondition Failed',
  888. 413 => 'Request Entity Too Large',
  889. 414 => 'Request-URI Too Large',
  890. 415 => 'Unsupported Media Type',
  891. 416 => 'Requested range not satisfiable',
  892. 417 => 'Expectation Failed',
  893. 500 => 'Internal Server Error',
  894. 501 => 'Not Implemented',
  895. 502 => 'Bad Gateway',
  896. 503 => 'Service Unavailable',
  897. 504 => 'Gateway Time-out',
  898. 505 => 'HTTP Version not supported',
  899. );
  900. // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  901. // base code in their class.
  902. if (!isset($responses[$code])) {
  903. $code = floor($code / 100) * 100;
  904. }
  905. $result->code = $code;
  906. switch ($code) {
  907. case 200: // OK
  908. case 304: // Not modified
  909. break;
  910. case 301: // Moved permanently
  911. case 302: // Moved temporarily
  912. case 307: // Moved temporarily
  913. $location = $result->headers['location'];
  914. $options['timeout'] -= timer_read(__FUNCTION__) / 1000;
  915. if ($options['timeout'] <= 0) {
  916. $result->code = HTTP_REQUEST_TIMEOUT;
  917. $result->error = 'request timed out';
  918. }
  919. elseif ($options['max_redirects']) {
  920. // Redirect to the new location.
  921. $options['max_redirects']--;
  922. $result = drupal_http_request($location, $options);
  923. $result->redirect_code = $code;
  924. }
  925. if (!isset($result->redirect_url)) {
  926. $result->redirect_url = $location;
  927. }
  928. break;
  929. default:
  930. $result->error = $status_message;
  931. }
  932. return $result;
  933. }
  934. /**
  935. * @} End of "HTTP handling".
  936. */
  937. /**
  938. * Strips slashes from a string or array of strings.
  939. *
  940. * Callback for array_walk() within fix_gpx_magic().
  941. *
  942. * @param $item
  943. * An individual string or array of strings from superglobals.
  944. */
  945. function _fix_gpc_magic(&$item) {
  946. if (is_array($item)) {
  947. array_walk($item, '_fix_gpc_magic');
  948. }
  949. else {
  950. $item = stripslashes($item);
  951. }
  952. }
  953. /**
  954. * Strips slashes from $_FILES items.
  955. *
  956. * Callback for array_walk() within fix_gpc_magic().
  957. *
  958. * The tmp_name key is skipped keys since PHP generates single backslashes for
  959. * file paths on Windows systems.
  960. *
  961. * @param $item
  962. * An item from $_FILES.
  963. * @param $key
  964. * The key for the item within $_FILES.
  965. *
  966. * @see http://php.net/manual/en/features.file-upload.php#42280
  967. */
  968. function _fix_gpc_magic_files(&$item, $key) {
  969. if ($key != 'tmp_name') {
  970. if (is_array($item)) {
  971. array_walk($item, '_fix_gpc_magic_files');
  972. }
  973. else {
  974. $item = stripslashes($item);
  975. }
  976. }
  977. }
  978. /**
  979. * Fixes double-escaping caused by "magic quotes" in some PHP installations.
  980. *
  981. * @see _fix_gpc_magic()
  982. * @see _fix_gpc_magic_files()
  983. */
  984. function fix_gpc_magic() {
  985. static $fixed = FALSE;
  986. if (!$fixed && ini_get('magic_quotes_gpc')) {
  987. array_walk($_GET, '_fix_gpc_magic');
  988. array_walk($_POST, '_fix_gpc_magic');
  989. array_walk($_COOKIE, '_fix_gpc_magic');
  990. array_walk($_REQUEST, '_fix_gpc_magic');
  991. array_walk($_FILES, '_fix_gpc_magic_files');
  992. }
  993. $fixed = TRUE;
  994. }
  995. /**
  996. * @defgroup validation Input validation
  997. * @{
  998. * Functions to validate user input.
  999. */
  1000. /**
  1001. * Verifies the syntax of the given e-mail address.
  1002. *
  1003. * Empty e-mail addresses are allowed. See RFC 2822 for details.
  1004. *
  1005. * @param $mail
  1006. * A string containing an e-mail address.
  1007. *
  1008. * @return
  1009. * TRUE if the address is in a valid format.
  1010. */
  1011. function valid_email_address($mail) {
  1012. return (bool)filter_var($mail, FILTER_VALIDATE_EMAIL);
  1013. }
  1014. /**
  1015. * Verifies the syntax of the given URL.
  1016. *
  1017. * This function should only be used on actual URLs. It should not be used for
  1018. * Drupal menu paths, which can contain arbitrary characters.
  1019. * Valid values per RFC 3986.
  1020. * @param $url
  1021. * The URL to verify.
  1022. * @param $absolute
  1023. * Whether the URL is absolute (beginning with a scheme such as "http:").
  1024. *
  1025. * @return
  1026. * TRUE if the URL is in a valid format.
  1027. */
  1028. function valid_url($url, $absolute = FALSE) {
  1029. if ($absolute) {
  1030. return (bool)preg_match("
  1031. /^ # Start at the beginning of the text
  1032. (?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
  1033. (?: # Userinfo (optional) which is typically
  1034. (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
  1035. (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
  1036. )?
  1037. (?:
  1038. (?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
  1039. |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
  1040. )
  1041. (?::[0-9]+)? # Server port number (optional)
  1042. (?:[\/|\?]
  1043. (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
  1044. *)?
  1045. $/xi", $url);
  1046. }
  1047. else {
  1048. return (bool)preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url);
  1049. }
  1050. }
  1051. /**
  1052. * @} End of "defgroup validation".
  1053. */
  1054. /**
  1055. * Registers an event for the current visitor to the flood control mechanism.
  1056. *
  1057. * @param $name
  1058. * The name of an event.
  1059. * @param $window
  1060. * Optional number of seconds before this event expires. Defaults to 3600 (1
  1061. * hour). Typically uses the same value as the flood_is_allowed() $window
  1062. * parameter. Expired events are purged on cron run to prevent the flood table
  1063. * from growing indefinitely.
  1064. * @param $identifier
  1065. * Optional identifier (defaults to the current user's IP address).
  1066. */
  1067. function flood_register_event($name, $window = 3600, $identifier = NULL) {
  1068. if (!isset($identifier)) {
  1069. $identifier = ip_address();
  1070. }
  1071. db_insert('flood')
  1072. ->fields(array(
  1073. 'event' => $name,
  1074. 'identifier' => $identifier,
  1075. 'timestamp' => REQUEST_TIME,
  1076. 'expiration' => REQUEST_TIME + $window,
  1077. ))
  1078. ->execute();
  1079. }
  1080. /**
  1081. * Makes the flood control mechanism forget an event for the current visitor.
  1082. *
  1083. * @param $name
  1084. * The name of an event.
  1085. * @param $identifier
  1086. * Optional identifier (defaults to the current user's IP address).
  1087. */
  1088. function flood_clear_event($name, $identifier = NULL) {
  1089. if (!isset($identifier)) {
  1090. $identifier = ip_address();
  1091. }
  1092. db_delete('flood')
  1093. ->condition('event', $name)
  1094. ->condition('identifier', $identifier)
  1095. ->execute();
  1096. }
  1097. /**
  1098. * Checks whether a user is allowed to proceed with the specified event.
  1099. *
  1100. * Events can have thresholds saying that each user can only do that event
  1101. * a certain number of times in a time window. This function verifies that the
  1102. * current user has not exceeded this threshold.
  1103. *
  1104. * @param $name
  1105. * The unique name of the event.
  1106. * @param $threshold
  1107. * The maximum number of times each user can do this event per time window.
  1108. * @param $window
  1109. * Number of seconds in the time window for this event (default is 3600
  1110. * seconds, or 1 hour).
  1111. * @param $identifier
  1112. * Unique identifier of the current user. Defaults to their IP address.
  1113. *
  1114. * @return
  1115. * TRUE if the user is allowed to proceed. FALSE if they have exceeded the
  1116. * threshold and should not be allowed to proceed.
  1117. */
  1118. function flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) {
  1119. if (!isset($identifier)) {
  1120. $identifier = ip_address();
  1121. }
  1122. $number = db_query("SELECT COUNT(*) FROM {flood} WHERE event = :event AND identifier = :identifier AND timestamp > :timestamp", array(
  1123. ':event' => $name,
  1124. ':identifier' => $identifier,
  1125. ':timestamp' => REQUEST_TIME - $window))
  1126. ->fetchField();
  1127. return ($number < $threshold);
  1128. }
  1129. /**
  1130. * @defgroup sanitization Sanitization functions
  1131. * @{
  1132. * Functions to sanitize values.
  1133. *
  1134. * See http://drupal.org/writing-secure-code for information
  1135. * on writing secure code.
  1136. */
  1137. /**
  1138. * Strips dangerous protocols (e.g. 'javascript:') from a URI.
  1139. *
  1140. * This function must be called for all URIs within user-entered input prior
  1141. * to being output to an HTML attribute value. It is often called as part of
  1142. * check_url() or filter_xss(), but those functions return an HTML-encoded
  1143. * string, so this function can be called independently when the output needs to
  1144. * be a plain-text string for passing to t(), l(), drupal_attributes(), or
  1145. * another function that will call check_plain() separately.
  1146. *
  1147. * @param $uri
  1148. * A plain-text URI that might contain dangerous protocols.
  1149. *
  1150. * @return
  1151. * A plain-text URI stripped of dangerous protocols. As with all plain-text
  1152. * strings, this return value must not be output to an HTML page without
  1153. * check_plain() being called on it. However, it can be passed to functions
  1154. * expecting plain-text strings.
  1155. *
  1156. * @see check_url()
  1157. */
  1158. function drupal_strip_dangerous_protocols($uri) {
  1159. static $allowed_protocols;
  1160. if (!isset($allowed_protocols)) {
  1161. $allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal')));
  1162. }
  1163. // Iteratively remove any invalid protocol found.
  1164. do {
  1165. $before = $uri;
  1166. $colonpos = strpos($uri, ':');
  1167. if ($colonpos > 0) {
  1168. // We found a colon, possibly a protocol. Verify.
  1169. $protocol = substr($uri, 0, $colonpos);
  1170. // If a colon is preceded by a slash, question mark or hash, it cannot
  1171. // possibly be part of the URL scheme. This must be a relative URL, which
  1172. // inherits the (safe) protocol of the base document.
  1173. if (preg_match('![/?#]!', $protocol)) {
  1174. break;
  1175. }
  1176. // Check if this is a disallowed protocol. Per RFC2616, section 3.2.3
  1177. // (URI Comparison) scheme comparison must be case-insensitive.
  1178. if (!isset($allowed_protocols[strtolower($protocol)])) {
  1179. $uri = substr($uri, $colonpos + 1);
  1180. }
  1181. }
  1182. } while ($before != $uri);
  1183. return $uri;
  1184. }
  1185. /**
  1186. * Strips dangerous protocols from a URI and encodes it for output to HTML.
  1187. *
  1188. * @param $uri
  1189. * A plain-text URI that might contain dangerous protocols.
  1190. *
  1191. * @return
  1192. * A URI stripped of dangerous protocols and encoded for output to an HTML
  1193. * attribute value. Because it is already encoded, it should not be set as a
  1194. * value within a $attributes array passed to drupal_attributes(), because
  1195. * drupal_attributes() expects those values to be plain-text strings. To pass
  1196. * a filtered URI to drupal_attributes(), call
  1197. * drupal_strip_dangerous_protocols() instead.
  1198. *
  1199. * @see drupal_strip_dangerous_protocols()
  1200. */
  1201. function check_url($uri) {
  1202. return check_plain(drupal_strip_dangerous_protocols($uri));
  1203. }
  1204. /**
  1205. * Applies a very permissive XSS/HTML filter for admin-only use.
  1206. *
  1207. * Use only for fields where it is impractical to use the
  1208. * whole filter system, but where some (mainly inline) mark-up
  1209. * is desired (so check_plain() is not acceptable).
  1210. *
  1211. * Allows all tags that can be used inside an HTML body, save
  1212. * for scripts and styles.
  1213. */
  1214. function filter_xss_admin($string) {
  1215. return filter_xss($string, array('a', 'abbr', 'acronym', 'address', 'article', 'aside', 'b', 'bdi', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'command', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'menu', 'meter', 'nav', 'ol', 'output', 'p', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'small', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time', 'tr', 'tt', 'u', 'ul', 'var', 'wbr'));
  1216. }
  1217. /**
  1218. * Filters HTML to prevent cross-site-scripting (XSS) vulnerabilities.
  1219. *
  1220. * Based on kses by Ulf Harnhammar, see http://sourceforge.net/projects/kses.
  1221. * For examples of various XSS attacks, see: http://ha.ckers.org/xss.html.
  1222. *
  1223. * This code does four things:
  1224. * - Removes characters and constructs that can trick browsers.
  1225. * - Makes sure all HTML entities are well-formed.
  1226. * - Makes sure all HTML tags and attributes are well-formed.
  1227. * - Makes sure no HTML tags contain URLs with a disallowed protocol (e.g.
  1228. * javascript:).
  1229. *
  1230. * @param $string
  1231. * The string with raw HTML in it. It will be stripped of everything that can
  1232. * cause an XSS attack.
  1233. * @param $allowed_tags
  1234. * An array of allowed tags.
  1235. *
  1236. * @return
  1237. * An XSS safe version of $string, or an empty string if $string is not
  1238. * valid UTF-8.
  1239. *
  1240. * @see drupal_validate_utf8()
  1241. * @ingroup sanitization
  1242. */
  1243. function filter_xss($string, $allowed_tags = array('a', 'em', 'strong', 'cite', 'blockquote', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd')) {
  1244. // Only operate on valid UTF-8 strings. This is necessary to prevent cross
  1245. // site scripting issues on Internet Explorer 6.
  1246. if (!drupal_validate_utf8($string)) {
  1247. return '';
  1248. }
  1249. // Store the text format.
  1250. _filter_xss_split($allowed_tags, TRUE);
  1251. // Remove NULL characters (ignored by some browsers).
  1252. $string = str_replace(chr(0), '', $string);
  1253. // Remove Netscape 4 JS entities.
  1254. $string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
  1255. // Defuse all HTML entities.
  1256. $string = str_replace('&', '&amp;', $string);
  1257. // Change back only well-formed entities in our whitelist:
  1258. // Decimal numeric entities.
  1259. $string = preg_replace('/&amp;#([0-9]+;)/', '&#\1', $string);
  1260. // Hexadecimal numeric entities.
  1261. $string = preg_replace('/&amp;#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\1', $string);
  1262. // Named entities.
  1263. $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string);
  1264. return preg_replace_callback('%
  1265. (
  1266. <(?=[^a-zA-Z!/]) # a lone <
  1267. | # or
  1268. <!--.*?--> # a comment
  1269. | # or
  1270. <[^>]*(>|$) # a string that starts with a <, up until the > or the end of the string
  1271. | # or
  1272. > # just a >
  1273. )%x', '_filter_xss_split', $string);
  1274. }
  1275. /**
  1276. * Processes an HTML tag.
  1277. *
  1278. * @param $m
  1279. * An array with various meaning depending on the value of $store.
  1280. * If $store is TRUE then the array contains the allowed tags.
  1281. * If $store is FALSE then the array has one element, the HTML tag to process.
  1282. * @param $store
  1283. * Whether to store $m.
  1284. *
  1285. * @return
  1286. * If the element isn't allowed, an empty string. Otherwise, the cleaned up
  1287. * version of the HTML element.
  1288. */
  1289. function _filter_xss_split($m, $store = FALSE) {
  1290. static $allowed_html;
  1291. if ($store) {
  1292. $allowed_html = array_flip($m);
  1293. return;
  1294. }
  1295. $string = $m[1];
  1296. if (substr($string, 0, 1) != '<') {
  1297. // We matched a lone ">" character.
  1298. return '&gt;';
  1299. }
  1300. elseif (strlen($string) == 1) {
  1301. // We matched a lone "<" character.
  1302. return '&lt;';
  1303. }
  1304. if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
  1305. // Seriously malformed.
  1306. return '';
  1307. }
  1308. $slash = trim($matches[1]);
  1309. $elem = &$matches[2];
  1310. $attrlist = &$matches[3];
  1311. $comment = &$matches[4];
  1312. if ($comment) {
  1313. $elem = '!--';
  1314. }
  1315. if (!isset($allowed_html[strtolower($elem)])) {
  1316. // Disallowed HTML element.
  1317. return '';
  1318. }
  1319. if ($comment) {
  1320. return $comment;
  1321. }
  1322. if ($slash != '') {
  1323. return "</$elem>";
  1324. }
  1325. // Is there a closing XHTML slash at the end of the attributes?
  1326. $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
  1327. $xhtml_slash = $count ? ' /' : '';
  1328. // Clean up attributes.
  1329. $attr2 = implode(' ', _filter_xss_attributes($attrlist));
  1330. $attr2 = preg_replace('/[<>]/', '', $attr2);
  1331. $attr2 = strlen($attr2) ? ' ' . $attr2 : '';
  1332. return "<$elem$attr2$xhtml_slash>";
  1333. }
  1334. /**
  1335. * Processes a string of HTML attributes.
  1336. *
  1337. * @return
  1338. * Cleaned up version of the HTML attributes.
  1339. */
  1340. function _filter_xss_attributes($attr) {
  1341. $attrarr = array();
  1342. $mode = 0;
  1343. $attrname = '';
  1344. while (strlen($attr) != 0) {
  1345. // Was the last operation successful?
  1346. $working = 0;
  1347. switch ($mode) {
  1348. case 0:
  1349. // Attribute name, href for instance.
  1350. if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
  1351. $attrname = strtolower($match[1]);
  1352. $skip = ($attrname == 'style' || substr($attrname, 0, 2) == 'on');
  1353. $working = $mode = 1;
  1354. $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
  1355. }
  1356. break;
  1357. case 1:
  1358. // Equals sign or valueless ("selected").
  1359. if (preg_match('/^\s*=\s*/', $attr)) {
  1360. $working = 1; $mode = 2;
  1361. $attr = preg_replace('/^\s*=\s*/', '', $attr);
  1362. break;
  1363. }
  1364. if (preg_match('/^\s+/', $attr)) {
  1365. $working = 1; $mode = 0;
  1366. if (!$skip) {
  1367. $attrarr[] = $attrname;
  1368. }
  1369. $attr = preg_replace('/^\s+/', '', $attr);
  1370. }
  1371. break;
  1372. case 2:
  1373. // Attribute value, a URL after href= for instance.
  1374. if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
  1375. $thisval = filter_xss_bad_protocol($match[1]);
  1376. if (!$skip) {
  1377. $attrarr[] = "$attrname=\"$thisval\"";
  1378. }
  1379. $working = 1;
  1380. $mode = 0;
  1381. $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
  1382. break;
  1383. }
  1384. if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match)) {
  1385. $thisval = filter_xss_bad_protocol($match[1]);
  1386. if (!$skip) {
  1387. $attrarr[] = "$attrname='$thisval'";
  1388. }
  1389. $working = 1; $mode = 0;
  1390. $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
  1391. break;
  1392. }
  1393. if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match)) {
  1394. $thisval = filter_xss_bad_protocol($match[1]);
  1395. if (!$skip) {
  1396. $attrarr[] = "$attrname=\"$thisval\"";
  1397. }
  1398. $working = 1; $mode = 0;
  1399. $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
  1400. }
  1401. break;
  1402. }
  1403. if ($working == 0) {
  1404. // Not well formed; remove and try again.
  1405. $attr = preg_replace('/
  1406. ^
  1407. (
  1408. "[^"]*("|$) # - a string that starts with a double quote, up until the next double quote or the end of the string
  1409. | # or
  1410. \'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
  1411. | # or
  1412. \S # - a non-whitespace character
  1413. )* # any number of the above three
  1414. \s* # any number of whitespaces
  1415. /x', '', $attr);
  1416. $mode = 0;
  1417. }
  1418. }
  1419. // The attribute list ends with a valueless attribute like "selected".
  1420. if ($mode == 1 && !$skip) {
  1421. $attrarr[] = $attrname;
  1422. }
  1423. return $attrarr;
  1424. }
  1425. /**
  1426. * Processes an HTML attribute value and strips dangerous protocols from URLs.
  1427. *
  1428. * @param $string
  1429. * The string with the attribute value.
  1430. * @param $decode
  1431. * (deprecated) Whether to decode entities in the $string. Set to FALSE if the
  1432. * $string is in plain text, TRUE otherwise. Defaults to TRUE. This parameter
  1433. * is deprecated and will be removed in Drupal 8. To process a plain-text URI,
  1434. * call drupal_strip_dangerous_protocols() or check_url() instead.
  1435. *
  1436. * @return
  1437. * Cleaned up and HTML-escaped version of $string.
  1438. */
  1439. function filter_xss_bad_protocol($string, $decode = TRUE) {
  1440. // Get the plain text representation of the attribute value (i.e. its meaning).
  1441. // @todo Remove the $decode parameter in Drupal 8, and always assume an HTML
  1442. // string that needs decoding.
  1443. if ($decode) {
  1444. if (!function_exists('decode_entities')) {
  1445. require_once DRUPAL_ROOT . '/includes/unicode.inc';
  1446. }
  1447. $string = decode_entities($string);
  1448. }
  1449. return check_plain(drupal_strip_dangerous_protocols($string));
  1450. }
  1451. /**
  1452. * @} End of "defgroup sanitization".
  1453. */
  1454. /**
  1455. * @defgroup format Formatting
  1456. * @{
  1457. * Functions to format numbers, strings, dates, etc.
  1458. */
  1459. /**
  1460. * Formats an RSS channel.
  1461. *
  1462. * Arbitrary elements may be added using the $args associative array.
  1463. */
  1464. function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
  1465. global $language_content;
  1466. $langcode = $langcode ? $langcode : $language_content->language;
  1467. $output = "<channel>\n";
  1468. $output .= ' <title>' . check_plain($title) . "</title>\n";
  1469. $output .= ' <link>' . check_url($link) . "</link>\n";
  1470. // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
  1471. // We strip all HTML tags, but need to prevent double encoding from properly
  1472. // escaped source data (such as &amp becoming &amp;amp;).
  1473. $output .= ' <description>' . check_plain(decode_entities(strip_tags($description))) . "</description>\n";
  1474. $output .= ' <language>' . check_plain($langcode) . "</language>\n";
  1475. $output .= format_xml_elements($args);
  1476. $output .= $items;
  1477. $output .= "</channel>\n";
  1478. return $output;
  1479. }
  1480. /**
  1481. * Formats a single RSS item.
  1482. *
  1483. * Arbitrary elements may be added using the $args associative array.
  1484. */
  1485. function format_rss_item($title, $link, $description, $args = array()) {
  1486. $output = "<item>\n";
  1487. $output .= ' <title>' . check_plain($title) . "</title>\n";
  1488. $output .= ' <link>' . check_url($link) . "</link>\n";
  1489. $output .= ' <description>' . check_plain($description) . "</description>\n";
  1490. $output .= format_xml_elements($args);
  1491. $output .= "</item>\n";
  1492. return $output;
  1493. }
  1494. /**
  1495. * Formats XML elements.
  1496. *
  1497. * @param $array
  1498. * An array where each item represents an element and is either a:
  1499. * - (key => value) pair (<key>value</key>)
  1500. * - Associative array with fields:
  1501. * - 'key': element name
  1502. * - 'value': element contents
  1503. * - 'attributes': associative array of element attributes
  1504. *
  1505. * In both cases, 'value' can be a simple string, or it can be another array
  1506. * with the same format as $array itself for nesting.
  1507. */
  1508. function format_xml_elements($array) {
  1509. $output = '';
  1510. foreach ($array as $key => $value) {
  1511. if (is_numeric($key)) {
  1512. if ($value['key']) {
  1513. $output .= ' <' . $value['key'];
  1514. if (isset($value['attributes']) && is_array($value['attributes'])) {
  1515. $output .= drupal_attributes($value['attributes']);
  1516. }
  1517. if (isset($value['value']) && $value['value'] != '') {
  1518. $output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) . '</' . $value['key'] . ">\n";
  1519. }
  1520. else {
  1521. $output .= " />\n";
  1522. }
  1523. }
  1524. }
  1525. else {
  1526. $output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</$key>\n";
  1527. }
  1528. }
  1529. return $output;
  1530. }
  1531. /**
  1532. * Formats a string containing a count of items.
  1533. *
  1534. * This function ensures that the string is pluralized correctly. Since t() is
  1535. * called by this function, make sure not to pass already-localized strings to
  1536. * it.
  1537. *
  1538. * For example:
  1539. * @code
  1540. * $output = format_plural($node->comment_count, '1 comment', '@count comments');
  1541. * @endcode
  1542. *
  1543. * Example with additional replacements:
  1544. * @code
  1545. * $output = format_plural($update_count,
  1546. * 'Changed the content type of 1 post from %old-type to %new-type.',
  1547. * 'Changed the content type of @count posts from %old-type to %new-type.',
  1548. * array('%old-type' => $info->old_type, '%new-type' => $info->new_type)));
  1549. * @endcode
  1550. *
  1551. * @param $count
  1552. * The item count to display.
  1553. * @param $singular
  1554. * The string for the singular case. Make sure it is clear this is singular,
  1555. * to ease translation (e.g. use "1 new comment" instead of "1 new"). Do not
  1556. * use @count in the singular string.
  1557. * @param $plural
  1558. * The string for the plural case. Make sure it is clear this is plural, to
  1559. * ease translation. Use @count in place of the item count, as in
  1560. * "@count new comments".
  1561. * @param $args
  1562. * An associative array of replacements to make after translation. Instances
  1563. * of any key in this array are replaced with the corresponding value.
  1564. * Based on the first character of the key, the value is escaped and/or
  1565. * themed. See format_string(). Note that you do not need to include @count
  1566. * in this array; this replacement is done automatically for the plural case.
  1567. * @param $options
  1568. * An associative array of additional options. See t() for allowed keys.
  1569. *
  1570. * @return
  1571. * A translated string.
  1572. *
  1573. * @see t()
  1574. * @see format_string()
  1575. */
  1576. function format_plural($count, $singular, $plural, array $args = array(), array $options = array()) {
  1577. $args['@count'] = $count;
  1578. if ($count == 1) {
  1579. return t($singular, $args, $options);
  1580. }
  1581. // Get the plural index through the gettext formula.
  1582. $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, isset($options['langcode']) ? $options['langcode'] : NULL) : -1;
  1583. // Backwards compatibility.
  1584. if ($index < 0) {
  1585. return t($plural, $args, $options);
  1586. }
  1587. else {
  1588. switch ($index) {
  1589. case "0":
  1590. return t($singular, $args, $options);
  1591. case "1":
  1592. return t($plural, $args, $options);
  1593. default:
  1594. unset($args['@count']);
  1595. $args['@count[' . $index . ']'] = $count;
  1596. return t(strtr($plural, array('@count' => '@count[' . $index . ']')), $args, $options);
  1597. }
  1598. }
  1599. }
  1600. /**
  1601. * Parses a given byte count.
  1602. *
  1603. * @param $size
  1604. * A size expressed as a number of bytes with optional SI or IEC binary unit
  1605. * prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).
  1606. *
  1607. * @return
  1608. * An integer representation of the size in bytes.
  1609. */
  1610. function parse_size($size) {
  1611. $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size.
  1612. $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size.
  1613. if ($unit) {
  1614. // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by.
  1615. return round($size * pow(DRUPAL_KILOBYTE, stripos('bkmgtpezy', $unit[0])));
  1616. }
  1617. else {
  1618. return round($size);
  1619. }
  1620. }
  1621. /**
  1622. * Generates a string representation for the given byte count.
  1623. *
  1624. * @param $size
  1625. * A size in bytes.
  1626. * @param $langcode
  1627. * Optional language code to translate to a language other than what is used
  1628. * to display the page.
  1629. *
  1630. * @return
  1631. * A translated string representation of the size.
  1632. */
  1633. function format_size($size, $langcode = NULL) {
  1634. if ($size < DRUPAL_KILOBYTE) {
  1635. return format_plural($size, '1 byte', '@count bytes', array(), array('langcode' => $langcode));
  1636. }
  1637. else {
  1638. $size = $size / DRUPAL_KILOBYTE; // Convert bytes to kilobytes.
  1639. $units = array(
  1640. t('@size KB', array(), array('langcode' => $langcode)),
  1641. t('@size MB', array(), array('langcode' => $langcode)),
  1642. t('@size GB', array(), array('langcode' => $langcode)),
  1643. t('@size TB', array(), array('langcode' => $langcode)),
  1644. t('@size PB', array(), array('langcode' => $langcode)),
  1645. t('@size EB', array(), array('langcode' => $langcode)),
  1646. t('@size ZB', array(), array('langcode' => $langcode)),
  1647. t('@size YB', array(), array('langcode' => $langcode)),
  1648. );
  1649. foreach ($units as $unit) {
  1650. if (round($size, 2) >= DRUPAL_KILOBYTE) {
  1651. $size = $size / DRUPAL_KILOBYTE;
  1652. }
  1653. else {
  1654. break;
  1655. }
  1656. }
  1657. return str_replace('@size', round($size, 2), $unit);
  1658. }
  1659. }
  1660. /**
  1661. * Formats a time interval with the requested granularity.
  1662. *
  1663. * @param $interval
  1664. * The length of the interval in seconds.
  1665. * @param $granularity
  1666. * How many different units to display in the string.
  1667. * @param $langcode
  1668. * Optional language code to translate to a language other than
  1669. * what is used to display the page.
  1670. *
  1671. * @return
  1672. * A translated string representation of the interval.
  1673. */
  1674. function format_interval($interval, $granularity = 2, $langcode = NULL) {
  1675. $units = array(
  1676. '1 year|@count years' => 31536000,
  1677. '1 month|@count months' => 2592000,
  1678. '1 week|@count weeks' => 604800,
  1679. '1 day|@count days' => 86400,
  1680. '1 hour|@count hours' => 3600,
  1681. '1 min|@count min' => 60,
  1682. '1 sec|@count sec' => 1
  1683. );
  1684. $output = '';
  1685. foreach ($units as $key => $value) {
  1686. $key = explode('|', $key);
  1687. if ($interval >= $value) {
  1688. $output .= ($output ? ' ' : '') . format_plural(floor($interval / $value), $key[0], $key[1], array(), array('langcode' => $langcode));
  1689. $interval %= $value;
  1690. $granularity--;
  1691. }
  1692. if ($granularity == 0) {
  1693. break;
  1694. }
  1695. }
  1696. return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
  1697. }
  1698. /**
  1699. * Formats a date, using a date type or a custom date format string.
  1700. *
  1701. * @param $timestamp
  1702. * A UNIX timestamp to format.
  1703. * @param $type
  1704. * (optional) The format to use, one of:
  1705. * - 'short', 'medium', or 'long' (the corresponding built-in date formats).
  1706. * - The name of a date type defined by a module in hook_date_format_types(),
  1707. * if it's been assigned a format.
  1708. * - The machine name of an administrator-defined date format.
  1709. * - 'custom', to use $format.
  1710. * Defaults to 'medium'.
  1711. * @param $format
  1712. * (optional) If $type is 'custom', a PHP date format string suitable for
  1713. * input to date(). Use a backslash to escape ordinary text, so it does not
  1714. * get interpreted as date format characters.
  1715. * @param $timezone
  1716. * (optional) Time zone identifier, as described at
  1717. * http://php.net/manual/en/timezones.php Defaults to the time zone used to
  1718. * display the page.
  1719. * @param $langcode
  1720. * (optional) Language code to translate to. Defaults to the language used to
  1721. * display the page.
  1722. *
  1723. * @return
  1724. * A translated date string in the requested format.
  1725. */
  1726. function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
  1727. // Use the advanced drupal_static() pattern, since this is called very often.
  1728. static $drupal_static_fast;
  1729. if (!isset($drupal_static_fast)) {
  1730. $drupal_static_fast['timezones'] = &drupal_static(__FUNCTION__);
  1731. }
  1732. $timezones = &$drupal_static_fast['timezones'];
  1733. if (!isset($timezone)) {
  1734. $timezone = date_default_timezone_get();
  1735. }
  1736. // Store DateTimeZone objects in an array rather than repeatedly
  1737. // constructing identical objects over the life of a request.
  1738. if (!isset($timezones[$timezone])) {
  1739. $timezones[$timezone] = timezone_open($timezone);
  1740. }
  1741. // Use the default langcode if none is set.
  1742. global $language;
  1743. if (empty($langcode)) {
  1744. $langcode = isset($language->language) ? $language->language : 'en';
  1745. }
  1746. switch ($type) {
  1747. case 'short':
  1748. $format = variable_get('date_format_short', 'm/d/Y - H:i');
  1749. break;
  1750. case 'long':
  1751. $format = variable_get('date_format_long', 'l, F j, Y - H:i');
  1752. break;
  1753. case 'custom':
  1754. // No change to format.
  1755. break;
  1756. case 'medium':
  1757. default:
  1758. // Retrieve the format of the custom $type passed.
  1759. if ($type != 'medium') {
  1760. $format = variable_get('date_format_' . $type, '');
  1761. }
  1762. // Fall back to 'medium'.
  1763. if ($format === '') {
  1764. $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
  1765. }
  1766. break;
  1767. }
  1768. // Create a DateTime object from the timestamp.
  1769. $date_time = date_create('@' . $timestamp);
  1770. // Set the time zone for the DateTime object.
  1771. date_timezone_set($date_time, $timezones[$timezone]);
  1772. // Encode markers that should be translated. 'A' becomes '\xEF\AA\xFF'.
  1773. // xEF and xFF are invalid UTF-8 sequences, and we assume they are not in the
  1774. // input string.
  1775. // Paired backslashes are isolated to prevent errors in read-ahead evaluation.
  1776. // The read-ahead expression ensures that A matches, but not \A.
  1777. $format = preg_replace(array('/\\\\\\\\/', '/(?<!\\\\)([AaeDlMTF])/'), array("\xEF\\\\\\\\\xFF", "\xEF\\\\\$1\$1\xFF"), $format);
  1778. // Call date_format().
  1779. $format = date_format($date_time, $format);
  1780. // Pass the langcode to _format_date_callback().
  1781. _format_date_callback(NULL, $langcode);
  1782. // Translate the marked sequences.
  1783. return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);
  1784. }
  1785. /**
  1786. * Returns an ISO8601 formatted date based on the given date.
  1787. *
  1788. * Callback for use within hook_rdf_mapping() implementations.
  1789. *
  1790. * @param $date
  1791. * A UNIX timestamp.
  1792. *
  1793. * @return string
  1794. * An ISO8601 formatted date.
  1795. */
  1796. function date_iso8601($date) {
  1797. // The DATE_ISO8601 constant cannot be used here because it does not match
  1798. // date('c') and produces invalid RDF markup.
  1799. return date('c', $date);
  1800. }
  1801. /**
  1802. * Translates a formatted date string.
  1803. *
  1804. * Callback for preg_replace_callback() within format_date().
  1805. */
  1806. function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
  1807. // We cache translations to avoid redundant and rather costly calls to t().
  1808. static $cache, $langcode;
  1809. if (!isset($matches)) {
  1810. $langcode = $new_langcode;
  1811. return;
  1812. }
  1813. $code = $matches[1];
  1814. $string = $matches[2];
  1815. if (!isset($cache[$langcode][$code][$string])) {
  1816. $options = array(
  1817. 'langcode' => $langcode,
  1818. );
  1819. if ($code == 'F') {
  1820. $options['context'] = 'Long month name';
  1821. }
  1822. if ($code == '') {
  1823. $cache[$langcode][$code][$string] = $string;
  1824. }
  1825. else {
  1826. $cache[$langcode][$code][$string] = t($string, array(), $options);
  1827. }
  1828. }
  1829. return $cache[$langcode][$code][$string];
  1830. }
  1831. /**
  1832. * Format a username.
  1833. *
  1834. * By default, the passed-in object's 'name' property is used if it exists, or
  1835. * else, the site-defined value for the 'anonymous' variable. However, a module
  1836. * may override this by implementing hook_username_alter(&$name, $account).
  1837. *
  1838. * @see hook_username_alter()
  1839. *
  1840. * @param $account
  1841. * The account object for the user whose name is to be formatted.
  1842. *
  1843. * @return
  1844. * An unsanitized string with the username to display. The code receiving
  1845. * this result must ensure that check_plain() is called on it before it is
  1846. * printed to the page.
  1847. */
  1848. function format_username($account) {
  1849. $name = !empty($account->name) ? $account->name : variable_get('anonymous', t('Anonymous'));
  1850. drupal_alter('username', $name, $account);
  1851. return $name;
  1852. }
  1853. /**
  1854. * @} End of "defgroup format".
  1855. */
  1856. /**
  1857. * Generates an internal or external URL.
  1858. *
  1859. * When creating links in modules, consider whether l() could be a better
  1860. * alternative than url().
  1861. *
  1862. * @param $path
  1863. * The internal path or external URL being linked to, such as "node/34" or
  1864. * "http://example.com/foo". A few notes:
  1865. * - If you provide a full URL, it will be considered an external URL.
  1866. * - If you provide only the path (e.g. "node/34"), it will be
  1867. * considered an internal link. In this case, it should be a system URL,
  1868. * and it will be replaced with the alias, if one exists. Additional query
  1869. * arguments for internal paths must be supplied in $options['query'], not
  1870. * included in $path.
  1871. * - If you provide an internal path and $options['alias'] is set to TRUE, the
  1872. * path is assumed already to be the correct path alias, and the alias is
  1873. * not looked up.
  1874. * - The special string '<front>' generates a link to the site's base URL.
  1875. * - If your external URL contains a query (e.g. http://example.com/foo?a=b),
  1876. * then you can either URL encode the query keys and values yourself and
  1877. * include them in $path, or use $options['query'] to let this function
  1878. * URL encode them.
  1879. * @param $options
  1880. * An associative array of additional options, with the following elements:
  1881. * - 'query': An array of query key/value-pairs (without any URL-encoding) to
  1882. * append to the URL.
  1883. * - 'fragment': A fragment identifier (named anchor) to append to the URL.
  1884. * Do not include the leading '#' character.
  1885. * - 'absolute': Defaults to FALSE. Whether to force the output to be an
  1886. * absolute link (beginning with http:). Useful for links that will be
  1887. * displayed outside the site, such as in an RSS feed.
  1888. * - 'alias': Defaults to FALSE. Whether the given path is a URL alias
  1889. * already.
  1890. * - 'external': Whether the given path is an external URL.
  1891. * - 'language': An optional language object. If the path being linked to is
  1892. * internal to the site, $options['language'] is used to look up the alias
  1893. * for the URL. If $options['language'] is omitted, the global $language_url
  1894. * will be used.
  1895. * - 'https': Whether this URL should point to a secure location. If not
  1896. * defined, the current scheme is used, so the user stays on http or https
  1897. * respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but HTTPS can
  1898. * only be enforced when the variable 'https' is set to TRUE.
  1899. * - 'base_url': Only used internally, to modify the base URL when a language
  1900. * dependent URL requires so.
  1901. * - 'prefix': Only used internally, to modify the path when a language
  1902. * dependent URL requires so.
  1903. * - 'script': The script filename in Drupal's root directory to use when
  1904. * clean URLs are disabled, such as 'index.php'. Defaults to an empty
  1905. * string, as most modern web servers automatically find 'index.php'. If
  1906. * clean URLs are disabled, the value of $path is appended as query
  1907. * parameter 'q' to $options['script'] in the returned URL. When deploying
  1908. * Drupal on a web server that cannot be configured to automatically find
  1909. * index.php, then hook_url_outbound_alter() can be implemented to force
  1910. * this value to 'index.php'.
  1911. * - 'entity_type': The entity type of the object that called url(). Only
  1912. * set if url() is invoked by entity_uri().
  1913. * - 'entity': The entity object (such as a node) for which the URL is being
  1914. * generated. Only set if url() is invoked by entity_uri().
  1915. *
  1916. * @return
  1917. * A string containing a URL to the given path.
  1918. */
  1919. function url($path = NULL, array $options = array()) {
  1920. // Merge in defaults.
  1921. $options += array(
  1922. 'fragment' => '',
  1923. 'query' => array(),
  1924. 'absolute' => FALSE,
  1925. 'alias' => FALSE,
  1926. 'prefix' => ''
  1927. );
  1928. if (!isset($options['external'])) {
  1929. // Return an external link if $path contains an allowed absolute URL. Only
  1930. // call the slow drupal_strip_dangerous_protocols() if $path contains a ':'
  1931. // before any / ? or #. Note: we could use url_is_external($path) here, but
  1932. // that would require another function call, and performance inside url() is
  1933. // critical.
  1934. $colonpos = strpos($path, ':');
  1935. $options['external'] = ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && drupal_strip_dangerous_protocols($path) == $path);
  1936. }
  1937. // Preserve the original path before altering or aliasing.
  1938. $original_path = $path;
  1939. // Allow other modules to alter the outbound URL and options.
  1940. drupal_alter('url_outbound', $path, $options, $original_path);
  1941. if (isset($options['fragment']) && $options['fragment'] !== '') {
  1942. $options['fragment'] = '#' . $options['fragment'];
  1943. }
  1944. if ($options['external']) {
  1945. // Split off the fragment.
  1946. if (strpos($path, '#') !== FALSE) {
  1947. list($path, $old_fragment) = explode('#', $path, 2);
  1948. // If $options contains no fragment, take it over from the path.
  1949. if (isset($old_fragment) && !$options['fragment']) {
  1950. $options['fragment'] = '#' . $old_fragment;
  1951. }
  1952. }
  1953. // Append the query.
  1954. if ($options['query']) {
  1955. $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($options['query']);
  1956. }
  1957. if (isset($options['https']) && variable_get('https', FALSE)) {
  1958. if ($options['https'] === TRUE) {
  1959. $path = str_replace('http://', 'https://', $path);
  1960. }
  1961. elseif ($options['https'] === FALSE) {
  1962. $path = str_replace('https://', 'http://', $path);
  1963. }
  1964. }
  1965. // Reassemble.
  1966. return $path . $options['fragment'];
  1967. }
  1968. global $base_url, $base_secure_url, $base_insecure_url;
  1969. // The base_url might be rewritten from the language rewrite in domain mode.
  1970. if (!isset($options['base_url'])) {
  1971. if (isset($options['https']) && variable_get('https', FALSE)) {
  1972. if ($options['https'] === TRUE) {
  1973. $options['base_url'] = $base_secure_url;
  1974. $options['absolute'] = TRUE;
  1975. }
  1976. elseif ($options['https'] === FALSE) {
  1977. $options['base_url'] = $base_insecure_url;
  1978. $options['absolute'] = TRUE;
  1979. }
  1980. }
  1981. else {
  1982. $options['base_url'] = $base_url;
  1983. }
  1984. }
  1985. // The special path '<front>' links to the default front page.
  1986. if ($path == '<front>') {
  1987. $path = '';
  1988. }
  1989. elseif (!empty($path) && !$options['alias']) {
  1990. $language = isset($options['language']) && isset($options['language']->language) ? $options['language']->language : '';
  1991. $alias = drupal_get_path_alias($original_path, $language);
  1992. if ($alias != $original_path) {
  1993. $path = $alias;
  1994. }
  1995. }
  1996. $base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
  1997. $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
  1998. // With Clean URLs.
  1999. if (!empty($GLOBALS['conf']['clean_url'])) {
  2000. $path = drupal_encode_path($prefix . $path);
  2001. if ($options['query']) {
  2002. return $base . $path . '?' . drupal_http_build_query($options['query']) . $options['fragment'];
  2003. }
  2004. else {
  2005. return $base . $path . $options['fragment'];
  2006. }
  2007. }
  2008. // Without Clean URLs.
  2009. else {
  2010. $path = $prefix . $path;
  2011. $query = array();
  2012. if (!empty($path)) {
  2013. $query['q'] = $path;
  2014. }
  2015. if ($options['query']) {
  2016. // We do not use array_merge() here to prevent overriding $path via query
  2017. // parameters.
  2018. $query += $options['query'];
  2019. }
  2020. $query = $query ? ('?' . drupal_http_build_query($query)) : '';
  2021. $script = isset($options['script']) ? $options['script'] : '';
  2022. return $base . $script . $query . $options['fragment'];
  2023. }
  2024. }
  2025. /**
  2026. * Returns TRUE if a path is external to Drupal (e.g. http://example.com).
  2027. *
  2028. * If a path cannot be assessed by Drupal's menu handler, then we must
  2029. * treat it as potentially insecure.
  2030. *
  2031. * @param $path
  2032. * The internal path or external URL being linked to, such as "node/34" or
  2033. * "http://example.com/foo".
  2034. *
  2035. * @return
  2036. * Boolean TRUE or FALSE, where TRUE indicates an external path.
  2037. */
  2038. function url_is_external($path) {
  2039. $colonpos = strpos($path, ':');
  2040. // Avoid calling drupal_strip_dangerous_protocols() if there is any
  2041. // slash (/), hash (#) or question_mark (?) before the colon (:)
  2042. // occurrence - if any - as this would clearly mean it is not a URL.
  2043. return $colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && drupal_strip_dangerous_protocols($path) == $path;
  2044. }
  2045. /**
  2046. * Formats an attribute string for an HTTP header.
  2047. *
  2048. * @param $attributes
  2049. * An associative array of attributes such as 'rel'.
  2050. *
  2051. * @return
  2052. * A ; separated string ready for insertion in a HTTP header. No escaping is
  2053. * performed for HTML entities, so this string is not safe to be printed.
  2054. *
  2055. * @see drupal_add_http_header()
  2056. */
  2057. function drupal_http_header_attributes(array $attributes = array()) {
  2058. foreach ($attributes as $attribute => &$data) {
  2059. if (is_array($data)) {
  2060. $data = implode(' ', $data);
  2061. }
  2062. $data = $attribute . '="' . $data . '"';
  2063. }
  2064. return $attributes ? ' ' . implode('; ', $attributes) : '';
  2065. }
  2066. /**
  2067. * Converts an associative array to an XML/HTML tag attribute string.
  2068. *
  2069. * Each array key and its value will be formatted into an attribute string.
  2070. * If a value is itself an array, then its elements are concatenated to a single
  2071. * space-delimited string (for example, a class attribute with multiple values).
  2072. *
  2073. * Attribute values are sanitized by running them through check_plain().
  2074. * Attribute names are not automatically sanitized. When using user-supplied
  2075. * attribute names, it is strongly recommended to allow only white-listed names,
  2076. * since certain attributes carry security risks and can be abused.
  2077. *
  2078. * Examples of security aspects when using drupal_attributes:
  2079. * @code
  2080. * // By running the value in the following statement through check_plain,
  2081. * // the malicious script is neutralized.
  2082. * drupal_attributes(array('title' => t('<script>steal_cookie();</script>')));
  2083. *
  2084. * // The statement below demonstrates dangerous use of drupal_attributes, and
  2085. * // will return an onmouseout attribute with JavaScript code that, when used
  2086. * // as attribute in a tag, will cause users to be redirected to another site.
  2087. * //
  2088. * // In this case, the 'onmouseout' attribute should not be whitelisted --
  2089. * // you don't want users to have the ability to add this attribute or others
  2090. * // that take JavaScript commands.
  2091. * drupal_attributes(array('onmouseout' => 'window.location="http://malicious.com/";')));
  2092. * @endcode
  2093. *
  2094. * @param $attributes
  2095. * An associative array of key-value pairs to be converted to attributes.
  2096. *
  2097. * @return
  2098. * A string ready for insertion in a tag (starts with a space).
  2099. *
  2100. * @ingroup sanitization
  2101. */
  2102. function drupal_attributes(array $attributes = array()) {
  2103. foreach ($attributes as $attribute => &$data) {
  2104. $data = implode(' ', (array) $data);
  2105. $data = $attribute . '="' . check_plain($data) . '"';
  2106. }
  2107. return $attributes ? ' ' . implode(' ', $attributes) : '';
  2108. }
  2109. /**
  2110. * Formats an internal or external URL link as an HTML anchor tag.
  2111. *
  2112. * This function correctly handles aliased paths, and adds an 'active' class
  2113. * attribute to links that point to the current page (for theming), so all
  2114. * internal links output by modules should be generated by this function if
  2115. * possible.
  2116. *
  2117. * @param $text
  2118. * The link text for the anchor tag.
  2119. * @param $path
  2120. * The internal path or external URL being linked to, such as "node/34" or
  2121. * "http://example.com/foo". After the url() function is called to construct
  2122. * the URL from $path and $options, the resulting URL is passed through
  2123. * check_plain() before it is inserted into the HTML anchor tag, to ensure
  2124. * well-formed HTML. See url() for more information and notes.
  2125. * @param array $options
  2126. * An associative array of additional options, with the following elements:
  2127. * - 'attributes': An associative array of HTML attributes to apply to the
  2128. * anchor tag. If element 'class' is included, it must be an array; 'title'
  2129. * must be a string; other elements are more flexible, as they just need
  2130. * to work in a call to drupal_attributes($options['attributes']).
  2131. * - 'html' (default FALSE): Whether $text is HTML or just plain-text. For
  2132. * example, to make an image tag into a link, this must be set to TRUE, or
  2133. * you will see the escaped HTML image tag. $text is not sanitized if
  2134. * 'html' is TRUE. The calling function must ensure that $text is already
  2135. * safe.
  2136. * - 'language': An optional language object. If the path being linked to is
  2137. * internal to the site, $options['language'] is used to determine whether
  2138. * the link is "active", or pointing to the current page (the language as
  2139. * well as the path must match). This element is also used by url().
  2140. * - Additional $options elements used by the url() function.
  2141. *
  2142. * @return
  2143. * An HTML string containing a link to the given path.
  2144. */
  2145. function l($text, $path, array $options = array()) {
  2146. global $language_url;
  2147. static $use_theme = NULL;
  2148. // Merge in defaults.
  2149. $options += array(
  2150. 'attributes' => array(),
  2151. 'html' => FALSE,
  2152. );
  2153. // Append active class.
  2154. if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
  2155. (empty($options['language']) || $options['language']->language == $language_url->language)) {
  2156. $options['attributes']['class'][] = 'active';
  2157. }
  2158. // Remove all HTML and PHP tags from a tooltip. For best performance, we act only
  2159. // if a quick strpos() pre-check gave a suspicion (because strip_tags() is expensive).
  2160. if (isset($options['attributes']['title']) && strpos($options['attributes']['title'], '<') !== FALSE) {
  2161. $options['attributes']['title'] = strip_tags($options['attributes']['title']);
  2162. }
  2163. // Determine if rendering of the link is to be done with a theme function
  2164. // or the inline default. Inline is faster, but if the theme system has been
  2165. // loaded and a module or theme implements a preprocess or process function
  2166. // or overrides the theme_link() function, then invoke theme(). Preliminary
  2167. // benchmarks indicate that invoking theme() can slow down the l() function
  2168. // by 20% or more, and that some of the link-heavy Drupal pages spend more
  2169. // than 10% of the total page request time in the l() function.
  2170. if (!isset($use_theme) && function_exists('theme')) {
  2171. // Allow edge cases to prevent theme initialization and force inline link
  2172. // rendering.
  2173. if (variable_get('theme_link', TRUE)) {
  2174. drupal_theme_initialize();
  2175. $registry = theme_get_registry(FALSE);
  2176. // We don't want to duplicate functionality that's in theme(), so any
  2177. // hint of a module or theme doing anything at all special with the 'link'
  2178. // theme hook should simply result in theme() being called. This includes
  2179. // the overriding of theme_link() with an alternate function or template,
  2180. // the presence of preprocess or process functions, or the presence of
  2181. // include files.
  2182. $use_theme = !isset($registry['link']['function']) || ($registry['link']['function'] != 'theme_link');
  2183. $use_theme = $use_theme || !empty($registry['link']['preprocess functions']) || !empty($registry['link']['process functions']) || !empty($registry['link']['includes']);
  2184. }
  2185. else {
  2186. $use_theme = FALSE;
  2187. }
  2188. }
  2189. if ($use_theme) {
  2190. return theme('link', array('text' => $text, 'path' => $path, 'options' => $options));
  2191. }
  2192. // The result of url() is a plain-text URL. Because we are using it here
  2193. // in an HTML argument context, we need to encode it properly.
  2194. return '<a href="' . check_plain(url($path, $options)) . '"' . drupal_attributes($options['attributes']) . '>' . ($options['html'] ? $text : check_plain($text)) . '</a>';
  2195. }
  2196. /**
  2197. * Delivers a page callback result to the browser in the appropriate format.
  2198. *
  2199. * This function is most commonly called by menu_execute_active_handler(), but
  2200. * can also be called by error conditions such as drupal_not_found(),
  2201. * drupal_access_denied(), and drupal_site_offline().
  2202. *
  2203. * When a user requests a page, index.php calls menu_execute_active_handler(),
  2204. * which calls the 'page callback' function registered in hook_menu(). The page
  2205. * callback function can return one of:
  2206. * - NULL: to indicate no content.
  2207. * - An integer menu status constant: to indicate an error condition.
  2208. * - A string of HTML content.
  2209. * - A renderable array of content.
  2210. * Returning a renderable array rather than a string of HTML is preferred,
  2211. * because that provides modules with more flexibility in customizing the final
  2212. * result.
  2213. *
  2214. * When the page callback returns its constructed content to
  2215. * menu_execute_active_handler(), this function gets called. The purpose of
  2216. * this function is to determine the most appropriate 'delivery callback'
  2217. * function to route the content to. The delivery callback function then
  2218. * sends the content to the browser in the needed format. The default delivery
  2219. * callback is drupal_deliver_html_page(), which delivers the content as an HTML
  2220. * page, complete with blocks in addition to the content. This default can be
  2221. * overridden on a per menu router item basis by setting 'delivery callback' in
  2222. * hook_menu() or hook_menu_alter(), and can also be overridden on a per request
  2223. * basis in hook_page_delivery_callback_alter().
  2224. *
  2225. * For example, the same page callback function can be used for an HTML
  2226. * version of the page and an Ajax version of the page. The page callback
  2227. * function just needs to decide what content is to be returned and the
  2228. * delivery callback function will send it as an HTML page or an Ajax
  2229. * response, as appropriate.
  2230. *
  2231. * In order for page callbacks to be reusable in different delivery formats,
  2232. * they should not issue any "print" or "echo" statements, but instead just
  2233. * return content.
  2234. *
  2235. * Also note that this function does not perform access checks. The delivery
  2236. * callback function specified in hook_menu(), hook_menu_alter(), or
  2237. * hook_page_delivery_callback_alter() will be called even if the router item
  2238. * access checks fail. This is intentional (it is needed for JSON and other
  2239. * purposes), but it has security implications. Do not call this function
  2240. * directly unless you understand the security implications, and be careful in
  2241. * writing delivery callbacks, so that they do not violate security. See
  2242. * drupal_deliver_html_page() for an example of a delivery callback that
  2243. * respects security.
  2244. *
  2245. * @param $page_callback_result
  2246. * The result of a page callback. Can be one of:
  2247. * - NULL: to indicate no content.
  2248. * - An integer menu status constant: to indicate an error condition.
  2249. * - A string of HTML content.
  2250. * - A renderable array of content.
  2251. * @param $default_delivery_callback
  2252. * (Optional) If given, it is the name of a delivery function most likely
  2253. * to be appropriate for the page request as determined by the calling
  2254. * function (e.g., menu_execute_active_handler()). If not given, it is
  2255. * determined from the menu router information of the current page.
  2256. *
  2257. * @see menu_execute_active_handler()
  2258. * @see hook_menu()
  2259. * @see hook_menu_alter()
  2260. * @see hook_page_delivery_callback_alter()
  2261. */
  2262. function drupal_deliver_page($page_callback_result, $default_delivery_callback = NULL) {
  2263. if (!isset($default_delivery_callback) && ($router_item = menu_get_item())) {
  2264. $default_delivery_callback = $router_item['delivery_callback'];
  2265. }
  2266. $delivery_callback = !empty($default_delivery_callback) ? $default_delivery_callback : 'drupal_deliver_html_page';
  2267. // Give modules a chance to alter the delivery callback used, based on
  2268. // request-time context (e.g., HTTP request headers).
  2269. drupal_alter('page_delivery_callback', $delivery_callback);
  2270. if (function_exists($delivery_callback)) {
  2271. $delivery_callback($page_callback_result);
  2272. }
  2273. else {
  2274. // If a delivery callback is specified, but doesn't exist as a function,
  2275. // something is wrong, but don't print anything, since it's not known
  2276. // what format the response needs to be in.
  2277. watchdog('delivery callback not found', 'callback %callback not found: %q.', array('%callback' => $delivery_callback, '%q' => $_GET['q']), WATCHDOG_ERROR);
  2278. }
  2279. }
  2280. /**
  2281. * Packages and sends the result of a page callback to the browser as HTML.
  2282. *
  2283. * @param $page_callback_result
  2284. * The result of a page callback. Can be one of:
  2285. * - NULL: to indicate no content.
  2286. * - An integer menu status constant: to indicate an error condition.
  2287. * - A string of HTML content.
  2288. * - A renderable array of content.
  2289. *
  2290. * @see drupal_deliver_page()
  2291. */
  2292. function drupal_deliver_html_page($page_callback_result) {
  2293. // Emit the correct charset HTTP header, but not if the page callback
  2294. // result is NULL, since that likely indicates that it printed something
  2295. // in which case, no further headers may be sent, and not if code running
  2296. // for this page request has already set the content type header.
  2297. if (isset($page_callback_result) && is_null(drupal_get_http_header('Content-Type'))) {
  2298. drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
  2299. }
  2300. // Send appropriate HTTP-Header for browsers and search engines.
  2301. global $language;
  2302. drupal_add_http_header('Content-Language', $language->language);
  2303. // Menu status constants are integers; page content is a string or array.
  2304. if (is_int($page_callback_result)) {
  2305. // @todo: Break these up into separate functions?
  2306. switch ($page_callback_result) {
  2307. case MENU_NOT_FOUND:
  2308. // Print a 404 page.
  2309. drupal_add_http_header('Status', '404 Not Found');
  2310. watchdog('page not found', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
  2311. // Check for and return a fast 404 page if configured.
  2312. drupal_fast_404();
  2313. // Keep old path for reference, and to allow forms to redirect to it.
  2314. if (!isset($_GET['destination'])) {
  2315. $_GET['destination'] = $_GET['q'];
  2316. }
  2317. $path = drupal_get_normal_path(variable_get('site_404', ''));
  2318. if ($path && $path != $_GET['q']) {
  2319. // Custom 404 handler. Set the active item in case there are tabs to
  2320. // display, or other dependencies on the path.
  2321. menu_set_active_item($path);
  2322. $return = menu_execute_active_handler($path, FALSE);
  2323. }
  2324. if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
  2325. // Standard 404 handler.
  2326. drupal_set_title(t('Page not found'));
  2327. $return = t('The requested page "@path" could not be found.', array('@path' => request_uri()));
  2328. }
  2329. drupal_set_page_content($return);
  2330. $page = element_info('page');
  2331. print drupal_render_page($page);
  2332. break;
  2333. case MENU_ACCESS_DENIED:
  2334. // Print a 403 page.
  2335. drupal_add_http_header('Status', '403 Forbidden');
  2336. watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
  2337. // Keep old path for reference, and to allow forms to redirect to it.
  2338. if (!isset($_GET['destination'])) {
  2339. $_GET['destination'] = $_GET['q'];
  2340. }
  2341. $path = drupal_get_normal_path(variable_get('site_403', ''));
  2342. if ($path && $path != $_GET['q']) {
  2343. // Custom 403 handler. Set the active item in case there are tabs to
  2344. // display or other dependencies on the path.
  2345. menu_set_active_item($path);
  2346. $return = menu_execute_active_handler($path, FALSE);
  2347. }
  2348. if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
  2349. // Standard 403 handler.
  2350. drupal_set_title(t('Access denied'));
  2351. $return = t('You are not authorized to access this page.');
  2352. }
  2353. print drupal_render_page($return);
  2354. break;
  2355. case MENU_SITE_OFFLINE:
  2356. // Print a 503 page.
  2357. drupal_maintenance_theme();
  2358. drupal_add_http_header('Status', '503 Service unavailable');
  2359. drupal_set_title(t('Site under maintenance'));
  2360. print theme('maintenance_page', array('content' => filter_xss_admin(variable_get('maintenance_mode_message',
  2361. t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))))));
  2362. break;
  2363. }
  2364. }
  2365. elseif (isset($page_callback_result)) {
  2366. // Print anything besides a menu constant, assuming it's not NULL or
  2367. // undefined.
  2368. print drupal_render_page($page_callback_result);
  2369. }
  2370. // Perform end-of-request tasks.
  2371. drupal_page_footer();
  2372. }
  2373. /**
  2374. * Performs end-of-request tasks.
  2375. *
  2376. * This function sets the page cache if appropriate, and allows modules to
  2377. * react to the closing of the page by calling hook_exit().
  2378. */
  2379. function drupal_page_footer() {
  2380. global $user;
  2381. module_invoke_all('exit');
  2382. // Commit the user session, if needed.
  2383. drupal_session_commit();
  2384. if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
  2385. drupal_serve_page_from_cache($cache);
  2386. }
  2387. else {
  2388. ob_flush();
  2389. }
  2390. _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
  2391. drupal_cache_system_paths();
  2392. module_implements_write_cache();
  2393. system_run_automated_cron();
  2394. }
  2395. /**
  2396. * Performs end-of-request tasks.
  2397. *
  2398. * In some cases page requests need to end without calling drupal_page_footer().
  2399. * In these cases, call drupal_exit() instead. There should rarely be a reason
  2400. * to call exit instead of drupal_exit();
  2401. *
  2402. * @param $destination
  2403. * If this function is called from drupal_goto(), then this argument
  2404. * will be a fully-qualified URL that is the destination of the redirect.
  2405. * This should be passed along to hook_exit() implementations.
  2406. */
  2407. function drupal_exit($destination = NULL) {
  2408. if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL) {
  2409. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
  2410. module_invoke_all('exit', $destination);
  2411. }
  2412. drupal_session_commit();
  2413. }
  2414. exit;
  2415. }
  2416. /**
  2417. * Forms an associative array from a linear array.
  2418. *
  2419. * This function walks through the provided array and constructs an associative
  2420. * array out of it. The keys of the resulting array will be the values of the
  2421. * input array. The values will be the same as the keys unless a function is
  2422. * specified, in which case the output of the function is used for the values
  2423. * instead.
  2424. *
  2425. * @param $array
  2426. * A linear array.
  2427. * @param $function
  2428. * A name of a function to apply to all values before output.
  2429. *
  2430. * @return
  2431. * An associative array.
  2432. */
  2433. function drupal_map_assoc($array, $function = NULL) {
  2434. // array_combine() fails with empty arrays:
  2435. // http://bugs.php.net/bug.php?id=34857.
  2436. $array = !empty($array) ? array_combine($array, $array) : array();
  2437. if (is_callable($function)) {
  2438. $array = array_map($function, $array);
  2439. }
  2440. return $array;
  2441. }
  2442. /**
  2443. * Attempts to set the PHP maximum execution time.
  2444. *
  2445. * This function is a wrapper around the PHP function set_time_limit().
  2446. * When called, set_time_limit() restarts the timeout counter from zero.
  2447. * In other words, if the timeout is the default 30 seconds, and 25 seconds
  2448. * into script execution a call such as set_time_limit(20) is made, the
  2449. * script will run for a total of 45 seconds before timing out.
  2450. *
  2451. * It also means that it is possible to decrease the total time limit if
  2452. * the sum of the new time limit and the current time spent running the
  2453. * script is inferior to the original time limit. It is inherent to the way
  2454. * set_time_limit() works, it should rather be called with an appropriate
  2455. * value every time you need to allocate a certain amount of time
  2456. * to execute a task than only once at the beginning of the script.
  2457. *
  2458. * Before calling set_time_limit(), we check if this function is available
  2459. * because it could be disabled by the server administrator. We also hide all
  2460. * the errors that could occur when calling set_time_limit(), because it is
  2461. * not possible to reliably ensure that PHP or a security extension will
  2462. * not issue a warning/error if they prevent the use of this function.
  2463. *
  2464. * @param $time_limit
  2465. * An integer specifying the new time limit, in seconds. A value of 0
  2466. * indicates unlimited execution time.
  2467. *
  2468. * @ingroup php_wrappers
  2469. */
  2470. function drupal_set_time_limit($time_limit) {
  2471. if (function_exists('set_time_limit')) {
  2472. @set_time_limit($time_limit);
  2473. }
  2474. }
  2475. /**
  2476. * Returns the path to a system item (module, theme, etc.).
  2477. *
  2478. * @param $type
  2479. * The type of the item (i.e. theme, theme_engine, module, profile).
  2480. * @param $name
  2481. * The name of the item for which the path is requested.
  2482. *
  2483. * @return
  2484. * The path to the requested item.
  2485. */
  2486. function drupal_get_path($type, $name) {
  2487. return dirname(drupal_get_filename($type, $name));
  2488. }
  2489. /**
  2490. * Returns the base URL path (i.e., directory) of the Drupal installation.
  2491. *
  2492. * base_path() adds a "/" to the beginning and end of the returned path if the
  2493. * path is not empty. At the very least, this will return "/".
  2494. *
  2495. * Examples:
  2496. * - http://example.com returns "/" because the path is empty.
  2497. * - http://example.com/drupal/folder returns "/drupal/folder/".
  2498. */
  2499. function base_path() {
  2500. return $GLOBALS['base_path'];
  2501. }
  2502. /**
  2503. * Adds a LINK tag with a distinct 'rel' attribute to the page's HEAD.
  2504. *
  2505. * This function can be called as long the HTML header hasn't been sent, which
  2506. * on normal pages is up through the preprocess step of theme('html'). Adding
  2507. * a link will overwrite a prior link with the exact same 'rel' and 'href'
  2508. * attributes.
  2509. *
  2510. * @param $attributes
  2511. * Associative array of element attributes including 'href' and 'rel'.
  2512. * @param $header
  2513. * Optional flag to determine if a HTTP 'Link:' header should be sent.
  2514. */
  2515. function drupal_add_html_head_link($attributes, $header = FALSE) {
  2516. $element = array(
  2517. '#tag' => 'link',
  2518. '#attributes' => $attributes,
  2519. );
  2520. $href = $attributes['href'];
  2521. if ($header) {
  2522. // Also add a HTTP header "Link:".
  2523. $href = '<' . check_plain($attributes['href']) . '>;';
  2524. unset($attributes['href']);
  2525. $element['#attached']['drupal_add_http_header'][] = array('Link', $href . drupal_http_header_attributes($attributes), TRUE);
  2526. }
  2527. drupal_add_html_head($element, 'drupal_add_html_head_link:' . $attributes['rel'] . ':' . $href);
  2528. }
  2529. /**
  2530. * Adds a cascading stylesheet to the stylesheet queue.
  2531. *
  2532. * Calling drupal_static_reset('drupal_add_css') will clear all cascading
  2533. * stylesheets added so far.
  2534. *
  2535. * If CSS aggregation/compression is enabled, all cascading style sheets added
  2536. * with $options['preprocess'] set to TRUE will be merged into one aggregate
  2537. * file and compressed by removing all extraneous white space.
  2538. * Preprocessed inline stylesheets will not be aggregated into this single file;
  2539. * instead, they are just compressed upon output on the page. Externally hosted
  2540. * stylesheets are never aggregated or compressed.
  2541. *
  2542. * The reason for aggregating the files is outlined quite thoroughly here:
  2543. * http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
  2544. * to request overhead, one bigger file just loads faster than two smaller ones
  2545. * half its size."
  2546. *
  2547. * $options['preprocess'] should be only set to TRUE when a file is required for
  2548. * all typical visitors and most pages of a site. It is critical that all
  2549. * preprocessed files are added unconditionally on every page, even if the
  2550. * files do not happen to be needed on a page. This is normally done by calling
  2551. * drupal_add_css() in a hook_init() implementation.
  2552. *
  2553. * Non-preprocessed files should only be added to the page when they are
  2554. * actually needed.
  2555. *
  2556. * @param $data
  2557. * (optional) The stylesheet data to be added, depending on what is passed
  2558. * through to the $options['type'] parameter:
  2559. * - 'file': The path to the CSS file relative to the base_path(), or a
  2560. * stream wrapper URI. For example: "modules/devel/devel.css" or
  2561. * "public://generated_css/stylesheet_1.css". Note that Modules should
  2562. * always prefix the names of their CSS files with the module name; for
  2563. * example, system-menus.css rather than simply menus.css. Themes can
  2564. * override module-supplied CSS files based on their filenames, and this
  2565. * prefixing helps prevent confusing name collisions for theme developers.
  2566. * See drupal_get_css() where the overrides are performed. Also, if the
  2567. * direction of the current language is right-to-left (Hebrew, Arabic,
  2568. * etc.), the function will also look for an RTL CSS file and append it to
  2569. * the list. The name of this file should have an '-rtl.css' suffix. For
  2570. * example, a CSS file called 'mymodule-name.css' will have a
  2571. * 'mymodule-name-rtl.css' file added to the list, if exists in the same
  2572. * directory. This CSS file should contain overrides for properties which
  2573. * should be reversed or otherwise different in a right-to-left display.
  2574. * - 'inline': A string of CSS that should be placed in the given scope. Note
  2575. * that it is better practice to use 'file' stylesheets, rather than
  2576. * 'inline', as the CSS would then be aggregated and cached.
  2577. * - 'external': The absolute path to an external CSS file that is not hosted
  2578. * on the local server. These files will not be aggregated if CSS
  2579. * aggregation is enabled.
  2580. * @param $options
  2581. * (optional) A string defining the 'type' of CSS that is being added in the
  2582. * $data parameter ('file', 'inline', or 'external'), or an array which can
  2583. * have any or all of the following keys:
  2584. * - 'type': The type of stylesheet being added. Available options are 'file',
  2585. * 'inline' or 'external'. Defaults to 'file'.
  2586. * - 'basename': Force a basename for the file being added. Modules are
  2587. * expected to use stylesheets with unique filenames, but integration of
  2588. * external libraries may make this impossible. The basename of
  2589. * 'modules/node/node.css' is 'node.css'. If the external library "node.js"
  2590. * ships with a 'node.css', then a different, unique basename would be
  2591. * 'node.js.css'.
  2592. * - 'group': A number identifying the group in which to add the stylesheet.
  2593. * Available constants are:
  2594. * - CSS_SYSTEM: Any system-layer CSS.
  2595. * - CSS_DEFAULT: Any module-layer CSS.
  2596. * - CSS_THEME: Any theme-layer CSS.
  2597. * The group number serves as a weight: the markup for loading a stylesheet
  2598. * within a lower weight group is output to the page before the markup for
  2599. * loading a stylesheet within a higher weight group, so CSS within higher
  2600. * weight groups take precendence over CSS within lower weight groups.
  2601. * - 'every_page': For optimal front-end performance when aggregation is
  2602. * enabled, this should be set to TRUE if the stylesheet is present on every
  2603. * page of the website for users for whom it is present at all. This
  2604. * defaults to FALSE. It is set to TRUE for stylesheets added via module and
  2605. * theme .info files. Modules that add stylesheets within hook_init()
  2606. * implementations, or from other code that ensures that the stylesheet is
  2607. * added to all website pages, should also set this flag to TRUE. All
  2608. * stylesheets within the same group that have the 'every_page' flag set to
  2609. * TRUE and do not have 'preprocess' set to FALSE are aggregated together
  2610. * into a single aggregate file, and that aggregate file can be reused
  2611. * across a user's entire site visit, leading to faster navigation between
  2612. * pages. However, stylesheets that are only needed on pages less frequently
  2613. * visited, can be added by code that only runs for those particular pages,
  2614. * and that code should not set the 'every_page' flag. This minimizes the
  2615. * size of the aggregate file that the user needs to download when first
  2616. * visiting the website. Stylesheets without the 'every_page' flag are
  2617. * aggregated into a separate aggregate file. This other aggregate file is
  2618. * likely to change from page to page, and each new aggregate file needs to
  2619. * be downloaded when first encountered, so it should be kept relatively
  2620. * small by ensuring that most commonly needed stylesheets are added to
  2621. * every page.
  2622. * - 'weight': The weight of the stylesheet specifies the order in which the
  2623. * CSS will appear relative to other stylesheets with the same group and
  2624. * 'every_page' flag. The exact ordering of stylesheets is as follows:
  2625. * - First by group.
  2626. * - Then by the 'every_page' flag, with TRUE coming before FALSE.
  2627. * - Then by weight.
  2628. * - Then by the order in which the CSS was added. For example, all else
  2629. * being the same, a stylesheet added by a call to drupal_add_css() that
  2630. * happened later in the page request gets added to the page after one for
  2631. * which drupal_add_css() happened earlier in the page request.
  2632. * - 'media': The media type for the stylesheet, e.g., all, print, screen.
  2633. * Defaults to 'all'.
  2634. * - 'preprocess': If TRUE and CSS aggregation/compression is enabled, the
  2635. * styles will be aggregated and compressed. Defaults to TRUE.
  2636. * - 'browsers': An array containing information specifying which browsers
  2637. * should load the CSS item. See drupal_pre_render_conditional_comments()
  2638. * for details.
  2639. *
  2640. * @return
  2641. * An array of queued cascading stylesheets.
  2642. *
  2643. * @see drupal_get_css()
  2644. */
  2645. function drupal_add_css($data = NULL, $options = NULL) {
  2646. $css = &drupal_static(__FUNCTION__, array());
  2647. // Construct the options, taking the defaults into consideration.
  2648. if (isset($options)) {
  2649. if (!is_array($options)) {
  2650. $options = array('type' => $options);
  2651. }
  2652. }
  2653. else {
  2654. $options = array();
  2655. }
  2656. // Create an array of CSS files for each media type first, since each type needs to be served
  2657. // to the browser differently.
  2658. if (isset($data)) {
  2659. $options += array(
  2660. 'type' => 'file',
  2661. 'group' => CSS_DEFAULT,
  2662. 'weight' => 0,
  2663. 'every_page' => FALSE,
  2664. 'media' => 'all',
  2665. 'preprocess' => TRUE,
  2666. 'data' => $data,
  2667. 'browsers' => array(),
  2668. );
  2669. $options['browsers'] += array(
  2670. 'IE' => TRUE,
  2671. '!IE' => TRUE,
  2672. );
  2673. // Files with a query string cannot be preprocessed.
  2674. if ($options['type'] === 'file' && $options['preprocess'] && strpos($options['data'], '?') !== FALSE) {
  2675. $options['preprocess'] = FALSE;
  2676. }
  2677. // Always add a tiny value to the weight, to conserve the insertion order.
  2678. $options['weight'] += count($css) / 1000;
  2679. // Add the data to the CSS array depending on the type.
  2680. switch ($options['type']) {
  2681. case 'inline':
  2682. // For inline stylesheets, we don't want to use the $data as the array
  2683. // key as $data could be a very long string of CSS.
  2684. $css[] = $options;
  2685. break;
  2686. default:
  2687. // Local and external files must keep their name as the associative key
  2688. // so the same CSS file is not be added twice.
  2689. $css[$data] = $options;
  2690. }
  2691. }
  2692. return $css;
  2693. }
  2694. /**
  2695. * Returns a themed representation of all stylesheets to attach to the page.
  2696. *
  2697. * It loads the CSS in order, with 'module' first, then 'theme' afterwards.
  2698. * This ensures proper cascading of styles so themes can easily override
  2699. * module styles through CSS selectors.
  2700. *
  2701. * Themes may replace module-defined CSS files by adding a stylesheet with the
  2702. * same filename. For example, themes/bartik/system-menus.css would replace
  2703. * modules/system/system-menus.css. This allows themes to override complete
  2704. * CSS files, rather than specific selectors, when necessary.
  2705. *
  2706. * If the original CSS file is being overridden by a theme, the theme is
  2707. * responsible for supplying an accompanying RTL CSS file to replace the
  2708. * module's.
  2709. *
  2710. * @param $css
  2711. * (optional) An array of CSS files. If no array is provided, the default
  2712. * stylesheets array is used instead.
  2713. * @param $skip_alter
  2714. * (optional) If set to TRUE, this function skips calling drupal_alter() on
  2715. * $css, useful when the calling function passes a $css array that has already
  2716. * been altered.
  2717. *
  2718. * @return
  2719. * A string of XHTML CSS tags.
  2720. *
  2721. * @see drupal_add_css()
  2722. */
  2723. function drupal_get_css($css = NULL, $skip_alter = FALSE) {
  2724. if (!isset($css)) {
  2725. $css = drupal_add_css();
  2726. }
  2727. // Allow modules and themes to alter the CSS items.
  2728. if (!$skip_alter) {
  2729. drupal_alter('css', $css);
  2730. }
  2731. // Sort CSS items, so that they appear in the correct order.
  2732. uasort($css, 'drupal_sort_css_js');
  2733. // Remove the overridden CSS files. Later CSS files override former ones.
  2734. $previous_item = array();
  2735. foreach ($css as $key => $item) {
  2736. if ($item['type'] == 'file') {
  2737. // If defined, force a unique basename for this file.
  2738. $basename = isset($item['basename']) ? $item['basename'] : drupal_basename($item['data']);
  2739. if (isset($previous_item[$basename])) {
  2740. // Remove the previous item that shared the same base name.
  2741. unset($css[$previous_item[$basename]]);
  2742. }
  2743. $previous_item[$basename] = $key;
  2744. }
  2745. }
  2746. // Render the HTML needed to load the CSS.
  2747. $styles = array(
  2748. '#type' => 'styles',
  2749. '#items' => $css,
  2750. );
  2751. // Provide the page with information about the individual CSS files used,
  2752. // information not otherwise available when CSS aggregation is enabled.
  2753. $setting['ajaxPageState']['css'] = array_fill_keys(array_keys($css), 1);
  2754. $styles['#attached']['js'][] = array('type' => 'setting', 'data' => $setting);
  2755. return drupal_render($styles);
  2756. }
  2757. /**
  2758. * Sorts CSS and JavaScript resources.
  2759. *
  2760. * Callback for uasort() within:
  2761. * - drupal_get_css()
  2762. * - drupal_get_js()
  2763. *
  2764. * This sort order helps optimize front-end performance while providing modules
  2765. * and themes with the necessary control for ordering the CSS and JavaScript
  2766. * appearing on a page.
  2767. *
  2768. * @param $a
  2769. * First item for comparison. The compared items should be associative arrays
  2770. * of member items from drupal_add_css() or drupal_add_js().
  2771. * @param $b
  2772. * Second item for comparison.
  2773. *
  2774. * @see drupal_add_css()
  2775. * @see drupal_add_js()
  2776. */
  2777. function drupal_sort_css_js($a, $b) {
  2778. // First order by group, so that, for example, all items in the CSS_SYSTEM
  2779. // group appear before items in the CSS_DEFAULT group, which appear before
  2780. // all items in the CSS_THEME group. Modules may create additional groups by
  2781. // defining their own constants.
  2782. if ($a['group'] < $b['group']) {
  2783. return -1;
  2784. }
  2785. elseif ($a['group'] > $b['group']) {
  2786. return 1;
  2787. }
  2788. // Within a group, order all infrequently needed, page-specific files after
  2789. // common files needed throughout the website. Separating this way allows for
  2790. // the aggregate file generated for all of the common files to be reused
  2791. // across a site visit without being cut by a page using a less common file.
  2792. elseif ($a['every_page'] && !$b['every_page']) {
  2793. return -1;
  2794. }
  2795. elseif (!$a['every_page'] && $b['every_page']) {
  2796. return 1;
  2797. }
  2798. // Finally, order by weight.
  2799. elseif ($a['weight'] < $b['weight']) {
  2800. return -1;
  2801. }
  2802. elseif ($a['weight'] > $b['weight']) {
  2803. return 1;
  2804. }
  2805. else {
  2806. return 0;
  2807. }
  2808. }
  2809. /**
  2810. * Default callback to group CSS items.
  2811. *
  2812. * This function arranges the CSS items that are in the #items property of the
  2813. * styles element into groups. Arranging the CSS items into groups serves two
  2814. * purposes. When aggregation is enabled, files within a group are aggregated
  2815. * into a single file, significantly improving page loading performance by
  2816. * minimizing network traffic overhead. When aggregation is disabled, grouping
  2817. * allows multiple files to be loaded from a single STYLE tag, enabling sites
  2818. * with many modules enabled or a complex theme being used to stay within IE's
  2819. * 31 CSS inclusion tag limit: http://drupal.org/node/228818.
  2820. *
  2821. * This function puts multiple items into the same group if they are groupable
  2822. * and if they are for the same 'media' and 'browsers'. Items of the 'file' type
  2823. * are groupable if their 'preprocess' flag is TRUE, items of the 'inline' type
  2824. * are always groupable, and items of the 'external' type are never groupable.
  2825. * This function also ensures that the process of grouping items does not change
  2826. * their relative order. This requirement may result in multiple groups for the
  2827. * same type, media, and browsers, if needed to accommodate other items in
  2828. * between.
  2829. *
  2830. * @param $css
  2831. * An array of CSS items, as returned by drupal_add_css(), but after
  2832. * alteration performed by drupal_get_css().
  2833. *
  2834. * @return
  2835. * An array of CSS groups. Each group contains the same keys (e.g., 'media',
  2836. * 'data', etc.) as a CSS item from the $css parameter, with the value of
  2837. * each key applying to the group as a whole. Each group also contains an
  2838. * 'items' key, which is the subset of items from $css that are in the group.
  2839. *
  2840. * @see drupal_pre_render_styles()
  2841. * @see system_element_info()
  2842. */
  2843. function drupal_group_css($css) {
  2844. $groups = array();
  2845. // If a group can contain multiple items, we track the information that must
  2846. // be the same for each item in the group, so that when we iterate the next
  2847. // item, we can determine if it can be put into the current group, or if a
  2848. // new group needs to be made for it.
  2849. $current_group_keys = NULL;
  2850. // When creating a new group, we pre-increment $i, so by initializing it to
  2851. // -1, the first group will have index 0.
  2852. $i = -1;
  2853. foreach ($css as $item) {
  2854. // The browsers for which the CSS item needs to be loaded is part of the
  2855. // information that determines when a new group is needed, but the order of
  2856. // keys in the array doesn't matter, and we don't want a new group if all
  2857. // that's different is that order.
  2858. ksort($item['browsers']);
  2859. // If the item can be grouped with other items, set $group_keys to an array
  2860. // of information that must be the same for all items in its group. If the
  2861. // item can't be grouped with other items, set $group_keys to FALSE. We
  2862. // put items into a group that can be aggregated together: whether they will
  2863. // be aggregated is up to the _drupal_css_aggregate() function or an
  2864. // override of that function specified in hook_css_alter(), but regardless
  2865. // of the details of that function, a group represents items that can be
  2866. // aggregated. Since a group may be rendered with a single HTML tag, all
  2867. // items in the group must share the same information that would need to be
  2868. // part of that HTML tag.
  2869. switch ($item['type']) {
  2870. case 'file':
  2871. // Group file items if their 'preprocess' flag is TRUE.
  2872. // Help ensure maximum reuse of aggregate files by only grouping
  2873. // together items that share the same 'group' value and 'every_page'
  2874. // flag. See drupal_add_css() for details about that.
  2875. $group_keys = $item['preprocess'] ? array($item['type'], $item['group'], $item['every_page'], $item['media'], $item['browsers']) : FALSE;
  2876. break;
  2877. case 'inline':
  2878. // Always group inline items.
  2879. $group_keys = array($item['type'], $item['media'], $item['browsers']);
  2880. break;
  2881. case 'external':
  2882. // Do not group external items.
  2883. $group_keys = FALSE;
  2884. break;
  2885. }
  2886. // If the group keys don't match the most recent group we're working with,
  2887. // then a new group must be made.
  2888. if ($group_keys !== $current_group_keys) {
  2889. $i++;
  2890. // Initialize the new group with the same properties as the first item
  2891. // being placed into it. The item's 'data' and 'weight' properties are
  2892. // unique to the item and should not be carried over to the group.
  2893. $groups[$i] = $item;
  2894. unset($groups[$i]['data'], $groups[$i]['weight']);
  2895. $groups[$i]['items'] = array();
  2896. $current_group_keys = $group_keys ? $group_keys : NULL;
  2897. }
  2898. // Add the item to the current group.
  2899. $groups[$i]['items'][] = $item;
  2900. }
  2901. return $groups;
  2902. }
  2903. /**
  2904. * Default callback to aggregate CSS files and inline content.
  2905. *
  2906. * Having the browser load fewer CSS files results in much faster page loads
  2907. * than when it loads many small files. This function aggregates files within
  2908. * the same group into a single file unless the site-wide setting to do so is
  2909. * disabled (commonly the case during site development). To optimize download,
  2910. * it also compresses the aggregate files by removing comments, whitespace, and
  2911. * other unnecessary content. Additionally, this functions aggregates inline
  2912. * content together, regardless of the site-wide aggregation setting.
  2913. *
  2914. * @param $css_groups
  2915. * An array of CSS groups as returned by drupal_group_css(). This function
  2916. * modifies the group's 'data' property for each group that is aggregated.
  2917. *
  2918. * @see drupal_group_css()
  2919. * @see drupal_pre_render_styles()
  2920. * @see system_element_info()
  2921. */
  2922. function drupal_aggregate_css(&$css_groups) {
  2923. $preprocess_css = (variable_get('preprocess_css', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
  2924. // For each group that needs aggregation, aggregate its items.
  2925. foreach ($css_groups as $key => $group) {
  2926. switch ($group['type']) {
  2927. // If a file group can be aggregated into a single file, do so, and set
  2928. // the group's data property to the file path of the aggregate file.
  2929. case 'file':
  2930. if ($group['preprocess'] && $preprocess_css) {
  2931. $css_groups[$key]['data'] = drupal_build_css_cache($group['items']);
  2932. }
  2933. break;
  2934. // Aggregate all inline CSS content into the group's data property.
  2935. case 'inline':
  2936. $css_groups[$key]['data'] = '';
  2937. foreach ($group['items'] as $item) {
  2938. $css_groups[$key]['data'] .= drupal_load_stylesheet_content($item['data'], $item['preprocess']);
  2939. }
  2940. break;
  2941. }
  2942. }
  2943. }
  2944. /**
  2945. * #pre_render callback to add the elements needed for CSS tags to be rendered.
  2946. *
  2947. * For production websites, LINK tags are preferable to STYLE tags with @import
  2948. * statements, because:
  2949. * - They are the standard tag intended for linking to a resource.
  2950. * - On Firefox 2 and perhaps other browsers, CSS files included with @import
  2951. * statements don't get saved when saving the complete web page for offline
  2952. * use: http://drupal.org/node/145218.
  2953. * - On IE, if only LINK tags and no @import statements are used, all the CSS
  2954. * files are downloaded in parallel, resulting in faster page load, but if
  2955. * @import statements are used and span across multiple STYLE tags, all the
  2956. * ones from one STYLE tag must be downloaded before downloading begins for
  2957. * the next STYLE tag. Furthermore, IE7 does not support media declaration on
  2958. * the @import statement, so multiple STYLE tags must be used when different
  2959. * files are for different media types. Non-IE browsers always download in
  2960. * parallel, so this is an IE-specific performance quirk:
  2961. * http://www.stevesouders.com/blog/2009/04/09/dont-use-import/.
  2962. *
  2963. * However, IE has an annoying limit of 31 total CSS inclusion tags
  2964. * (http://drupal.org/node/228818) and LINK tags are limited to one file per
  2965. * tag, whereas STYLE tags can contain multiple @import statements allowing
  2966. * multiple files to be loaded per tag. When CSS aggregation is disabled, a
  2967. * Drupal site can easily have more than 31 CSS files that need to be loaded, so
  2968. * using LINK tags exclusively would result in a site that would display
  2969. * incorrectly in IE. Depending on different needs, different strategies can be
  2970. * employed to decide when to use LINK tags and when to use STYLE tags.
  2971. *
  2972. * The strategy employed by this function is to use LINK tags for all aggregate
  2973. * files and for all files that cannot be aggregated (e.g., if 'preprocess' is
  2974. * set to FALSE or the type is 'external'), and to use STYLE tags for groups
  2975. * of files that could be aggregated together but aren't (e.g., if the site-wide
  2976. * aggregation setting is disabled). This results in all LINK tags when
  2977. * aggregation is enabled, a guarantee that as many or only slightly more tags
  2978. * are used with aggregation disabled than enabled (so that if the limit were to
  2979. * be crossed with aggregation enabled, the site developer would also notice the
  2980. * problem while aggregation is disabled), and an easy way for a developer to
  2981. * view HTML source while aggregation is disabled and know what files will be
  2982. * aggregated together when aggregation becomes enabled.
  2983. *
  2984. * This function evaluates the aggregation enabled/disabled condition on a group
  2985. * by group basis by testing whether an aggregate file has been made for the
  2986. * group rather than by testing the site-wide aggregation setting. This allows
  2987. * this function to work correctly even if modules have implemented custom
  2988. * logic for grouping and aggregating files.
  2989. *
  2990. * @param $element
  2991. * A render array containing:
  2992. * - '#items': The CSS items as returned by drupal_add_css() and altered by
  2993. * drupal_get_css().
  2994. * - '#group_callback': A function to call to group #items to enable the use
  2995. * of fewer tags by aggregating files and/or using multiple @import
  2996. * statements within a single tag.
  2997. * - '#aggregate_callback': A function to call to aggregate the items within
  2998. * the groups arranged by the #group_callback function.
  2999. *
  3000. * @return
  3001. * A render array that will render to a string of XHTML CSS tags.
  3002. *
  3003. * @see drupal_get_css()
  3004. */
  3005. function drupal_pre_render_styles($elements) {
  3006. // Group and aggregate the items.
  3007. if (isset($elements['#group_callback'])) {
  3008. $elements['#groups'] = $elements['#group_callback']($elements['#items']);
  3009. }
  3010. if (isset($elements['#aggregate_callback'])) {
  3011. $elements['#aggregate_callback']($elements['#groups']);
  3012. }
  3013. // A dummy query-string is added to filenames, to gain control over
  3014. // browser-caching. The string changes on every update or full cache
  3015. // flush, forcing browsers to load a new copy of the files, as the
  3016. // URL changed.
  3017. $query_string = variable_get('css_js_query_string', '0');
  3018. // For inline CSS to validate as XHTML, all CSS containing XHTML needs to be
  3019. // wrapped in CDATA. To make that backwards compatible with HTML 4, we need to
  3020. // comment out the CDATA-tag.
  3021. $embed_prefix = "\n<!--/*--><![CDATA[/*><!--*/\n";
  3022. $embed_suffix = "\n/*]]>*/-->\n";
  3023. // Defaults for LINK and STYLE elements.
  3024. $link_element_defaults = array(
  3025. '#type' => 'html_tag',
  3026. '#tag' => 'link',
  3027. '#attributes' => array(
  3028. 'type' => 'text/css',
  3029. 'rel' => 'stylesheet',
  3030. ),
  3031. );
  3032. $style_element_defaults = array(
  3033. '#type' => 'html_tag',
  3034. '#tag' => 'style',
  3035. '#attributes' => array(
  3036. 'type' => 'text/css',
  3037. ),
  3038. );
  3039. // Loop through each group.
  3040. foreach ($elements['#groups'] as $group) {
  3041. switch ($group['type']) {
  3042. // For file items, there are three possibilites.
  3043. // - The group has been aggregated: in this case, output a LINK tag for
  3044. // the aggregate file.
  3045. // - The group can be aggregated but has not been (most likely because
  3046. // the site administrator disabled the site-wide setting): in this case,
  3047. // output as few STYLE tags for the group as possible, using @import
  3048. // statement for each file in the group. This enables us to stay within
  3049. // IE's limit of 31 total CSS inclusion tags.
  3050. // - The group contains items not eligible for aggregation (their
  3051. // 'preprocess' flag has been set to FALSE): in this case, output a LINK
  3052. // tag for each file.
  3053. case 'file':
  3054. // The group has been aggregated into a single file: output a LINK tag
  3055. // for the aggregate file.
  3056. if (isset($group['data'])) {
  3057. $element = $link_element_defaults;
  3058. $element['#attributes']['href'] = file_create_url($group['data']);
  3059. $element['#attributes']['media'] = $group['media'];
  3060. $element['#browsers'] = $group['browsers'];
  3061. $elements[] = $element;
  3062. }
  3063. // The group can be aggregated, but hasn't been: combine multiple items
  3064. // into as few STYLE tags as possible.
  3065. elseif ($group['preprocess']) {
  3066. $import = array();
  3067. foreach ($group['items'] as $item) {
  3068. // A theme's .info file may have an entry for a file that doesn't
  3069. // exist as a way of overriding a module or base theme CSS file from
  3070. // being added to the page. Normally, file_exists() calls that need
  3071. // to run for every page request should be minimized, but this one
  3072. // is okay, because it only runs when CSS aggregation is disabled.
  3073. // On a server under heavy enough load that file_exists() calls need
  3074. // to be minimized, CSS aggregation should be enabled, in which case
  3075. // this code is not run. When aggregation is enabled,
  3076. // drupal_load_stylesheet() checks file_exists(), but only when
  3077. // building the aggregate file, which is then reused for many page
  3078. // requests.
  3079. if (file_exists($item['data'])) {
  3080. // The dummy query string needs to be added to the URL to control
  3081. // browser-caching. IE7 does not support a media type on the
  3082. // @import statement, so we instead specify the media for the
  3083. // group on the STYLE tag.
  3084. $import[] = '@import url("' . check_plain(file_create_url($item['data']) . '?' . $query_string) . '");';
  3085. }
  3086. }
  3087. // In addition to IE's limit of 31 total CSS inclusion tags, it also
  3088. // has a limit of 31 @import statements per STYLE tag.
  3089. while (!empty($import)) {
  3090. $import_batch = array_slice($import, 0, 31);
  3091. $import = array_slice($import, 31);
  3092. $element = $style_element_defaults;
  3093. $element['#value'] = implode("\n", $import_batch);
  3094. $element['#attributes']['media'] = $group['media'];
  3095. $element['#browsers'] = $group['browsers'];
  3096. $elements[] = $element;
  3097. }
  3098. }
  3099. // The group contains items ineligible for aggregation: output a LINK
  3100. // tag for each file.
  3101. else {
  3102. foreach ($group['items'] as $item) {
  3103. $element = $link_element_defaults;
  3104. // We do not check file_exists() here, because this code runs for
  3105. // files whose 'preprocess' is set to FALSE, and therefore, even
  3106. // when aggregation is enabled, and we want to avoid needlessly
  3107. // taxing a server that may be under heavy load. The file_exists()
  3108. // performed above for files whose 'preprocess' is TRUE is done for
  3109. // the benefit of theme .info files, but code that deals with files
  3110. // whose 'preprocess' is FALSE is responsible for ensuring the file
  3111. // exists.
  3112. // The dummy query string needs to be added to the URL to control
  3113. // browser-caching.
  3114. $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
  3115. $element['#attributes']['href'] = file_create_url($item['data']) . $query_string_separator . $query_string;
  3116. $element['#attributes']['media'] = $item['media'];
  3117. $element['#browsers'] = $group['browsers'];
  3118. $elements[] = $element;
  3119. }
  3120. }
  3121. break;
  3122. // For inline content, the 'data' property contains the CSS content. If
  3123. // the group's 'data' property is set, then output it in a single STYLE
  3124. // tag. Otherwise, output a separate STYLE tag for each item.
  3125. case 'inline':
  3126. if (isset($group['data'])) {
  3127. $element = $style_element_defaults;
  3128. $element['#value'] = $group['data'];
  3129. $element['#value_prefix'] = $embed_prefix;
  3130. $element['#value_suffix'] = $embed_suffix;
  3131. $element['#attributes']['media'] = $group['media'];
  3132. $element['#browsers'] = $group['browsers'];
  3133. $elements[] = $element;
  3134. }
  3135. else {
  3136. foreach ($group['items'] as $item) {
  3137. $element = $style_element_defaults;
  3138. $element['#value'] = $item['data'];
  3139. $element['#value_prefix'] = $embed_prefix;
  3140. $element['#value_suffix'] = $embed_suffix;
  3141. $element['#attributes']['media'] = $item['media'];
  3142. $element['#browsers'] = $group['browsers'];
  3143. $elements[] = $element;
  3144. }
  3145. }
  3146. break;
  3147. // Output a LINK tag for each external item. The item's 'data' property
  3148. // contains the full URL.
  3149. case 'external':
  3150. foreach ($group['items'] as $item) {
  3151. $element = $link_element_defaults;
  3152. $element['#attributes']['href'] = $item['data'];
  3153. $element['#attributes']['media'] = $item['media'];
  3154. $element['#browsers'] = $group['browsers'];
  3155. $elements[] = $element;
  3156. }
  3157. break;
  3158. }
  3159. }
  3160. return $elements;
  3161. }
  3162. /**
  3163. * Aggregates and optimizes CSS files into a cache file in the files directory.
  3164. *
  3165. * The file name for the CSS cache file is generated from the hash of the
  3166. * aggregated contents of the files in $css. This forces proxies and browsers
  3167. * to download new CSS when the CSS changes.
  3168. *
  3169. * The cache file name is retrieved on a page load via a lookup variable that
  3170. * contains an associative array. The array key is the hash of the file names
  3171. * in $css while the value is the cache file name. The cache file is generated
  3172. * in two cases. First, if there is no file name value for the key, which will
  3173. * happen if a new file name has been added to $css or after the lookup
  3174. * variable is emptied to force a rebuild of the cache. Second, the cache file
  3175. * is generated if it is missing on disk. Old cache files are not deleted
  3176. * immediately when the lookup variable is emptied, but are deleted after a set
  3177. * period by drupal_delete_file_if_stale(). This ensures that files referenced
  3178. * by a cached page will still be available.
  3179. *
  3180. * @param $css
  3181. * An array of CSS files to aggregate and compress into one file.
  3182. *
  3183. * @return
  3184. * The URI of the CSS cache file, or FALSE if the file could not be saved.
  3185. */
  3186. function drupal_build_css_cache($css) {
  3187. $data = '';
  3188. $uri = '';
  3189. $map = variable_get('drupal_css_cache_files', array());
  3190. $key = hash('sha256', serialize($css));
  3191. if (isset($map[$key])) {
  3192. $uri = $map[$key];
  3193. }
  3194. if (empty($uri) || !file_exists($uri)) {
  3195. // Build aggregate CSS file.
  3196. foreach ($css as $stylesheet) {
  3197. // Only 'file' stylesheets can be aggregated.
  3198. if ($stylesheet['type'] == 'file') {
  3199. $contents = drupal_load_stylesheet($stylesheet['data'], TRUE);
  3200. // Build the base URL of this CSS file: start with the full URL.
  3201. $css_base_url = file_create_url($stylesheet['data']);
  3202. // Move to the parent.
  3203. $css_base_url = substr($css_base_url, 0, strrpos($css_base_url, '/'));
  3204. // Simplify to a relative URL if the stylesheet URL starts with the
  3205. // base URL of the website.
  3206. if (substr($css_base_url, 0, strlen($GLOBALS['base_root'])) == $GLOBALS['base_root']) {
  3207. $css_base_url = substr($css_base_url, strlen($GLOBALS['base_root']));
  3208. }
  3209. _drupal_build_css_path(NULL, $css_base_url . '/');
  3210. // Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
  3211. $data .= preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);
  3212. }
  3213. }
  3214. // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
  3215. // @import rules must proceed any other style, so we move those to the top.
  3216. $regexp = '/@import[^;]+;/i';
  3217. preg_match_all($regexp, $data, $matches);
  3218. $data = preg_replace($regexp, '', $data);
  3219. $data = implode('', $matches[0]) . $data;
  3220. // Prefix filename to prevent blocking by firewalls which reject files
  3221. // starting with "ad*".
  3222. $filename = 'css_' . drupal_hash_base64($data) . '.css';
  3223. // Create the css/ within the files folder.
  3224. $csspath = 'public://css';
  3225. $uri = $csspath . '/' . $filename;
  3226. // Create the CSS file.
  3227. file_prepare_directory($csspath, FILE_CREATE_DIRECTORY);
  3228. if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
  3229. return FALSE;
  3230. }
  3231. // If CSS gzip compression is enabled, clean URLs are enabled (which means
  3232. // that rewrite rules are working) and the zlib extension is available then
  3233. // create a gzipped version of this file. This file is served conditionally
  3234. // to browsers that accept gzip using .htaccess rules.
  3235. if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
  3236. if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
  3237. return FALSE;
  3238. }
  3239. }
  3240. // Save the updated map.
  3241. $map[$key] = $uri;
  3242. variable_set('drupal_css_cache_files', $map);
  3243. }
  3244. return $uri;
  3245. }
  3246. /**
  3247. * Prefixes all paths within a CSS file for drupal_build_css_cache().
  3248. */
  3249. function _drupal_build_css_path($matches, $base = NULL) {
  3250. $_base = &drupal_static(__FUNCTION__);
  3251. // Store base path for preg_replace_callback.
  3252. if (isset($base)) {
  3253. $_base = $base;
  3254. }
  3255. // Prefix with base and remove '../' segments where possible.
  3256. $path = $_base . $matches[1];
  3257. $last = '';
  3258. while ($path != $last) {
  3259. $last = $path;
  3260. $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
  3261. }
  3262. return 'url(' . $path . ')';
  3263. }
  3264. /**
  3265. * Loads the stylesheet and resolves all @import commands.
  3266. *
  3267. * Loads a stylesheet and replaces @import commands with the contents of the
  3268. * imported file. Use this instead of file_get_contents when processing
  3269. * stylesheets.
  3270. *
  3271. * The returned contents are compressed removing white space and comments only
  3272. * when CSS aggregation is enabled. This optimization will not apply for
  3273. * color.module enabled themes with CSS aggregation turned off.
  3274. *
  3275. * @param $file
  3276. * Name of the stylesheet to be processed.
  3277. * @param $optimize
  3278. * Defines if CSS contents should be compressed or not.
  3279. * @param $reset_basepath
  3280. * Used internally to facilitate recursive resolution of @import commands.
  3281. *
  3282. * @return
  3283. * Contents of the stylesheet, including any resolved @import commands.
  3284. */
  3285. function drupal_load_stylesheet($file, $optimize = NULL, $reset_basepath = TRUE) {
  3286. // These statics are not cache variables, so we don't use drupal_static().
  3287. static $_optimize, $basepath;
  3288. if ($reset_basepath) {
  3289. $basepath = '';
  3290. }
  3291. // Store the value of $optimize for preg_replace_callback with nested
  3292. // @import loops.
  3293. if (isset($optimize)) {
  3294. $_optimize = $optimize;
  3295. }
  3296. // Stylesheets are relative one to each other. Start by adding a base path
  3297. // prefix provided by the parent stylesheet (if necessary).
  3298. if ($basepath && !file_uri_scheme($file)) {
  3299. $file = $basepath . '/' . $file;
  3300. }
  3301. $basepath = dirname($file);
  3302. // Load the CSS stylesheet. We suppress errors because themes may specify
  3303. // stylesheets in their .info file that don't exist in the theme's path,
  3304. // but are merely there to disable certain module CSS files.
  3305. if ($contents = @file_get_contents($file)) {
  3306. // Return the processed stylesheet.
  3307. return drupal_load_stylesheet_content($contents, $_optimize);
  3308. }
  3309. return '';
  3310. }
  3311. /**
  3312. * Processes the contents of a stylesheet for aggregation.
  3313. *
  3314. * @param $contents
  3315. * The contents of the stylesheet.
  3316. * @param $optimize
  3317. * (optional) Boolean whether CSS contents should be minified. Defaults to
  3318. * FALSE.
  3319. *
  3320. * @return
  3321. * Contents of the stylesheet including the imported stylesheets.
  3322. */
  3323. function drupal_load_stylesheet_content($contents, $optimize = FALSE) {
  3324. // Remove multiple charset declarations for standards compliance (and fixing Safari problems).
  3325. $contents = preg_replace('/^@charset\s+[\'"](\S*)\b[\'"];/i', '', $contents);
  3326. if ($optimize) {
  3327. // Perform some safe CSS optimizations.
  3328. // Regexp to match comment blocks.
  3329. $comment = '/\*[^*]*\*+(?:[^/*][^*]*\*+)*/';
  3330. // Regexp to match double quoted strings.
  3331. $double_quot = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
  3332. // Regexp to match single quoted strings.
  3333. $single_quot = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'";
  3334. // Strip all comment blocks, but keep double/single quoted strings.
  3335. $contents = preg_replace(
  3336. "<($double_quot|$single_quot)|$comment>Ss",
  3337. "$1",
  3338. $contents
  3339. );
  3340. // Remove certain whitespace.
  3341. // There are different conditions for removing leading and trailing
  3342. // whitespace.
  3343. // @see http://php.net/manual/en/regexp.reference.subpatterns.php
  3344. $contents = preg_replace('<
  3345. # Strip leading and trailing whitespace.
  3346. \s*([@{};,])\s*
  3347. # Strip only leading whitespace from:
  3348. # - Closing parenthesis: Retain "@media (bar) and foo".
  3349. | \s+([\)])
  3350. # Strip only trailing whitespace from:
  3351. # - Opening parenthesis: Retain "@media (bar) and foo".
  3352. # - Colon: Retain :pseudo-selectors.
  3353. | ([\(:])\s+
  3354. >xS',
  3355. // Only one of the three capturing groups will match, so its reference
  3356. // will contain the wanted value and the references for the
  3357. // two non-matching groups will be replaced with empty strings.
  3358. '$1$2$3',
  3359. $contents
  3360. );
  3361. // End the file with a new line.
  3362. $contents = trim($contents);
  3363. $contents .= "\n";
  3364. }
  3365. // Replaces @import commands with the actual stylesheet content.
  3366. // This happens recursively but omits external files.
  3367. $contents = preg_replace_callback('/@import\s*(?:url\(\s*)?[\'"]?(?![a-z]+:)([^\'"\()]+)[\'"]?\s*\)?\s*;/', '_drupal_load_stylesheet', $contents);
  3368. return $contents;
  3369. }
  3370. /**
  3371. * Loads stylesheets recursively and returns contents with corrected paths.
  3372. *
  3373. * This function is used for recursive loading of stylesheets and
  3374. * returns the stylesheet content with all url() paths corrected.
  3375. */
  3376. function _drupal_load_stylesheet($matches) {
  3377. $filename = $matches[1];
  3378. // Load the imported stylesheet and replace @import commands in there as well.
  3379. $file = drupal_load_stylesheet($filename, NULL, FALSE);
  3380. // Determine the file's directory.
  3381. $directory = dirname($filename);
  3382. // If the file is in the current directory, make sure '.' doesn't appear in
  3383. // the url() path.
  3384. $directory = $directory == '.' ? '' : $directory .'/';
  3385. // Alter all internal url() paths. Leave external paths alone. We don't need
  3386. // to normalize absolute paths here (i.e. remove folder/... segments) because
  3387. // that will be done later.
  3388. return preg_replace('/url\(\s*([\'"]?)(?![a-z]+:|\/+)/i', 'url(\1'. $directory, $file);
  3389. }
  3390. /**
  3391. * Deletes old cached CSS files.
  3392. */
  3393. function drupal_clear_css_cache() {
  3394. variable_del('drupal_css_cache_files');
  3395. file_scan_directory('public://css', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
  3396. }
  3397. /**
  3398. * Callback to delete files modified more than a set time ago.
  3399. */
  3400. function drupal_delete_file_if_stale($uri) {
  3401. // Default stale file threshold is 30 days.
  3402. if (REQUEST_TIME - filemtime($uri) > variable_get('drupal_stale_file_threshold', 2592000)) {
  3403. file_unmanaged_delete($uri);
  3404. }
  3405. }
  3406. /**
  3407. * Prepares a string for use as a CSS identifier (element, class, or ID name).
  3408. *
  3409. * http://www.w3.org/TR/CSS21/syndata.html#characters shows the syntax for valid
  3410. * CSS identifiers (including element names, classes, and IDs in selectors.)
  3411. *
  3412. * @param $identifier
  3413. * The identifier to clean.
  3414. * @param $filter
  3415. * An array of string replacements to use on the identifier.
  3416. *
  3417. * @return
  3418. * The cleaned identifier.
  3419. */
  3420. function drupal_clean_css_identifier($identifier, $filter = array(' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '')) {
  3421. // By default, we filter using Drupal's coding standards.
  3422. $identifier = strtr($identifier, $filter);
  3423. // Valid characters in a CSS identifier are:
  3424. // - the hyphen (U+002D)
  3425. // - a-z (U+0030 - U+0039)
  3426. // - A-Z (U+0041 - U+005A)
  3427. // - the underscore (U+005F)
  3428. // - 0-9 (U+0061 - U+007A)
  3429. // - ISO 10646 characters U+00A1 and higher
  3430. // We strip out any character not in the above list.
  3431. $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);
  3432. return $identifier;
  3433. }
  3434. /**
  3435. * Prepares a string for use as a valid class name.
  3436. *
  3437. * Do not pass one string containing multiple classes as they will be
  3438. * incorrectly concatenated with dashes, i.e. "one two" will become "one-two".
  3439. *
  3440. * @param $class
  3441. * The class name to clean.
  3442. *
  3443. * @return
  3444. * The cleaned class name.
  3445. */
  3446. function drupal_html_class($class) {
  3447. return drupal_clean_css_identifier(drupal_strtolower($class));
  3448. }
  3449. /**
  3450. * Prepares a string for use as a valid HTML ID and guarantees uniqueness.
  3451. *
  3452. * This function ensures that each passed HTML ID value only exists once on the
  3453. * page. By tracking the already returned ids, this function enables forms,
  3454. * blocks, and other content to be output multiple times on the same page,
  3455. * without breaking (X)HTML validation.
  3456. *
  3457. * For already existing IDs, a counter is appended to the ID string. Therefore,
  3458. * JavaScript and CSS code should not rely on any value that was generated by
  3459. * this function and instead should rely on manually added CSS classes or
  3460. * similarly reliable constructs.
  3461. *
  3462. * Two consecutive hyphens separate the counter from the original ID. To manage
  3463. * uniqueness across multiple Ajax requests on the same page, Ajax requests
  3464. * POST an array of all IDs currently present on the page, which are used to
  3465. * prime this function's cache upon first invocation.
  3466. *
  3467. * To allow reverse-parsing of IDs submitted via Ajax, any multiple consecutive
  3468. * hyphens in the originally passed $id are replaced with a single hyphen.
  3469. *
  3470. * @param $id
  3471. * The ID to clean.
  3472. *
  3473. * @return
  3474. * The cleaned ID.
  3475. */
  3476. function drupal_html_id($id) {
  3477. // If this is an Ajax request, then content returned by this page request will
  3478. // be merged with content already on the base page. The HTML IDs must be
  3479. // unique for the fully merged content. Therefore, initialize $seen_ids to
  3480. // take into account IDs that are already in use on the base page.
  3481. $seen_ids_init = &drupal_static(__FUNCTION__ . ':init');
  3482. if (!isset($seen_ids_init)) {
  3483. // Ideally, Drupal would provide an API to persist state information about
  3484. // prior page requests in the database, and we'd be able to add this
  3485. // function's $seen_ids static variable to that state information in order
  3486. // to have it properly initialized for this page request. However, no such
  3487. // page state API exists, so instead, ajax.js adds all of the in-use HTML
  3488. // IDs to the POST data of Ajax submissions. Direct use of $_POST is
  3489. // normally not recommended as it could open up security risks, but because
  3490. // the raw POST data is cast to a number before being returned by this
  3491. // function, this usage is safe.
  3492. if (empty($_POST['ajax_html_ids'])) {
  3493. $seen_ids_init = array();
  3494. }
  3495. else {
  3496. // This function ensures uniqueness by appending a counter to the base id
  3497. // requested by the calling function after the first occurrence of that
  3498. // requested id. $_POST['ajax_html_ids'] contains the ids as they were
  3499. // returned by this function, potentially with the appended counter, so
  3500. // we parse that to reconstruct the $seen_ids array.
  3501. foreach ($_POST['ajax_html_ids'] as $seen_id) {
  3502. // We rely on '--' being used solely for separating a base id from the
  3503. // counter, which this function ensures when returning an id.
  3504. $parts = explode('--', $seen_id, 2);
  3505. if (!empty($parts[1]) && is_numeric($parts[1])) {
  3506. list($seen_id, $i) = $parts;
  3507. }
  3508. else {
  3509. $i = 1;
  3510. }
  3511. if (!isset($seen_ids_init[$seen_id]) || ($i > $seen_ids_init[$seen_id])) {
  3512. $seen_ids_init[$seen_id] = $i;
  3513. }
  3514. }
  3515. }
  3516. }
  3517. $seen_ids = &drupal_static(__FUNCTION__, $seen_ids_init);
  3518. $id = strtr(drupal_strtolower($id), array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
  3519. // As defined in http://www.w3.org/TR/html4/types.html#type-name, HTML IDs can
  3520. // only contain letters, digits ([0-9]), hyphens ("-"), underscores ("_"),
  3521. // colons (":"), and periods ("."). We strip out any character not in that
  3522. // list. Note that the CSS spec doesn't allow colons or periods in identifiers
  3523. // (http://www.w3.org/TR/CSS21/syndata.html#characters), so we strip those two
  3524. // characters as well.
  3525. $id = preg_replace('/[^A-Za-z0-9\-_]/', '', $id);
  3526. // Removing multiple consecutive hyphens.
  3527. $id = preg_replace('/\-+/', '-', $id);
  3528. // Ensure IDs are unique by appending a counter after the first occurrence.
  3529. // The counter needs to be appended with a delimiter that does not exist in
  3530. // the base ID. Requiring a unique delimiter helps ensure that we really do
  3531. // return unique IDs and also helps us re-create the $seen_ids array during
  3532. // Ajax requests.
  3533. if (isset($seen_ids[$id])) {
  3534. $id = $id . '--' . ++$seen_ids[$id];
  3535. }
  3536. else {
  3537. $seen_ids[$id] = 1;
  3538. }
  3539. return $id;
  3540. }
  3541. /**
  3542. * Provides a standard HTML class name that identifies a page region.
  3543. *
  3544. * It is recommended that template preprocess functions apply this class to any
  3545. * page region that is output by the theme (Drupal core already handles this in
  3546. * the standard template preprocess implementation). Standardizing the class
  3547. * names in this way allows modules to implement certain features, such as
  3548. * drag-and-drop or dynamic Ajax loading, in a theme-independent way.
  3549. *
  3550. * @param $region
  3551. * The name of the page region (for example, 'page_top' or 'content').
  3552. *
  3553. * @return
  3554. * An HTML class that identifies the region (for example, 'region-page-top'
  3555. * or 'region-content').
  3556. *
  3557. * @see template_preprocess_region()
  3558. */
  3559. function drupal_region_class($region) {
  3560. return drupal_html_class("region-$region");
  3561. }
  3562. /**
  3563. * Adds a JavaScript file, setting, or inline code to the page.
  3564. *
  3565. * The behavior of this function depends on the parameters it is called with.
  3566. * Generally, it handles the addition of JavaScript to the page, either as
  3567. * reference to an existing file or as inline code. The following actions can be
  3568. * performed using this function:
  3569. * - Add a file ('file'): Adds a reference to a JavaScript file to the page.
  3570. * - Add inline JavaScript code ('inline'): Executes a piece of JavaScript code
  3571. * on the current page by placing the code directly in the page (for example,
  3572. * to tell the user that a new message arrived, by opening a pop up, alert
  3573. * box, etc.). This should only be used for JavaScript that cannot be executed
  3574. * from a file. When adding inline code, make sure that you are not relying on
  3575. * $() being the jQuery function. Wrap your code in
  3576. * @code (function ($) {... })(jQuery); @endcode
  3577. * or use jQuery() instead of $().
  3578. * - Add external JavaScript ('external'): Allows the inclusion of external
  3579. * JavaScript files that are not hosted on the local server. Note that these
  3580. * external JavaScript references do not get aggregated when preprocessing is
  3581. * on.
  3582. * - Add settings ('setting'): Adds settings to Drupal's global storage of
  3583. * JavaScript settings. Per-page settings are required by some modules to
  3584. * function properly. All settings will be accessible at Drupal.settings.
  3585. *
  3586. * Examples:
  3587. * @code
  3588. * drupal_add_js('misc/collapse.js');
  3589. * drupal_add_js('misc/collapse.js', 'file');
  3590. * drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  3591. * drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
  3592. * array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
  3593. * );
  3594. * drupal_add_js('http://example.com/example.js', 'external');
  3595. * drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');
  3596. * @endcode
  3597. *
  3598. * Calling drupal_static_reset('drupal_add_js') will clear all JavaScript added
  3599. * so far.
  3600. *
  3601. * If JavaScript aggregation is enabled, all JavaScript files added with
  3602. * $options['preprocess'] set to TRUE will be merged into one aggregate file.
  3603. * Preprocessed inline JavaScript will not be aggregated into this single file.
  3604. * Externally hosted JavaScripts are never aggregated.
  3605. *
  3606. * The reason for aggregating the files is outlined quite thoroughly here:
  3607. * http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
  3608. * to request overhead, one bigger file just loads faster than two smaller ones
  3609. * half its size."
  3610. *
  3611. * $options['preprocess'] should be only set to TRUE when a file is required for
  3612. * all typical visitors and most pages of a site. It is critical that all
  3613. * preprocessed files are added unconditionally on every page, even if the
  3614. * files are not needed on a page. This is normally done by calling
  3615. * drupal_add_js() in a hook_init() implementation.
  3616. *
  3617. * Non-preprocessed files should only be added to the page when they are
  3618. * actually needed.
  3619. *
  3620. * @param $data
  3621. * (optional) If given, the value depends on the $options parameter:
  3622. * - 'file': Path to the file relative to base_path().
  3623. * - 'inline': The JavaScript code that should be placed in the given scope.
  3624. * - 'external': The absolute path to an external JavaScript file that is not
  3625. * hosted on the local server. These files will not be aggregated if
  3626. * JavaScript aggregation is enabled.
  3627. * - 'setting': An associative array with configuration options. The array is
  3628. * merged directly into Drupal.settings. All modules should wrap their
  3629. * actual configuration settings in another variable to prevent conflicts in
  3630. * the Drupal.settings namespace. Items added with a string key will replace
  3631. * existing settings with that key; items with numeric array keys will be
  3632. * added to the existing settings array.
  3633. * @param $options
  3634. * (optional) A string defining the type of JavaScript that is being added in
  3635. * the $data parameter ('file'/'setting'/'inline'/'external'), or an
  3636. * associative array. JavaScript settings should always pass the string
  3637. * 'setting' only. Other types can have the following elements in the array:
  3638. * - type: The type of JavaScript that is to be added to the page. Allowed
  3639. * values are 'file', 'inline', 'external' or 'setting'. Defaults
  3640. * to 'file'.
  3641. * - scope: The location in which you want to place the script. Possible
  3642. * values are 'header' or 'footer'. If your theme implements different
  3643. * regions, you can also use these. Defaults to 'header'.
  3644. * - group: A number identifying the group in which to add the JavaScript.
  3645. * Available constants are:
  3646. * - JS_LIBRARY: Any libraries, settings, or jQuery plugins.
  3647. * - JS_DEFAULT: Any module-layer JavaScript.
  3648. * - JS_THEME: Any theme-layer JavaScript.
  3649. * The group number serves as a weight: JavaScript within a lower weight
  3650. * group is presented on the page before JavaScript within a higher weight
  3651. * group.
  3652. * - every_page: For optimal front-end performance when aggregation is
  3653. * enabled, this should be set to TRUE if the JavaScript is present on every
  3654. * page of the website for users for whom it is present at all. This
  3655. * defaults to FALSE. It is set to TRUE for JavaScript files that are added
  3656. * via module and theme .info files. Modules that add JavaScript within
  3657. * hook_init() implementations, or from other code that ensures that the
  3658. * JavaScript is added to all website pages, should also set this flag to
  3659. * TRUE. All JavaScript files within the same group and that have the
  3660. * 'every_page' flag set to TRUE and do not have 'preprocess' set to FALSE
  3661. * are aggregated together into a single aggregate file, and that aggregate
  3662. * file can be reused across a user's entire site visit, leading to faster
  3663. * navigation between pages. However, JavaScript that is only needed on
  3664. * pages less frequently visited, can be added by code that only runs for
  3665. * those particular pages, and that code should not set the 'every_page'
  3666. * flag. This minimizes the size of the aggregate file that the user needs
  3667. * to download when first visiting the website. JavaScript without the
  3668. * 'every_page' flag is aggregated into a separate aggregate file. This
  3669. * other aggregate file is likely to change from page to page, and each new
  3670. * aggregate file needs to be downloaded when first encountered, so it
  3671. * should be kept relatively small by ensuring that most commonly needed
  3672. * JavaScript is added to every page.
  3673. * - weight: A number defining the order in which the JavaScript is added to
  3674. * the page relative to other JavaScript with the same 'scope', 'group',
  3675. * and 'every_page' value. In some cases, the order in which the JavaScript
  3676. * is presented on the page is very important. jQuery, for example, must be
  3677. * added to the page before any jQuery code is run, so jquery.js uses the
  3678. * JS_LIBRARY group and a weight of -20, jquery.once.js (a library drupal.js
  3679. * depends on) uses the JS_LIBRARY group and a weight of -19, drupal.js uses
  3680. * the JS_LIBRARY group and a weight of -1, other libraries use the
  3681. * JS_LIBRARY group and a weight of 0 or higher, and all other scripts use
  3682. * one of the other group constants. The exact ordering of JavaScript is as
  3683. * follows:
  3684. * - First by scope, with 'header' first, 'footer' last, and any other
  3685. * scopes provided by a custom theme coming in between, as determined by
  3686. * the theme.
  3687. * - Then by group.
  3688. * - Then by the 'every_page' flag, with TRUE coming before FALSE.
  3689. * - Then by weight.
  3690. * - Then by the order in which the JavaScript was added. For example, all
  3691. * else being the same, JavaScript added by a call to drupal_add_js() that
  3692. * happened later in the page request gets added to the page after one for
  3693. * which drupal_add_js() happened earlier in the page request.
  3694. * - defer: If set to TRUE, the defer attribute is set on the &lt;script&gt;
  3695. * tag. Defaults to FALSE.
  3696. * - cache: If set to FALSE, the JavaScript file is loaded anew on every page
  3697. * call; in other words, it is not cached. Used only when 'type' references
  3698. * a JavaScript file. Defaults to TRUE.
  3699. * - preprocess: If TRUE and JavaScript aggregation is enabled, the script
  3700. * file will be aggregated. Defaults to TRUE.
  3701. *
  3702. * @return
  3703. * The current array of JavaScript files, settings, and in-line code,
  3704. * including Drupal defaults, anything previously added with calls to
  3705. * drupal_add_js(), and this function call's additions.
  3706. *
  3707. * @see drupal_get_js()
  3708. */
  3709. function drupal_add_js($data = NULL, $options = NULL) {
  3710. $javascript = &drupal_static(__FUNCTION__, array());
  3711. // Construct the options, taking the defaults into consideration.
  3712. if (isset($options)) {
  3713. if (!is_array($options)) {
  3714. $options = array('type' => $options);
  3715. }
  3716. }
  3717. else {
  3718. $options = array();
  3719. }
  3720. $options += drupal_js_defaults($data);
  3721. // Preprocess can only be set if caching is enabled.
  3722. $options['preprocess'] = $options['cache'] ? $options['preprocess'] : FALSE;
  3723. // Tweak the weight so that files of the same weight are included in the
  3724. // order of the calls to drupal_add_js().
  3725. $options['weight'] += count($javascript) / 1000;
  3726. if (isset($data)) {
  3727. // Add jquery.js and drupal.js, as well as the basePath setting, the
  3728. // first time a JavaScript file is added.
  3729. if (empty($javascript)) {
  3730. // url() generates the prefix using hook_url_outbound_alter(). Instead of
  3731. // running the hook_url_outbound_alter() again here, extract the prefix
  3732. // from url().
  3733. url('', array('prefix' => &$prefix));
  3734. $javascript = array(
  3735. 'settings' => array(
  3736. 'data' => array(
  3737. array('basePath' => base_path()),
  3738. array('pathPrefix' => empty($prefix) ? '' : $prefix),
  3739. ),
  3740. 'type' => 'setting',
  3741. 'scope' => 'header',
  3742. 'group' => JS_LIBRARY,
  3743. 'every_page' => TRUE,
  3744. 'weight' => 0,
  3745. ),
  3746. 'misc/drupal.js' => array(
  3747. 'data' => 'misc/drupal.js',
  3748. 'type' => 'file',
  3749. 'scope' => 'header',
  3750. 'group' => JS_LIBRARY,
  3751. 'every_page' => TRUE,
  3752. 'weight' => -1,
  3753. 'preprocess' => TRUE,
  3754. 'cache' => TRUE,
  3755. 'defer' => FALSE,
  3756. ),
  3757. );
  3758. // Register all required libraries.
  3759. drupal_add_library('system', 'jquery', TRUE);
  3760. drupal_add_library('system', 'jquery.once', TRUE);
  3761. }
  3762. switch ($options['type']) {
  3763. case 'setting':
  3764. // All JavaScript settings are placed in the header of the page with
  3765. // the library weight so that inline scripts appear afterwards.
  3766. $javascript['settings']['data'][] = $data;
  3767. break;
  3768. case 'inline':
  3769. $javascript[] = $options;
  3770. break;
  3771. default: // 'file' and 'external'
  3772. // Local and external files must keep their name as the associative key
  3773. // so the same JavaScript file is not added twice.
  3774. $javascript[$options['data']] = $options;
  3775. }
  3776. }
  3777. return $javascript;
  3778. }
  3779. /**
  3780. * Constructs an array of the defaults that are used for JavaScript items.
  3781. *
  3782. * @param $data
  3783. * (optional) The default data parameter for the JavaScript item array.
  3784. *
  3785. * @see drupal_get_js()
  3786. * @see drupal_add_js()
  3787. */
  3788. function drupal_js_defaults($data = NULL) {
  3789. return array(
  3790. 'type' => 'file',
  3791. 'group' => JS_DEFAULT,
  3792. 'every_page' => FALSE,
  3793. 'weight' => 0,
  3794. 'scope' => 'header',
  3795. 'cache' => TRUE,
  3796. 'defer' => FALSE,
  3797. 'preprocess' => TRUE,
  3798. 'version' => NULL,
  3799. 'data' => $data,
  3800. );
  3801. }
  3802. /**
  3803. * Returns a themed presentation of all JavaScript code for the current page.
  3804. *
  3805. * References to JavaScript files are placed in a certain order: first, all
  3806. * 'core' files, then all 'module' and finally all 'theme' JavaScript files
  3807. * are added to the page. Then, all settings are output, followed by 'inline'
  3808. * JavaScript code. If running update.php, all preprocessing is disabled.
  3809. *
  3810. * Note that hook_js_alter(&$javascript) is called during this function call
  3811. * to allow alterations of the JavaScript during its presentation. Calls to
  3812. * drupal_add_js() from hook_js_alter() will not be added to the output
  3813. * presentation. The correct way to add JavaScript during hook_js_alter()
  3814. * is to add another element to the $javascript array, deriving from
  3815. * drupal_js_defaults(). See locale_js_alter() for an example of this.
  3816. *
  3817. * @param $scope
  3818. * (optional) The scope for which the JavaScript rules should be returned.
  3819. * Defaults to 'header'.
  3820. * @param $javascript
  3821. * (optional) An array with all JavaScript code. Defaults to the default
  3822. * JavaScript array for the given scope.
  3823. * @param $skip_alter
  3824. * (optional) If set to TRUE, this function skips calling drupal_alter() on
  3825. * $javascript, useful when the calling function passes a $javascript array
  3826. * that has already been altered.
  3827. *
  3828. * @return
  3829. * All JavaScript code segments and includes for the scope as HTML tags.
  3830. *
  3831. * @see drupal_add_js()
  3832. * @see locale_js_alter()
  3833. * @see drupal_js_defaults()
  3834. */
  3835. function drupal_get_js($scope = 'header', $javascript = NULL, $skip_alter = FALSE) {
  3836. if (!isset($javascript)) {
  3837. $javascript = drupal_add_js();
  3838. }
  3839. if (empty($javascript)) {
  3840. return '';
  3841. }
  3842. // Allow modules to alter the JavaScript.
  3843. if (!$skip_alter) {
  3844. drupal_alter('js', $javascript);
  3845. }
  3846. // Filter out elements of the given scope.
  3847. $items = array();
  3848. foreach ($javascript as $key => $item) {
  3849. if ($item['scope'] == $scope) {
  3850. $items[$key] = $item;
  3851. }
  3852. }
  3853. $output = '';
  3854. // The index counter is used to keep aggregated and non-aggregated files in
  3855. // order by weight.
  3856. $index = 1;
  3857. $processed = array();
  3858. $files = array();
  3859. $preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
  3860. // A dummy query-string is added to filenames, to gain control over
  3861. // browser-caching. The string changes on every update or full cache
  3862. // flush, forcing browsers to load a new copy of the files, as the
  3863. // URL changed. Files that should not be cached (see drupal_add_js())
  3864. // get REQUEST_TIME as query-string instead, to enforce reload on every
  3865. // page request.
  3866. $default_query_string = variable_get('css_js_query_string', '0');
  3867. // For inline JavaScript to validate as XHTML, all JavaScript containing
  3868. // XHTML needs to be wrapped in CDATA. To make that backwards compatible
  3869. // with HTML 4, we need to comment out the CDATA-tag.
  3870. $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
  3871. $embed_suffix = "\n//--><!]]>\n";
  3872. // Since JavaScript may look for arguments in the URL and act on them, some
  3873. // third-party code might require the use of a different query string.
  3874. $js_version_string = variable_get('drupal_js_version_query_string', 'v=');
  3875. // Sort the JavaScript so that it appears in the correct order.
  3876. uasort($items, 'drupal_sort_css_js');
  3877. // Provide the page with information about the individual JavaScript files
  3878. // used, information not otherwise available when aggregation is enabled.
  3879. $setting['ajaxPageState']['js'] = array_fill_keys(array_keys($items), 1);
  3880. unset($setting['ajaxPageState']['js']['settings']);
  3881. drupal_add_js($setting, 'setting');
  3882. // If we're outputting the header scope, then this might be the final time
  3883. // that drupal_get_js() is running, so add the setting to this output as well
  3884. // as to the drupal_add_js() cache. If $items['settings'] doesn't exist, it's
  3885. // because drupal_get_js() was intentionally passed a $javascript argument
  3886. // stripped off settings, potentially in order to override how settings get
  3887. // output, so in this case, do not add the setting to this output.
  3888. if ($scope == 'header' && isset($items['settings'])) {
  3889. $items['settings']['data'][] = $setting;
  3890. }
  3891. // Loop through the JavaScript to construct the rendered output.
  3892. $element = array(
  3893. '#tag' => 'script',
  3894. '#value' => '',
  3895. '#attributes' => array(
  3896. 'type' => 'text/javascript',
  3897. ),
  3898. );
  3899. foreach ($items as $item) {
  3900. $query_string = empty($item['version']) ? $default_query_string : $js_version_string . $item['version'];
  3901. switch ($item['type']) {
  3902. case 'setting':
  3903. $js_element = $element;
  3904. $js_element['#value_prefix'] = $embed_prefix;
  3905. $js_element['#value'] = 'jQuery.extend(Drupal.settings, ' . drupal_json_encode(drupal_array_merge_deep_array($item['data'])) . ");";
  3906. $js_element['#value_suffix'] = $embed_suffix;
  3907. $output .= theme('html_tag', array('element' => $js_element));
  3908. break;
  3909. case 'inline':
  3910. $js_element = $element;
  3911. if ($item['defer']) {
  3912. $js_element['#attributes']['defer'] = 'defer';
  3913. }
  3914. $js_element['#value_prefix'] = $embed_prefix;
  3915. $js_element['#value'] = $item['data'];
  3916. $js_element['#value_suffix'] = $embed_suffix;
  3917. $processed[$index++] = theme('html_tag', array('element' => $js_element));
  3918. break;
  3919. case 'file':
  3920. $js_element = $element;
  3921. if (!$item['preprocess'] || !$preprocess_js) {
  3922. if ($item['defer']) {
  3923. $js_element['#attributes']['defer'] = 'defer';
  3924. }
  3925. $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
  3926. $js_element['#attributes']['src'] = file_create_url($item['data']) . $query_string_separator . ($item['cache'] ? $query_string : REQUEST_TIME);
  3927. $processed[$index++] = theme('html_tag', array('element' => $js_element));
  3928. }
  3929. else {
  3930. // By increasing the index for each aggregated file, we maintain
  3931. // the relative ordering of JS by weight. We also set the key such
  3932. // that groups are split by items sharing the same 'group' value and
  3933. // 'every_page' flag. While this potentially results in more aggregate
  3934. // files, it helps make each one more reusable across a site visit,
  3935. // leading to better front-end performance of a website as a whole.
  3936. // See drupal_add_js() for details.
  3937. $key = 'aggregate_' . $item['group'] . '_' . $item['every_page'] . '_' . $index;
  3938. $processed[$key] = '';
  3939. $files[$key][$item['data']] = $item;
  3940. }
  3941. break;
  3942. case 'external':
  3943. $js_element = $element;
  3944. // Preprocessing for external JavaScript files is ignored.
  3945. if ($item['defer']) {
  3946. $js_element['#attributes']['defer'] = 'defer';
  3947. }
  3948. $js_element['#attributes']['src'] = $item['data'];
  3949. $processed[$index++] = theme('html_tag', array('element' => $js_element));
  3950. break;
  3951. }
  3952. }
  3953. // Aggregate any remaining JS files that haven't already been output.
  3954. if ($preprocess_js && count($files) > 0) {
  3955. foreach ($files as $key => $file_set) {
  3956. $uri = drupal_build_js_cache($file_set);
  3957. // Only include the file if was written successfully. Errors are logged
  3958. // using watchdog.
  3959. if ($uri) {
  3960. $preprocess_file = file_create_url($uri);
  3961. $js_element = $element;
  3962. $js_element['#attributes']['src'] = $preprocess_file;
  3963. $processed[$key] = theme('html_tag', array('element' => $js_element));
  3964. }
  3965. }
  3966. }
  3967. // Keep the order of JS files consistent as some are preprocessed and others are not.
  3968. // Make sure any inline or JS setting variables appear last after libraries have loaded.
  3969. return implode('', $processed) . $output;
  3970. }
  3971. /**
  3972. * Adds attachments to a render() structure.
  3973. *
  3974. * Libraries, JavaScript, CSS and other types of custom structures are attached
  3975. * to elements using the #attached property. The #attached property is an
  3976. * associative array, where the keys are the the attachment types and the values
  3977. * are the attached data. For example:
  3978. * @code
  3979. * $build['#attached'] = array(
  3980. * 'js' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.js'),
  3981. * 'css' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.css'),
  3982. * );
  3983. * @endcode
  3984. *
  3985. * 'js', 'css', and 'library' are types that get special handling. For any
  3986. * other kind of attached data, the array key must be the full name of the
  3987. * callback function and each value an array of arguments. For example:
  3988. * @code
  3989. * $build['#attached']['drupal_add_http_header'] = array(
  3990. * array('Content-Type', 'application/rss+xml; charset=utf-8'),
  3991. * );
  3992. * @endcode
  3993. *
  3994. * External 'js' and 'css' files can also be loaded. For example:
  3995. * @code
  3996. * $build['#attached']['js'] = array(
  3997. * 'http://code.jquery.com/jquery-1.4.2.min.js' => array(
  3998. * 'type' => 'external',
  3999. * ),
  4000. * );
  4001. * @endcode
  4002. *
  4003. * @param $elements
  4004. * The structured array describing the data being rendered.
  4005. * @param $group
  4006. * The default group of JavaScript and CSS being added. This is only applied
  4007. * to the stylesheets and JavaScript items that don't have an explicit group
  4008. * assigned to them.
  4009. * @param $dependency_check
  4010. * When TRUE, will exit if a given library's dependencies are missing. When
  4011. * set to FALSE, will continue to add the libraries, even though one or more
  4012. * dependencies are missing. Defaults to FALSE.
  4013. * @param $every_page
  4014. * Set to TRUE to indicate that the attachments are added to every page on the
  4015. * site. Only attachments with the every_page flag set to TRUE can participate
  4016. * in JavaScript/CSS aggregation.
  4017. *
  4018. * @return
  4019. * FALSE if there were any missing library dependencies; TRUE if all library
  4020. * dependencies were met.
  4021. *
  4022. * @see drupal_add_library()
  4023. * @see drupal_add_js()
  4024. * @see drupal_add_css()
  4025. * @see drupal_render()
  4026. */
  4027. function drupal_process_attached($elements, $group = JS_DEFAULT, $dependency_check = FALSE, $every_page = NULL) {
  4028. // Add defaults to the special attached structures that should be processed differently.
  4029. $elements['#attached'] += array(
  4030. 'library' => array(),
  4031. 'js' => array(),
  4032. 'css' => array(),
  4033. );
  4034. // Add the libraries first.
  4035. $success = TRUE;
  4036. foreach ($elements['#attached']['library'] as $library) {
  4037. if (drupal_add_library($library[0], $library[1], $every_page) === FALSE) {
  4038. $success = FALSE;
  4039. // Exit if the dependency is missing.
  4040. if ($dependency_check) {
  4041. return $success;
  4042. }
  4043. }
  4044. }
  4045. unset($elements['#attached']['library']);
  4046. // Add both the JavaScript and the CSS.
  4047. // The parameters for drupal_add_js() and drupal_add_css() require special
  4048. // handling.
  4049. foreach (array('js', 'css') as $type) {
  4050. foreach ($elements['#attached'][$type] as $data => $options) {
  4051. // If the value is not an array, it's a filename and passed as first
  4052. // (and only) argument.
  4053. if (!is_array($options)) {
  4054. $data = $options;
  4055. $options = NULL;
  4056. }
  4057. // In some cases, the first parameter ($data) is an array. Arrays can't be
  4058. // passed as keys in PHP, so we have to get $data from the value array.
  4059. if (is_numeric($data)) {
  4060. $data = $options['data'];
  4061. unset($options['data']);
  4062. }
  4063. // Apply the default group if it isn't explicitly given.
  4064. if (!isset($options['group'])) {
  4065. $options['group'] = $group;
  4066. }
  4067. // Set the every_page flag if one was passed.
  4068. if (isset($every_page)) {
  4069. $options['every_page'] = $every_page;
  4070. }
  4071. call_user_func('drupal_add_' . $type, $data, $options);
  4072. }
  4073. unset($elements['#attached'][$type]);
  4074. }
  4075. // Add additional types of attachments specified in the render() structure.
  4076. // Libraries, JavaScript and CSS have been added already, as they require
  4077. // special handling.
  4078. foreach ($elements['#attached'] as $callback => $options) {
  4079. if (function_exists($callback)) {
  4080. foreach ($elements['#attached'][$callback] as $args) {
  4081. call_user_func_array($callback, $args);
  4082. }
  4083. }
  4084. }
  4085. return $success;
  4086. }
  4087. /**
  4088. * Adds JavaScript to change the state of an element based on another element.
  4089. *
  4090. * A "state" means a certain property on a DOM element, such as "visible" or
  4091. * "checked". A state can be applied to an element, depending on the state of
  4092. * another element on the page. In general, states depend on HTML attributes and
  4093. * DOM element properties, which change due to user interaction.
  4094. *
  4095. * Since states are driven by JavaScript only, it is important to understand
  4096. * that all states are applied on presentation only, none of the states force
  4097. * any server-side logic, and that they will not be applied for site visitors
  4098. * without JavaScript support. All modules implementing states have to make
  4099. * sure that the intended logic also works without JavaScript being enabled.
  4100. *
  4101. * #states is an associative array in the form of:
  4102. * @code
  4103. * array(
  4104. * STATE1 => CONDITIONS_ARRAY1,
  4105. * STATE2 => CONDITIONS_ARRAY2,
  4106. * ...
  4107. * )
  4108. * @endcode
  4109. * Each key is the name of a state to apply to the element, such as 'visible'.
  4110. * Each value is a list of conditions that denote when the state should be
  4111. * applied.
  4112. *
  4113. * Multiple different states may be specified to act on complex conditions:
  4114. * @code
  4115. * array(
  4116. * 'visible' => CONDITIONS,
  4117. * 'checked' => OTHER_CONDITIONS,
  4118. * )
  4119. * @endcode
  4120. *
  4121. * Every condition is a key/value pair, whose key is a jQuery selector that
  4122. * denotes another element on the page, and whose value is an array of
  4123. * conditions, which must bet met on that element:
  4124. * @code
  4125. * array(
  4126. * 'visible' => array(
  4127. * JQUERY_SELECTOR => REMOTE_CONDITIONS,
  4128. * JQUERY_SELECTOR => REMOTE_CONDITIONS,
  4129. * ...
  4130. * ),
  4131. * )
  4132. * @endcode
  4133. * All conditions must be met for the state to be applied.
  4134. *
  4135. * Each remote condition is a key/value pair specifying conditions on the other
  4136. * element that need to be met to apply the state to the element:
  4137. * @code
  4138. * array(
  4139. * 'visible' => array(
  4140. * ':input[name="remote_checkbox"]' => array('checked' => TRUE),
  4141. * ),
  4142. * )
  4143. * @endcode
  4144. *
  4145. * For example, to show a textfield only when a checkbox is checked:
  4146. * @code
  4147. * $form['toggle_me'] = array(
  4148. * '#type' => 'checkbox',
  4149. * '#title' => t('Tick this box to type'),
  4150. * );
  4151. * $form['settings'] = array(
  4152. * '#type' => 'textfield',
  4153. * '#states' => array(
  4154. * // Only show this field when the 'toggle_me' checkbox is enabled.
  4155. * 'visible' => array(
  4156. * ':input[name="toggle_me"]' => array('checked' => TRUE),
  4157. * ),
  4158. * ),
  4159. * );
  4160. * @endcode
  4161. *
  4162. * The following states may be applied to an element:
  4163. * - enabled
  4164. * - disabled
  4165. * - required
  4166. * - optional
  4167. * - visible
  4168. * - invisible
  4169. * - checked
  4170. * - unchecked
  4171. * - expanded
  4172. * - collapsed
  4173. *
  4174. * The following states may be used in remote conditions:
  4175. * - empty
  4176. * - filled
  4177. * - checked
  4178. * - unchecked
  4179. * - expanded
  4180. * - collapsed
  4181. * - value
  4182. *
  4183. * The following states exist for both elements and remote conditions, but are
  4184. * not fully implemented and may not change anything on the element:
  4185. * - relevant
  4186. * - irrelevant
  4187. * - valid
  4188. * - invalid
  4189. * - touched
  4190. * - untouched
  4191. * - readwrite
  4192. * - readonly
  4193. *
  4194. * When referencing select lists and radio buttons in remote conditions, a
  4195. * 'value' condition must be used:
  4196. * @code
  4197. * '#states' => array(
  4198. * // Show the settings if 'bar' has been selected for 'foo'.
  4199. * 'visible' => array(
  4200. * ':input[name="foo"]' => array('value' => 'bar'),
  4201. * ),
  4202. * ),
  4203. * @endcode
  4204. *
  4205. * @param $elements
  4206. * A renderable array element having a #states property as described above.
  4207. *
  4208. * @see form_example_states_form()
  4209. */
  4210. function drupal_process_states(&$elements) {
  4211. $elements['#attached']['library'][] = array('system', 'drupal.states');
  4212. $elements['#attached']['js'][] = array(
  4213. 'type' => 'setting',
  4214. 'data' => array('states' => array('#' . $elements['#id'] => $elements['#states'])),
  4215. );
  4216. }
  4217. /**
  4218. * Adds multiple JavaScript or CSS files at the same time.
  4219. *
  4220. * A library defines a set of JavaScript and/or CSS files, optionally using
  4221. * settings, and optionally requiring another library. For example, a library
  4222. * can be a jQuery plugin, a JavaScript framework, or a CSS framework. This
  4223. * function allows modules to load a library defined/shipped by itself or a
  4224. * depending module, without having to add all files of the library separately.
  4225. * Each library is only loaded once.
  4226. *
  4227. * @param $module
  4228. * The name of the module that registered the library.
  4229. * @param $name
  4230. * The name of the library to add.
  4231. * @param $every_page
  4232. * Set to TRUE if this library is added to every page on the site. Only items
  4233. * with the every_page flag set to TRUE can participate in aggregation.
  4234. *
  4235. * @return
  4236. * TRUE if the library was successfully added; FALSE if the library or one of
  4237. * its dependencies could not be added.
  4238. *
  4239. * @see drupal_get_library()
  4240. * @see hook_library()
  4241. * @see hook_library_alter()
  4242. */
  4243. function drupal_add_library($module, $name, $every_page = NULL) {
  4244. $added = &drupal_static(__FUNCTION__, array());
  4245. // Only process the library if it exists and it was not added already.
  4246. if (!isset($added[$module][$name])) {
  4247. if ($library = drupal_get_library($module, $name)) {
  4248. // Add all components within the library.
  4249. $elements['#attached'] = array(
  4250. 'library' => $library['dependencies'],
  4251. 'js' => $library['js'],
  4252. 'css' => $library['css'],
  4253. );
  4254. $added[$module][$name] = drupal_process_attached($elements, JS_LIBRARY, TRUE, $every_page);
  4255. }
  4256. else {
  4257. // Requested library does not exist.
  4258. $added[$module][$name] = FALSE;
  4259. }
  4260. }
  4261. return $added[$module][$name];
  4262. }
  4263. /**
  4264. * Retrieves information for a JavaScript/CSS library.
  4265. *
  4266. * Library information is statically cached. Libraries are keyed by module for
  4267. * several reasons:
  4268. * - Libraries are not unique. Multiple modules might ship with the same library
  4269. * in a different version or variant. This registry cannot (and does not
  4270. * attempt to) prevent library conflicts.
  4271. * - Modules implementing and thereby depending on a library that is registered
  4272. * by another module can only rely on that module's library.
  4273. * - Two (or more) modules can still register the same library and use it
  4274. * without conflicts in case the libraries are loaded on certain pages only.
  4275. *
  4276. * @param $module
  4277. * The name of a module that registered a library.
  4278. * @param $name
  4279. * (optional) The name of a registered library to retrieve. By default, all
  4280. * libraries registered by $module are returned.
  4281. *
  4282. * @return
  4283. * The definition of the requested library, if $name was passed and it exists,
  4284. * or FALSE if it does not exist. If no $name was passed, an associative array
  4285. * of libraries registered by $module is returned (which may be empty).
  4286. *
  4287. * @see drupal_add_library()
  4288. * @see hook_library()
  4289. * @see hook_library_alter()
  4290. *
  4291. * @todo The purpose of drupal_get_*() is completely different to other page
  4292. * requisite API functions; find and use a different name.
  4293. */
  4294. function drupal_get_library($module, $name = NULL) {
  4295. $libraries = &drupal_static(__FUNCTION__, array());
  4296. if (!isset($libraries[$module])) {
  4297. // Retrieve all libraries associated with the module.
  4298. $module_libraries = module_invoke($module, 'library');
  4299. if (empty($module_libraries)) {
  4300. $module_libraries = array();
  4301. }
  4302. // Allow modules to alter the module's registered libraries.
  4303. drupal_alter('library', $module_libraries, $module);
  4304. foreach ($module_libraries as $key => $data) {
  4305. if (is_array($data)) {
  4306. // Add default elements to allow for easier processing.
  4307. $module_libraries[$key] += array('dependencies' => array(), 'js' => array(), 'css' => array());
  4308. foreach ($module_libraries[$key]['js'] as $file => $options) {
  4309. $module_libraries[$key]['js'][$file]['version'] = $module_libraries[$key]['version'];
  4310. }
  4311. }
  4312. }
  4313. $libraries[$module] = $module_libraries;
  4314. }
  4315. if (isset($name)) {
  4316. if (!isset($libraries[$module][$name])) {
  4317. $libraries[$module][$name] = FALSE;
  4318. }
  4319. return $libraries[$module][$name];
  4320. }
  4321. return $libraries[$module];
  4322. }
  4323. /**
  4324. * Assists in adding the tableDrag JavaScript behavior to a themed table.
  4325. *
  4326. * Draggable tables should be used wherever an outline or list of sortable items
  4327. * needs to be arranged by an end-user. Draggable tables are very flexible and
  4328. * can manipulate the value of form elements placed within individual columns.
  4329. *
  4330. * To set up a table to use drag and drop in place of weight select-lists or in
  4331. * place of a form that contains parent relationships, the form must be themed
  4332. * into a table. The table must have an ID attribute set. If using
  4333. * theme_table(), the ID may be set as follows:
  4334. * @code
  4335. * $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'my-module-table')));
  4336. * return $output;
  4337. * @endcode
  4338. *
  4339. * In the theme function for the form, a special class must be added to each
  4340. * form element within the same column, "grouping" them together.
  4341. *
  4342. * In a situation where a single weight column is being sorted in the table, the
  4343. * classes could be added like this (in the theme function):
  4344. * @code
  4345. * $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
  4346. * @endcode
  4347. *
  4348. * Each row of the table must also have a class of "draggable" in order to
  4349. * enable the drag handles:
  4350. * @code
  4351. * $row = array(...);
  4352. * $rows[] = array(
  4353. * 'data' => $row,
  4354. * 'class' => array('draggable'),
  4355. * );
  4356. * @endcode
  4357. *
  4358. * When tree relationships are present, the two additional classes
  4359. * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
  4360. * - Rows with the 'tabledrag-leaf' class cannot have child rows.
  4361. * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
  4362. *
  4363. * Calling drupal_add_tabledrag() would then be written as such:
  4364. * @code
  4365. * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
  4366. * @endcode
  4367. *
  4368. * In a more complex case where there are several groups in one column (such as
  4369. * the block regions on the admin/structure/block page), a separate subgroup
  4370. * class must also be added to differentiate the groups.
  4371. * @code
  4372. * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
  4373. * @endcode
  4374. *
  4375. * $group is still 'my-element-weight', and the additional $subgroup variable
  4376. * will be passed in as 'my-elements-weight-' . $region. This also means that
  4377. * you'll need to call drupal_add_tabledrag() once for every region added.
  4378. *
  4379. * @code
  4380. * foreach ($regions as $region) {
  4381. * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight', 'my-elements-weight-' . $region);
  4382. * }
  4383. * @endcode
  4384. *
  4385. * In a situation where tree relationships are present, adding multiple
  4386. * subgroups is not necessary, because the table will contain indentations that
  4387. * provide enough information about the sibling and parent relationships. See
  4388. * theme_menu_overview_form() for an example creating a table containing parent
  4389. * relationships.
  4390. *
  4391. * Note that this function should be called from the theme layer, such as in a
  4392. * .tpl.php file, theme_ function, or in a template_preprocess function, not in
  4393. * a form declaration. Though the same JavaScript could be added to the page
  4394. * using drupal_add_js() directly, this function helps keep template files
  4395. * clean and readable. It also prevents tabledrag.js from being added twice
  4396. * accidentally.
  4397. *
  4398. * @param $table_id
  4399. * String containing the target table's id attribute. If the table does not
  4400. * have an id, one will need to be set, such as <table id="my-module-table">.
  4401. * @param $action
  4402. * String describing the action to be done on the form item. Either 'match'
  4403. * 'depth', or 'order'. Match is typically used for parent relationships.
  4404. * Order is typically used to set weights on other form elements with the same
  4405. * group. Depth updates the target element with the current indentation.
  4406. * @param $relationship
  4407. * String describing where the $action variable should be performed. Either
  4408. * 'parent', 'sibling', 'group', or 'self'. Parent will only look for fields
  4409. * up the tree. Sibling will look for fields in the same group in rows above
  4410. * and below it. Self affects the dragged row itself. Group affects the
  4411. * dragged row, plus any children below it (the entire dragged group).
  4412. * @param $group
  4413. * A class name applied on all related form elements for this action.
  4414. * @param $subgroup
  4415. * (optional) If the group has several subgroups within it, this string should
  4416. * contain the class name identifying fields in the same subgroup.
  4417. * @param $source
  4418. * (optional) If the $action is 'match', this string should contain the class
  4419. * name identifying what field will be used as the source value when matching
  4420. * the value in $subgroup.
  4421. * @param $hidden
  4422. * (optional) The column containing the field elements may be entirely hidden
  4423. * from view dynamically when the JavaScript is loaded. Set to FALSE if the
  4424. * column should not be hidden.
  4425. * @param $limit
  4426. * (optional) Limit the maximum amount of parenting in this table.
  4427. * @see block-admin-display-form.tpl.php
  4428. * @see theme_menu_overview_form()
  4429. */
  4430. function drupal_add_tabledrag($table_id, $action, $relationship, $group, $subgroup = NULL, $source = NULL, $hidden = TRUE, $limit = 0) {
  4431. $js_added = &drupal_static(__FUNCTION__, FALSE);
  4432. if (!$js_added) {
  4433. // Add the table drag JavaScript to the page before the module JavaScript
  4434. // to ensure that table drag behaviors are registered before any module
  4435. // uses it.
  4436. drupal_add_library('system', 'jquery.cookie');
  4437. drupal_add_js('misc/tabledrag.js', array('weight' => -1));
  4438. $js_added = TRUE;
  4439. }
  4440. // If a subgroup or source isn't set, assume it is the same as the group.
  4441. $target = isset($subgroup) ? $subgroup : $group;
  4442. $source = isset($source) ? $source : $target;
  4443. $settings['tableDrag'][$table_id][$group][] = array(
  4444. 'target' => $target,
  4445. 'source' => $source,
  4446. 'relationship' => $relationship,
  4447. 'action' => $action,
  4448. 'hidden' => $hidden,
  4449. 'limit' => $limit,
  4450. );
  4451. drupal_add_js($settings, 'setting');
  4452. }
  4453. /**
  4454. * Aggregates JavaScript files into a cache file in the files directory.
  4455. *
  4456. * The file name for the JavaScript cache file is generated from the hash of
  4457. * the aggregated contents of the files in $files. This forces proxies and
  4458. * browsers to download new JavaScript when the JavaScript changes.
  4459. *
  4460. * The cache file name is retrieved on a page load via a lookup variable that
  4461. * contains an associative array. The array key is the hash of the names in
  4462. * $files while the value is the cache file name. The cache file is generated
  4463. * in two cases. First, if there is no file name value for the key, which will
  4464. * happen if a new file name has been added to $files or after the lookup
  4465. * variable is emptied to force a rebuild of the cache. Second, the cache file
  4466. * is generated if it is missing on disk. Old cache files are not deleted
  4467. * immediately when the lookup variable is emptied, but are deleted after a set
  4468. * period by drupal_delete_file_if_stale(). This ensures that files referenced
  4469. * by a cached page will still be available.
  4470. *
  4471. * @param $files
  4472. * An array of JavaScript files to aggregate and compress into one file.
  4473. *
  4474. * @return
  4475. * The URI of the cache file, or FALSE if the file could not be saved.
  4476. */
  4477. function drupal_build_js_cache($files) {
  4478. $contents = '';
  4479. $uri = '';
  4480. $map = variable_get('drupal_js_cache_files', array());
  4481. $key = hash('sha256', serialize($files));
  4482. if (isset($map[$key])) {
  4483. $uri = $map[$key];
  4484. }
  4485. if (empty($uri) || !file_exists($uri)) {
  4486. // Build aggregate JS file.
  4487. foreach ($files as $path => $info) {
  4488. if ($info['preprocess']) {
  4489. // Append a ';' and a newline after each JS file to prevent them from running together.
  4490. $contents .= file_get_contents($path) . ";\n";
  4491. }
  4492. }
  4493. // Prefix filename to prevent blocking by firewalls which reject files
  4494. // starting with "ad*".
  4495. $filename = 'js_' . drupal_hash_base64($contents) . '.js';
  4496. // Create the js/ within the files folder.
  4497. $jspath = 'public://js';
  4498. $uri = $jspath . '/' . $filename;
  4499. // Create the JS file.
  4500. file_prepare_directory($jspath, FILE_CREATE_DIRECTORY);
  4501. if (!file_exists($uri) && !file_unmanaged_save_data($contents, $uri, FILE_EXISTS_REPLACE)) {
  4502. return FALSE;
  4503. }
  4504. // If JS gzip compression is enabled, clean URLs are enabled (which means
  4505. // that rewrite rules are working) and the zlib extension is available then
  4506. // create a gzipped version of this file. This file is served conditionally
  4507. // to browsers that accept gzip using .htaccess rules.
  4508. if (variable_get('js_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
  4509. if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($contents, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
  4510. return FALSE;
  4511. }
  4512. }
  4513. $map[$key] = $uri;
  4514. variable_set('drupal_js_cache_files', $map);
  4515. }
  4516. return $uri;
  4517. }
  4518. /**
  4519. * Deletes old cached JavaScript files and variables.
  4520. */
  4521. function drupal_clear_js_cache() {
  4522. variable_del('javascript_parsed');
  4523. variable_del('drupal_js_cache_files');
  4524. file_scan_directory('public://js', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
  4525. }
  4526. /**
  4527. * Converts a PHP variable into its JavaScript equivalent.
  4528. *
  4529. * We use HTML-safe strings, with several characters escaped.
  4530. *
  4531. * @see drupal_json_decode()
  4532. * @see drupal_json_encode_helper()
  4533. * @ingroup php_wrappers
  4534. */
  4535. function drupal_json_encode($var) {
  4536. // The PHP version cannot change within a request.
  4537. static $php530;
  4538. if (!isset($php530)) {
  4539. $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
  4540. }
  4541. if ($php530) {
  4542. // Encode <, >, ', &, and " using the json_encode() options parameter.
  4543. return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
  4544. }
  4545. // json_encode() escapes <, >, ', &, and " using its options parameter, but
  4546. // does not support this parameter prior to PHP 5.3.0. Use a helper instead.
  4547. include_once DRUPAL_ROOT . '/includes/json-encode.inc';
  4548. return drupal_json_encode_helper($var);
  4549. }
  4550. /**
  4551. * Converts an HTML-safe JSON string into its PHP equivalent.
  4552. *
  4553. * @see drupal_json_encode()
  4554. * @ingroup php_wrappers
  4555. */
  4556. function drupal_json_decode($var) {
  4557. return json_decode($var, TRUE);
  4558. }
  4559. /**
  4560. * Returns data in JSON format.
  4561. *
  4562. * This function should be used for JavaScript callback functions returning
  4563. * data in JSON format. It sets the header for JavaScript output.
  4564. *
  4565. * @param $var
  4566. * (optional) If set, the variable will be converted to JSON and output.
  4567. */
  4568. function drupal_json_output($var = NULL) {
  4569. // We are returning JSON, so tell the browser.
  4570. drupal_add_http_header('Content-Type', 'application/json');
  4571. if (isset($var)) {
  4572. echo drupal_json_encode($var);
  4573. }
  4574. }
  4575. /**
  4576. * Gets a salt useful for hardening against SQL injection.
  4577. *
  4578. * @return
  4579. * A salt based on information in settings.php, not in the database.
  4580. */
  4581. function drupal_get_hash_salt() {
  4582. global $drupal_hash_salt, $databases;
  4583. // If the $drupal_hash_salt variable is empty, a hash of the serialized
  4584. // database credentials is used as a fallback salt.
  4585. return empty($drupal_hash_salt) ? hash('sha256', serialize($databases)) : $drupal_hash_salt;
  4586. }
  4587. /**
  4588. * Ensures the private key variable used to generate tokens is set.
  4589. *
  4590. * @return
  4591. * The private key.
  4592. */
  4593. function drupal_get_private_key() {
  4594. if (!($key = variable_get('drupal_private_key', 0))) {
  4595. $key = drupal_hash_base64(drupal_random_bytes(55));
  4596. variable_set('drupal_private_key', $key);
  4597. }
  4598. return $key;
  4599. }
  4600. /**
  4601. * Generates a token based on $value, the user session, and the private key.
  4602. *
  4603. * @param $value
  4604. * An additional value to base the token on.
  4605. */
  4606. function drupal_get_token($value = '') {
  4607. return drupal_hmac_base64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());
  4608. }
  4609. /**
  4610. * Validates a token based on $value, the user session, and the private key.
  4611. *
  4612. * @param $token
  4613. * The token to be validated.
  4614. * @param $value
  4615. * An additional value to base the token on.
  4616. * @param $skip_anonymous
  4617. * Set to true to skip token validation for anonymous users.
  4618. *
  4619. * @return
  4620. * True for a valid token, false for an invalid token. When $skip_anonymous
  4621. * is true, the return value will always be true for anonymous users.
  4622. */
  4623. function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
  4624. global $user;
  4625. return (($skip_anonymous && $user->uid == 0) || ($token == drupal_get_token($value)));
  4626. }
  4627. function _drupal_bootstrap_full() {
  4628. static $called = FALSE;
  4629. if ($called) {
  4630. return;
  4631. }
  4632. $called = TRUE;
  4633. require_once DRUPAL_ROOT . '/' . variable_get('path_inc', 'includes/path.inc');
  4634. require_once DRUPAL_ROOT . '/includes/theme.inc';
  4635. require_once DRUPAL_ROOT . '/includes/pager.inc';
  4636. require_once DRUPAL_ROOT . '/' . variable_get('menu_inc', 'includes/menu.inc');
  4637. require_once DRUPAL_ROOT . '/includes/tablesort.inc';
  4638. require_once DRUPAL_ROOT . '/includes/file.inc';
  4639. require_once DRUPAL_ROOT . '/includes/unicode.inc';
  4640. require_once DRUPAL_ROOT . '/includes/image.inc';
  4641. require_once DRUPAL_ROOT . '/includes/form.inc';
  4642. require_once DRUPAL_ROOT . '/includes/mail.inc';
  4643. require_once DRUPAL_ROOT . '/includes/actions.inc';
  4644. require_once DRUPAL_ROOT . '/includes/ajax.inc';
  4645. require_once DRUPAL_ROOT . '/includes/token.inc';
  4646. require_once DRUPAL_ROOT . '/includes/errors.inc';
  4647. // Detect string handling method
  4648. unicode_check();
  4649. // Undo magic quotes
  4650. fix_gpc_magic();
  4651. // Load all enabled modules
  4652. module_load_all();
  4653. // Make sure all stream wrappers are registered.
  4654. file_get_stream_wrappers();
  4655. $test_info = &$GLOBALS['drupal_test_info'];
  4656. if (!empty($test_info['in_child_site'])) {
  4657. // Running inside the simpletest child site, log fatal errors to test
  4658. // specific file directory.
  4659. ini_set('log_errors', 1);
  4660. ini_set('error_log', 'public://error.log');
  4661. }
  4662. // Initialize $_GET['q'] prior to invoking hook_init().
  4663. drupal_path_initialize();
  4664. // Let all modules take action before the menu system handles the request.
  4665. // We do not want this while running update.php.
  4666. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
  4667. // Prior to invoking hook_init(), initialize the theme (potentially a custom
  4668. // one for this page), so that:
  4669. // - Modules with hook_init() implementations that call theme() or
  4670. // theme_get_registry() don't initialize the incorrect theme.
  4671. // - The theme can have hook_*_alter() implementations affect page building
  4672. // (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
  4673. // ahead of when rendering starts.
  4674. menu_set_custom_theme();
  4675. drupal_theme_initialize();
  4676. module_invoke_all('init');
  4677. }
  4678. }
  4679. /**
  4680. * Stores the current page in the cache.
  4681. *
  4682. * If page_compression is enabled, a gzipped version of the page is stored in
  4683. * the cache to avoid compressing the output on each request. The cache entry
  4684. * is unzipped in the relatively rare event that the page is requested by a
  4685. * client without gzip support.
  4686. *
  4687. * Page compression requires the PHP zlib extension
  4688. * (http://php.net/manual/en/ref.zlib.php).
  4689. *
  4690. * @see drupal_page_header()
  4691. */
  4692. function drupal_page_set_cache() {
  4693. global $base_root;
  4694. if (drupal_page_is_cacheable()) {
  4695. $cache = (object) array(
  4696. 'cid' => $base_root . request_uri(),
  4697. 'data' => array(
  4698. 'path' => $_GET['q'],
  4699. 'body' => ob_get_clean(),
  4700. 'title' => drupal_get_title(),
  4701. 'headers' => array(),
  4702. ),
  4703. 'expire' => CACHE_TEMPORARY,
  4704. 'created' => REQUEST_TIME,
  4705. );
  4706. // Restore preferred header names based on the lower-case names returned
  4707. // by drupal_get_http_header().
  4708. $header_names = _drupal_set_preferred_header_name();
  4709. foreach (drupal_get_http_header() as $name_lower => $value) {
  4710. $cache->data['headers'][$header_names[$name_lower]] = $value;
  4711. if ($name_lower == 'expires') {
  4712. // Use the actual timestamp from an Expires header if available.
  4713. $cache->expire = strtotime($value);
  4714. }
  4715. }
  4716. if ($cache->data['body']) {
  4717. if (variable_get('page_compression', TRUE) && extension_loaded('zlib')) {
  4718. $cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
  4719. }
  4720. cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire);
  4721. }
  4722. return $cache;
  4723. }
  4724. }
  4725. /**
  4726. * Executes a cron run when called.
  4727. *
  4728. * Do not call this function from a test. Use $this->cronRun() instead.
  4729. *
  4730. * @return
  4731. * TRUE if cron ran successfully.
  4732. */
  4733. function drupal_cron_run() {
  4734. // Allow execution to continue even if the request gets canceled.
  4735. @ignore_user_abort(TRUE);
  4736. // Prevent session information from being saved while cron is running.
  4737. drupal_save_session(FALSE);
  4738. // Force the current user to anonymous to ensure consistent permissions on
  4739. // cron runs.
  4740. $original_user = $GLOBALS['user'];
  4741. $GLOBALS['user'] = drupal_anonymous_user();
  4742. // Try to allocate enough time to run all the hook_cron implementations.
  4743. drupal_set_time_limit(240);
  4744. $return = FALSE;
  4745. // Grab the defined cron queues.
  4746. $queues = module_invoke_all('cron_queue_info');
  4747. drupal_alter('cron_queue_info', $queues);
  4748. // Try to acquire cron lock.
  4749. if (!lock_acquire('cron', 240.0)) {
  4750. // Cron is still running normally.
  4751. watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
  4752. }
  4753. else {
  4754. // Make sure every queue exists. There is no harm in trying to recreate an
  4755. // existing queue.
  4756. foreach ($queues as $queue_name => $info) {
  4757. DrupalQueue::get($queue_name)->createQueue();
  4758. }
  4759. // Register shutdown callback.
  4760. drupal_register_shutdown_function('drupal_cron_cleanup');
  4761. // Iterate through the modules calling their cron handlers (if any):
  4762. foreach (module_implements('cron') as $module) {
  4763. // Do not let an exception thrown by one module disturb another.
  4764. try {
  4765. module_invoke($module, 'cron');
  4766. }
  4767. catch (Exception $e) {
  4768. watchdog_exception('cron', $e);
  4769. }
  4770. }
  4771. // Record cron time.
  4772. variable_set('cron_last', REQUEST_TIME);
  4773. watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
  4774. // Release cron lock.
  4775. lock_release('cron');
  4776. // Return TRUE so other functions can check if it did run successfully
  4777. $return = TRUE;
  4778. }
  4779. foreach ($queues as $queue_name => $info) {
  4780. $function = $info['worker callback'];
  4781. $end = time() + (isset($info['time']) ? $info['time'] : 15);
  4782. $queue = DrupalQueue::get($queue_name);
  4783. while (time() < $end && ($item = $queue->claimItem())) {
  4784. $function($item->data);
  4785. $queue->deleteItem($item);
  4786. }
  4787. }
  4788. // Restore the user.
  4789. $GLOBALS['user'] = $original_user;
  4790. drupal_save_session(TRUE);
  4791. return $return;
  4792. }
  4793. /**
  4794. * Shutdown function: Performs cron cleanup.
  4795. *
  4796. * @see drupal_cron_run()
  4797. * @see drupal_register_shutdown_function()
  4798. */
  4799. function drupal_cron_cleanup() {
  4800. // See if the semaphore is still locked.
  4801. if (variable_get('cron_semaphore', FALSE)) {
  4802. watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);
  4803. // Release cron semaphore.
  4804. variable_del('cron_semaphore');
  4805. }
  4806. }
  4807. /**
  4808. * Returns information about system object files (modules, themes, etc.).
  4809. *
  4810. * This function is used to find all or some system object files (module files,
  4811. * theme files, etc.) that exist on the site. It searches in several locations,
  4812. * depending on what type of object you are looking for. For instance, if you
  4813. * are looking for modules and call:
  4814. * @code
  4815. * drupal_system_listing("/\.module$/", "modules", 'name', 0);
  4816. * @endcode
  4817. * this function will search the site-wide modules directory (i.e., /modules/),
  4818. * your install profile's directory (i.e.,
  4819. * /profiles/your_site_profile/modules/), the all-sites directory (i.e.,
  4820. * /sites/all/modules/), and your site-specific directory (i.e.,
  4821. * /sites/your_site_dir/modules/), in that order, and return information about
  4822. * all of the files ending in .module in those directories.
  4823. *
  4824. * The information is returned in an associative array, which can be keyed on
  4825. * the file name ($key = 'filename'), the file name without the extension ($key
  4826. * = 'name'), or the full file stream URI ($key = 'uri'). If you use a key of
  4827. * 'filename' or 'name', files found later in the search will take precedence
  4828. * over files found earlier (unless they belong to a module or theme not
  4829. * compatible with Drupal core); if you choose a key of 'uri', you will get all
  4830. * files found.
  4831. *
  4832. * @param string $mask
  4833. * The preg_match() regular expression for the files to find.
  4834. * @param string $directory
  4835. * The subdirectory name in which the files are found. For example,
  4836. * 'modules' will search in sub-directories of the top-level /modules
  4837. * directory, sub-directories of /sites/all/modules/, etc.
  4838. * @param string $key
  4839. * The key to be used for the associative array returned. Possible values are
  4840. * 'uri', for the file's URI; 'filename', for the basename of the file; and
  4841. * 'name' for the name of the file without the extension. If you choose 'name'
  4842. * or 'filename', only the highest-precedence file will be returned.
  4843. * @param int $min_depth
  4844. * Minimum depth of directories to return files from, relative to each
  4845. * directory searched. For instance, a minimum depth of 2 would find modules
  4846. * inside /modules/node/tests, but not modules directly in /modules/node.
  4847. *
  4848. * @return array
  4849. * An associative array of file objects, keyed on the chosen key. Each element
  4850. * in the array is an object containing file information, with properties:
  4851. * - 'uri': Full URI of the file.
  4852. * - 'filename': File name.
  4853. * - 'name': Name of file without the extension.
  4854. */
  4855. function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
  4856. $config = conf_path();
  4857. $profile = drupal_get_profile();
  4858. $searchdir = array($directory);
  4859. $files = array();
  4860. // The 'profiles' directory contains pristine collections of modules and
  4861. // themes as organized by a distribution. It is pristine in the same way
  4862. // that /modules is pristine for core; users should avoid changing anything
  4863. // there in favor of sites/all or sites/<domain> directories.
  4864. if (file_exists("profiles/$profile/$directory")) {
  4865. $searchdir[] = "profiles/$profile/$directory";
  4866. }
  4867. // Always search sites/all/* as well as the global directories.
  4868. $searchdir[] = 'sites/all/' . $directory;
  4869. if (file_exists("$config/$directory")) {
  4870. $searchdir[] = "$config/$directory";
  4871. }
  4872. // Get current list of items.
  4873. if (!function_exists('file_scan_directory')) {
  4874. require_once DRUPAL_ROOT . '/includes/file.inc';
  4875. }
  4876. foreach ($searchdir as $dir) {
  4877. $files_to_add = file_scan_directory($dir, $mask, array('key' => $key, 'min_depth' => $min_depth));
  4878. // Duplicate files found in later search directories take precedence over
  4879. // earlier ones, so we want them to overwrite keys in our resulting
  4880. // $files array.
  4881. // The exception to this is if the later file is from a module or theme not
  4882. // compatible with Drupal core. This may occur during upgrades of Drupal
  4883. // core when new modules exist in core while older contrib modules with the
  4884. // same name exist in a directory such as sites/all/modules/.
  4885. foreach (array_intersect_key($files_to_add, $files) as $file_key => $file) {
  4886. // If it has no info file, then we just behave liberally and accept the
  4887. // new resource on the list for merging.
  4888. if (file_exists($info_file = dirname($file->uri) . '/' . $file->name . '.info')) {
  4889. // Get the .info file for the module or theme this file belongs to.
  4890. $info = drupal_parse_info_file($info_file);
  4891. // If the module or theme is incompatible with Drupal core, remove it
  4892. // from the array for the current search directory, so it is not
  4893. // overwritten when merged with the $files array.
  4894. if (isset($info['core']) && $info['core'] != DRUPAL_CORE_COMPATIBILITY) {
  4895. unset($files_to_add[$file_key]);
  4896. }
  4897. }
  4898. }
  4899. $files = array_merge($files, $files_to_add);
  4900. }
  4901. return $files;
  4902. }
  4903. /**
  4904. * Sets the main page content value for later use.
  4905. *
  4906. * Given the nature of the Drupal page handling, this will be called once with
  4907. * a string or array. We store that and return it later as the block is being
  4908. * displayed.
  4909. *
  4910. * @param $content
  4911. * A string or renderable array representing the body of the page.
  4912. *
  4913. * @return
  4914. * If called without $content, a renderable array representing the body of
  4915. * the page.
  4916. */
  4917. function drupal_set_page_content($content = NULL) {
  4918. $content_block = &drupal_static(__FUNCTION__, NULL);
  4919. $main_content_display = &drupal_static('system_main_content_added', FALSE);
  4920. if (!empty($content)) {
  4921. $content_block = (is_array($content) ? $content : array('main' => array('#markup' => $content)));
  4922. }
  4923. else {
  4924. // Indicate that the main content has been requested. We assume that
  4925. // the module requesting the content will be adding it to the page.
  4926. // A module can indicate that it does not handle the content by setting
  4927. // the static variable back to FALSE after calling this function.
  4928. $main_content_display = TRUE;
  4929. return $content_block;
  4930. }
  4931. }
  4932. /**
  4933. * #pre_render callback to render #browsers into #prefix and #suffix.
  4934. *
  4935. * @param $elements
  4936. * A render array with a '#browsers' property. The '#browsers' property can
  4937. * contain any or all of the following keys:
  4938. * - 'IE': If FALSE, the element is not rendered by Internet Explorer. If
  4939. * TRUE, the element is rendered by Internet Explorer. Can also be a string
  4940. * containing an expression for Internet Explorer to evaluate as part of a
  4941. * conditional comment. For example, this can be set to 'lt IE 7' for the
  4942. * element to be rendered in Internet Explorer 6, but not in Internet
  4943. * Explorer 7 or higher. Defaults to TRUE.
  4944. * - '!IE': If FALSE, the element is not rendered by browsers other than
  4945. * Internet Explorer. If TRUE, the element is rendered by those browsers.
  4946. * Defaults to TRUE.
  4947. * Examples:
  4948. * - To render an element in all browsers, '#browsers' can be left out or set
  4949. * to array('IE' => TRUE, '!IE' => TRUE).
  4950. * - To render an element in Internet Explorer only, '#browsers' can be set
  4951. * to array('!IE' => FALSE).
  4952. * - To render an element in Internet Explorer 6 only, '#browsers' can be set
  4953. * to array('IE' => 'lt IE 7', '!IE' => FALSE).
  4954. * - To render an element in Internet Explorer 8 and higher and in all other
  4955. * browsers, '#browsers' can be set to array('IE' => 'gte IE 8').
  4956. *
  4957. * @return
  4958. * The passed-in element with markup for conditional comments potentially
  4959. * added to '#prefix' and '#suffix'.
  4960. */
  4961. function drupal_pre_render_conditional_comments($elements) {
  4962. $browsers = isset($elements['#browsers']) ? $elements['#browsers'] : array();
  4963. $browsers += array(
  4964. 'IE' => TRUE,
  4965. '!IE' => TRUE,
  4966. );
  4967. // If rendering in all browsers, no need for conditional comments.
  4968. if ($browsers['IE'] === TRUE && $browsers['!IE']) {
  4969. return $elements;
  4970. }
  4971. // Determine the conditional comment expression for Internet Explorer to
  4972. // evaluate.
  4973. if ($browsers['IE'] === TRUE) {
  4974. $expression = 'IE';
  4975. }
  4976. elseif ($browsers['IE'] === FALSE) {
  4977. $expression = '!IE';
  4978. }
  4979. else {
  4980. $expression = $browsers['IE'];
  4981. }
  4982. // Wrap the element's potentially existing #prefix and #suffix properties with
  4983. // conditional comment markup. The conditional comment expression is evaluated
  4984. // by Internet Explorer only. To control the rendering by other browsers,
  4985. // either the "downlevel-hidden" or "downlevel-revealed" technique must be
  4986. // used. See http://en.wikipedia.org/wiki/Conditional_comment for details.
  4987. $elements += array(
  4988. '#prefix' => '',
  4989. '#suffix' => '',
  4990. );
  4991. if (!$browsers['!IE']) {
  4992. // "downlevel-hidden".
  4993. $elements['#prefix'] = "\n<!--[if $expression]>\n" . $elements['#prefix'];
  4994. $elements['#suffix'] .= "<![endif]-->\n";
  4995. }
  4996. else {
  4997. // "downlevel-revealed".
  4998. $elements['#prefix'] = "\n<!--[if $expression]><!-->\n" . $elements['#prefix'];
  4999. $elements['#suffix'] .= "<!--<![endif]-->\n";
  5000. }
  5001. return $elements;
  5002. }
  5003. /**
  5004. * #pre_render callback to render a link into #markup.
  5005. *
  5006. * Doing so during pre_render gives modules a chance to alter the link parts.
  5007. *
  5008. * @param $elements
  5009. * A structured array whose keys form the arguments to l():
  5010. * - #title: The link text to pass as argument to l().
  5011. * - #href: The URL path component to pass as argument to l().
  5012. * - #options: (optional) An array of options to pass to l().
  5013. *
  5014. * @return
  5015. * The passed-in elements containing a rendered link in '#markup'.
  5016. */
  5017. function drupal_pre_render_link($element) {
  5018. // By default, link options to pass to l() are normally set in #options.
  5019. $element += array('#options' => array());
  5020. // However, within the scope of renderable elements, #attributes is a valid
  5021. // way to specify attributes, too. Take them into account, but do not override
  5022. // attributes from #options.
  5023. if (isset($element['#attributes'])) {
  5024. $element['#options'] += array('attributes' => array());
  5025. $element['#options']['attributes'] += $element['#attributes'];
  5026. }
  5027. // This #pre_render callback can be invoked from inside or outside of a Form
  5028. // API context, and depending on that, a HTML ID may be already set in
  5029. // different locations. #options should have precedence over Form API's #id.
  5030. // #attributes have been taken over into #options above already.
  5031. if (isset($element['#options']['attributes']['id'])) {
  5032. $element['#id'] = $element['#options']['attributes']['id'];
  5033. }
  5034. elseif (isset($element['#id'])) {
  5035. $element['#options']['attributes']['id'] = $element['#id'];
  5036. }
  5037. // Conditionally invoke ajax_pre_render_element(), if #ajax is set.
  5038. if (isset($element['#ajax']) && !isset($element['#ajax_processed'])) {
  5039. // If no HTML ID was found above, automatically create one.
  5040. if (!isset($element['#id'])) {
  5041. $element['#id'] = $element['#options']['attributes']['id'] = drupal_html_id('ajax-link');
  5042. }
  5043. // If #ajax['path] was not specified, use the href as Ajax request URL.
  5044. if (!isset($element['#ajax']['path'])) {
  5045. $element['#ajax']['path'] = $element['#href'];
  5046. $element['#ajax']['options'] = $element['#options'];
  5047. }
  5048. $element = ajax_pre_render_element($element);
  5049. }
  5050. $element['#markup'] = l($element['#title'], $element['#href'], $element['#options']);
  5051. return $element;
  5052. }
  5053. /**
  5054. * #pre_render callback that collects child links into a single array.
  5055. *
  5056. * This function can be added as a pre_render callback for a renderable array,
  5057. * usually one which will be themed by theme_links(). It iterates through all
  5058. * unrendered children of the element, collects any #links properties it finds,
  5059. * merges them into the parent element's #links array, and prevents those
  5060. * children from being rendered separately.
  5061. *
  5062. * The purpose of this is to allow links to be logically grouped into related
  5063. * categories, so that each child group can be rendered as its own list of
  5064. * links if drupal_render() is called on it, but calling drupal_render() on the
  5065. * parent element will still produce a single list containing all the remaining
  5066. * links, regardless of what group they were in.
  5067. *
  5068. * A typical example comes from node links, which are stored in a renderable
  5069. * array similar to this:
  5070. * @code
  5071. * $node->content['links'] = array(
  5072. * '#theme' => 'links__node',
  5073. * '#pre_render' = array('drupal_pre_render_links'),
  5074. * 'comment' => array(
  5075. * '#theme' => 'links__node__comment',
  5076. * '#links' => array(
  5077. * // An array of links associated with node comments, suitable for
  5078. * // passing in to theme_links().
  5079. * ),
  5080. * ),
  5081. * 'statistics' => array(
  5082. * '#theme' => 'links__node__statistics',
  5083. * '#links' => array(
  5084. * // An array of links associated with node statistics, suitable for
  5085. * // passing in to theme_links().
  5086. * ),
  5087. * ),
  5088. * 'translation' => array(
  5089. * '#theme' => 'links__node__translation',
  5090. * '#links' => array(
  5091. * // An array of links associated with node translation, suitable for
  5092. * // passing in to theme_links().
  5093. * ),
  5094. * ),
  5095. * );
  5096. * @endcode
  5097. *
  5098. * In this example, the links are grouped by functionality, which can be
  5099. * helpful to themers who want to display certain kinds of links independently.
  5100. * For example, adding this code to node.tpl.php will result in the comment
  5101. * links being rendered as a single list:
  5102. * @code
  5103. * print render($content['links']['comment']);
  5104. * @endcode
  5105. *
  5106. * (where $node->content has been transformed into $content before handing
  5107. * control to the node.tpl.php template).
  5108. *
  5109. * The pre_render function defined here allows the above flexibility, but also
  5110. * allows the following code to be used to render all remaining links into a
  5111. * single list, regardless of their group:
  5112. * @code
  5113. * print render($content['links']);
  5114. * @endcode
  5115. *
  5116. * In the above example, this will result in the statistics and translation
  5117. * links being rendered together in a single list (but not the comment links,
  5118. * which were rendered previously on their own).
  5119. *
  5120. * Because of the way this function works, the individual properties of each
  5121. * group (for example, a group-specific #theme property such as
  5122. * 'links__node__comment' in the example above, or any other property such as
  5123. * #attributes or #pre_render that is attached to it) are only used when that
  5124. * group is rendered on its own. When the group is rendered together with other
  5125. * children, these child-specific properties are ignored, and only the overall
  5126. * properties of the parent are used.
  5127. */
  5128. function drupal_pre_render_links($element) {
  5129. $element += array('#links' => array());
  5130. foreach (element_children($element) as $key) {
  5131. $child = &$element[$key];
  5132. // If the child has links which have not been printed yet and the user has
  5133. // access to it, merge its links in to the parent.
  5134. if (isset($child['#links']) && empty($child['#printed']) && (!isset($child['#access']) || $child['#access'])) {
  5135. $element['#links'] += $child['#links'];
  5136. // Mark the child as having been printed already (so that its links
  5137. // cannot be mistakenly rendered twice).
  5138. $child['#printed'] = TRUE;
  5139. }
  5140. }
  5141. return $element;
  5142. }
  5143. /**
  5144. * #pre_render callback to append contents in #markup to #children.
  5145. *
  5146. * This needs to be a #pre_render callback, because eventually assigned
  5147. * #theme_wrappers will expect the element's rendered content in #children.
  5148. * Note that if also a #theme is defined for the element, then the result of
  5149. * the theme callback will override #children.
  5150. *
  5151. * @param $elements
  5152. * A structured array using the #markup key.
  5153. *
  5154. * @return
  5155. * The passed-in elements, but #markup appended to #children.
  5156. *
  5157. * @see drupal_render()
  5158. */
  5159. function drupal_pre_render_markup($elements) {
  5160. $elements['#children'] = $elements['#markup'];
  5161. return $elements;
  5162. }
  5163. /**
  5164. * Renders the page, including all theming.
  5165. *
  5166. * @param $page
  5167. * A string or array representing the content of a page. The array consists of
  5168. * the following keys:
  5169. * - #type: Value is always 'page'. This pushes the theming through
  5170. * page.tpl.php (required).
  5171. * - #show_messages: Suppress drupal_get_message() items. Used by Batch
  5172. * API (optional).
  5173. *
  5174. * @see hook_page_alter()
  5175. * @see element_info()
  5176. */
  5177. function drupal_render_page($page) {
  5178. $main_content_display = &drupal_static('system_main_content_added', FALSE);
  5179. // Allow menu callbacks to return strings or arbitrary arrays to render.
  5180. // If the array returned is not of #type page directly, we need to fill
  5181. // in the page with defaults.
  5182. if (is_string($page) || (is_array($page) && (!isset($page['#type']) || ($page['#type'] != 'page')))) {
  5183. drupal_set_page_content($page);
  5184. $page = element_info('page');
  5185. }
  5186. // Modules can add elements to $page as needed in hook_page_build().
  5187. foreach (module_implements('page_build') as $module) {
  5188. $function = $module . '_page_build';
  5189. $function($page);
  5190. }
  5191. // Modules alter the $page as needed. Blocks are populated into regions like
  5192. // 'sidebar_first', 'footer', etc.
  5193. drupal_alter('page', $page);
  5194. // If no module has taken care of the main content, add it to the page now.
  5195. // This allows the site to still be usable even if no modules that
  5196. // control page regions (for example, the Block module) are enabled.
  5197. if (!$main_content_display) {
  5198. $page['content']['system_main'] = drupal_set_page_content();
  5199. }
  5200. return drupal_render($page);
  5201. }
  5202. /**
  5203. * Renders HTML given a structured array tree.
  5204. *
  5205. * Recursively iterates over each of the array elements, generating HTML code.
  5206. *
  5207. * Renderable arrays have two kinds of key/value pairs: properties and
  5208. * children. Properties have keys starting with '#' and their values influence
  5209. * how the array will be rendered. Children are all elements whose keys do not
  5210. * start with a '#'. Their values should be renderable arrays themselves,
  5211. * which will be rendered during the rendering of the parent array. The markup
  5212. * provided by the children is typically inserted into the markup generated by
  5213. * the parent array.
  5214. *
  5215. * HTML generation for a renderable array, and the treatment of any children,
  5216. * is controlled by two properties containing theme functions, #theme and
  5217. * #theme_wrappers.
  5218. *
  5219. * #theme is the theme function called first. If it is set and the element has
  5220. * any children, it is the responsibility of the theme function to render
  5221. * these children. For elements that are not allowed to have any children,
  5222. * e.g. buttons or textfields, the theme function can be used to render the
  5223. * element itself. If #theme is not present and the element has children, they
  5224. * are rendered and concatenated into a string by drupal_render_children().
  5225. *
  5226. * The #theme_wrappers property contains an array of theme functions which will
  5227. * be called, in order, after #theme has run. These can be used to add further
  5228. * markup around the rendered children; e.g., fieldsets add the required markup
  5229. * for a fieldset around their rendered child elements. All wrapper theme
  5230. * functions have to include the element's #children property in their output,
  5231. * as it contains the output of the previous theme functions and the rendered
  5232. * children.
  5233. *
  5234. * For example, for the form element type, by default only the #theme_wrappers
  5235. * property is set, which adds the form markup around the rendered child
  5236. * elements of the form. This allows you to set the #theme property on a
  5237. * specific form to a custom theme function, giving you complete control over
  5238. * the placement of the form's children while not at all having to deal with
  5239. * the form markup itself.
  5240. *
  5241. * drupal_render() can optionally cache the rendered output of elements to
  5242. * improve performance. To use drupal_render() caching, set the element's #cache
  5243. * property to an associative array with one or several of the following keys:
  5244. * - 'keys': An array of one or more keys that identify the element. If 'keys'
  5245. * is set, the cache ID is created automatically from these keys. See
  5246. * drupal_render_cid_create().
  5247. * - 'granularity' (optional): Define the cache granularity using binary
  5248. * combinations of the cache granularity constants, e.g.
  5249. * DRUPAL_CACHE_PER_USER to cache for each user separately or
  5250. * DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE to cache separately for each
  5251. * page and role. If not specified the element is cached globally for each
  5252. * theme and language.
  5253. * - 'cid': Specify the cache ID directly. Either 'keys' or 'cid' is required.
  5254. * If 'cid' is set, 'keys' and 'granularity' are ignored. Use only if you
  5255. * have special requirements.
  5256. * - 'expire': Set to one of the cache lifetime constants.
  5257. * - 'bin': Specify a cache bin to cache the element in. Defaults to 'cache'.
  5258. *
  5259. * This function is usually called from within another function, like
  5260. * drupal_get_form() or a theme function. Elements are sorted internally
  5261. * using uasort(). Since this is expensive, when passing already sorted
  5262. * elements to drupal_render(), for example from a database query, set
  5263. * $elements['#sorted'] = TRUE to avoid sorting them a second time.
  5264. *
  5265. * drupal_render() flags each element with a '#printed' status to indicate that
  5266. * the element has been rendered, which allows individual elements of a given
  5267. * array to be rendered independently and prevents them from being rendered
  5268. * more than once on subsequent calls to drupal_render() (e.g., as part of a
  5269. * larger array). If the same array or array element is passed more than once
  5270. * to drupal_render(), it simply returns a NULL value.
  5271. *
  5272. * @param $elements
  5273. * The structured array describing the data to be rendered.
  5274. *
  5275. * @return
  5276. * The rendered HTML.
  5277. */
  5278. function drupal_render(&$elements) {
  5279. // Early-return nothing if user does not have access.
  5280. if (empty($elements) || (isset($elements['#access']) && !$elements['#access'])) {
  5281. return;
  5282. }
  5283. // Do not print elements twice.
  5284. if (!empty($elements['#printed'])) {
  5285. return;
  5286. }
  5287. // Try to fetch the element's markup from cache and return.
  5288. if (isset($elements['#cache'])) {
  5289. $cached_output = drupal_render_cache_get($elements);
  5290. if ($cached_output !== FALSE) {
  5291. return $cached_output;
  5292. }
  5293. }
  5294. // If #markup is set, ensure #type is set. This allows to specify just #markup
  5295. // on an element without setting #type.
  5296. if (isset($elements['#markup']) && !isset($elements['#type'])) {
  5297. $elements['#type'] = 'markup';
  5298. }
  5299. // If the default values for this element have not been loaded yet, populate
  5300. // them.
  5301. if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
  5302. $elements += element_info($elements['#type']);
  5303. }
  5304. // Make any final changes to the element before it is rendered. This means
  5305. // that the $element or the children can be altered or corrected before the
  5306. // element is rendered into the final text.
  5307. if (isset($elements['#pre_render'])) {
  5308. foreach ($elements['#pre_render'] as $function) {
  5309. if (function_exists($function)) {
  5310. $elements = $function($elements);
  5311. }
  5312. }
  5313. }
  5314. // Allow #pre_render to abort rendering.
  5315. if (!empty($elements['#printed'])) {
  5316. return;
  5317. }
  5318. // Get the children of the element, sorted by weight.
  5319. $children = element_children($elements, TRUE);
  5320. // Initialize this element's #children, unless a #pre_render callback already
  5321. // preset #children.
  5322. if (!isset($elements['#children'])) {
  5323. $elements['#children'] = '';
  5324. }
  5325. // Call the element's #theme function if it is set. Then any children of the
  5326. // element have to be rendered there.
  5327. if (isset($elements['#theme'])) {
  5328. $elements['#children'] = theme($elements['#theme'], $elements);
  5329. }
  5330. // If #theme was not set and the element has children, render them now.
  5331. // This is the same process as drupal_render_children() but is inlined
  5332. // for speed.
  5333. if ($elements['#children'] == '') {
  5334. foreach ($children as $key) {
  5335. $elements['#children'] .= drupal_render($elements[$key]);
  5336. }
  5337. }
  5338. // Let the theme functions in #theme_wrappers add markup around the rendered
  5339. // children.
  5340. if (isset($elements['#theme_wrappers'])) {
  5341. foreach ($elements['#theme_wrappers'] as $theme_wrapper) {
  5342. $elements['#children'] = theme($theme_wrapper, $elements);
  5343. }
  5344. }
  5345. // Filter the outputted content and make any last changes before the
  5346. // content is sent to the browser. The changes are made on $content
  5347. // which allows the output'ed text to be filtered.
  5348. if (isset($elements['#post_render'])) {
  5349. foreach ($elements['#post_render'] as $function) {
  5350. if (function_exists($function)) {
  5351. $elements['#children'] = $function($elements['#children'], $elements);
  5352. }
  5353. }
  5354. }
  5355. // Add any JavaScript state information associated with the element.
  5356. if (!empty($elements['#states'])) {
  5357. drupal_process_states($elements);
  5358. }
  5359. // Add additional libraries, CSS, JavaScript an other custom
  5360. // attached data associated with this element.
  5361. if (!empty($elements['#attached'])) {
  5362. drupal_process_attached($elements);
  5363. }
  5364. $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
  5365. $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
  5366. $output = $prefix . $elements['#children'] . $suffix;
  5367. // Cache the processed element if #cache is set.
  5368. if (isset($elements['#cache'])) {
  5369. drupal_render_cache_set($output, $elements);
  5370. }
  5371. $elements['#printed'] = TRUE;
  5372. return $output;
  5373. }
  5374. /**
  5375. * Renders children of an element and concatenates them.
  5376. *
  5377. * This renders all children of an element using drupal_render() and then
  5378. * joins them together into a single string.
  5379. *
  5380. * @param $element
  5381. * The structured array whose children shall be rendered.
  5382. * @param $children_keys
  5383. * If the keys of the element's children are already known, they can be passed
  5384. * in to save another run of element_children().
  5385. */
  5386. function drupal_render_children(&$element, $children_keys = NULL) {
  5387. if ($children_keys === NULL) {
  5388. $children_keys = element_children($element);
  5389. }
  5390. $output = '';
  5391. foreach ($children_keys as $key) {
  5392. if (!empty($element[$key])) {
  5393. $output .= drupal_render($element[$key]);
  5394. }
  5395. }
  5396. return $output;
  5397. }
  5398. /**
  5399. * Renders an element.
  5400. *
  5401. * This function renders an element using drupal_render(). The top level
  5402. * element is shown with show() before rendering, so it will always be rendered
  5403. * even if hide() had been previously used on it.
  5404. *
  5405. * @param $element
  5406. * The element to be rendered.
  5407. *
  5408. * @return
  5409. * The rendered element.
  5410. *
  5411. * @see drupal_render()
  5412. * @see show()
  5413. * @see hide()
  5414. */
  5415. function render(&$element) {
  5416. if (is_array($element)) {
  5417. show($element);
  5418. return drupal_render($element);
  5419. }
  5420. else {
  5421. // Safe-guard for inappropriate use of render() on flat variables: return
  5422. // the variable as-is.
  5423. return $element;
  5424. }
  5425. }
  5426. /**
  5427. * Hides an element from later rendering.
  5428. *
  5429. * The first time render() or drupal_render() is called on an element tree,
  5430. * as each element in the tree is rendered, it is marked with a #printed flag
  5431. * and the rendered children of the element are cached. Subsequent calls to
  5432. * render() or drupal_render() will not traverse the child tree of this element
  5433. * again: they will just use the cached children. So if you want to hide an
  5434. * element, be sure to call hide() on the element before its parent tree is
  5435. * rendered for the first time, as it will have no effect on subsequent
  5436. * renderings of the parent tree.
  5437. *
  5438. * @param $element
  5439. * The element to be hidden.
  5440. *
  5441. * @return
  5442. * The element.
  5443. *
  5444. * @see render()
  5445. * @see show()
  5446. */
  5447. function hide(&$element) {
  5448. $element['#printed'] = TRUE;
  5449. return $element;
  5450. }
  5451. /**
  5452. * Shows a hidden element for later rendering.
  5453. *
  5454. * You can also use render($element), which shows the element while rendering
  5455. * it.
  5456. *
  5457. * The first time render() or drupal_render() is called on an element tree,
  5458. * as each element in the tree is rendered, it is marked with a #printed flag
  5459. * and the rendered children of the element are cached. Subsequent calls to
  5460. * render() or drupal_render() will not traverse the child tree of this element
  5461. * again: they will just use the cached children. So if you want to show an
  5462. * element, be sure to call show() on the element before its parent tree is
  5463. * rendered for the first time, as it will have no effect on subsequent
  5464. * renderings of the parent tree.
  5465. *
  5466. * @param $element
  5467. * The element to be shown.
  5468. *
  5469. * @return
  5470. * The element.
  5471. *
  5472. * @see render()
  5473. * @see hide()
  5474. */
  5475. function show(&$element) {
  5476. $element['#printed'] = FALSE;
  5477. return $element;
  5478. }
  5479. /**
  5480. * Gets the rendered output of a renderable element from the cache.
  5481. *
  5482. * @param $elements
  5483. * A renderable array.
  5484. *
  5485. * @return
  5486. * A markup string containing the rendered content of the element, or FALSE
  5487. * if no cached copy of the element is available.
  5488. *
  5489. * @see drupal_render()
  5490. * @see drupal_render_cache_set()
  5491. */
  5492. function drupal_render_cache_get($elements) {
  5493. if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
  5494. return FALSE;
  5495. }
  5496. $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
  5497. if (!empty($cid) && $cache = cache_get($cid, $bin)) {
  5498. // Add additional libraries, JavaScript, CSS and other data attached
  5499. // to this element.
  5500. if (isset($cache->data['#attached'])) {
  5501. drupal_process_attached($cache->data);
  5502. }
  5503. // Return the rendered output.
  5504. return $cache->data['#markup'];
  5505. }
  5506. return FALSE;
  5507. }
  5508. /**
  5509. * Caches the rendered output of a renderable element.
  5510. *
  5511. * This is called by drupal_render() if the #cache property is set on an
  5512. * element.
  5513. *
  5514. * @param $markup
  5515. * The rendered output string of $elements.
  5516. * @param $elements
  5517. * A renderable array.
  5518. *
  5519. * @see drupal_render_cache_get()
  5520. */
  5521. function drupal_render_cache_set(&$markup, $elements) {
  5522. // Create the cache ID for the element.
  5523. if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
  5524. return FALSE;
  5525. }
  5526. // Cache implementations are allowed to modify the markup, to support
  5527. // replacing markup with edge-side include commands. The supporting cache
  5528. // backend will store the markup in some other key (like
  5529. // $data['#real-value']) and return an include command instead. When the
  5530. // ESI command is executed by the content accelerator, the real value can
  5531. // be retrieved and used.
  5532. $data['#markup'] = &$markup;
  5533. // Persist attached data associated with this element.
  5534. $attached = drupal_render_collect_attached($elements, TRUE);
  5535. if ($attached) {
  5536. $data['#attached'] = $attached;
  5537. }
  5538. $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
  5539. $expire = isset($elements['#cache']['expire']) ? $elements['#cache']['expire'] : CACHE_PERMANENT;
  5540. cache_set($cid, $data, $bin, $expire);
  5541. }
  5542. /**
  5543. * Collects #attached for an element and its children into a single array.
  5544. *
  5545. * When caching elements, it is necessary to collect all libraries, JavaScript
  5546. * and CSS into a single array, from both the element itself and all child
  5547. * elements. This allows drupal_render() to add these back to the page when the
  5548. * element is returned from cache.
  5549. *
  5550. * @param $elements
  5551. * The element to collect #attached from.
  5552. * @param $return
  5553. * Whether to return the attached elements and reset the internal static.
  5554. *
  5555. * @return
  5556. * The #attached array for this element and its descendants.
  5557. */
  5558. function drupal_render_collect_attached($elements, $return = FALSE) {
  5559. $attached = &drupal_static(__FUNCTION__, array());
  5560. // Collect all #attached for this element.
  5561. if (isset($elements['#attached'])) {
  5562. foreach ($elements['#attached'] as $key => $value) {
  5563. if (!isset($attached[$key])) {
  5564. $attached[$key] = array();
  5565. }
  5566. $attached[$key] = array_merge($attached[$key], $value);
  5567. }
  5568. }
  5569. if ($children = element_children($elements)) {
  5570. foreach ($children as $child) {
  5571. drupal_render_collect_attached($elements[$child]);
  5572. }
  5573. }
  5574. // If this was the first call to the function, return all attached elements
  5575. // and reset the static cache.
  5576. if ($return) {
  5577. $return = $attached;
  5578. $attached = array();
  5579. return $return;
  5580. }
  5581. }
  5582. /**
  5583. * Prepares an element for caching based on a query.
  5584. *
  5585. * This smart caching strategy saves Drupal from querying and rendering to HTML
  5586. * when the underlying query is unchanged.
  5587. *
  5588. * Expensive queries should use the query builder to create the query and then
  5589. * call this function. Executing the query and formatting results should happen
  5590. * in a #pre_render callback.
  5591. *
  5592. * @param $query
  5593. * A select query object as returned by db_select().
  5594. * @param $function
  5595. * The name of the function doing this caching. A _pre_render suffix will be
  5596. * added to this string and is also part of the cache key in
  5597. * drupal_render_cache_set() and drupal_render_cache_get().
  5598. * @param $expire
  5599. * The cache expire time, passed eventually to cache_set().
  5600. * @param $granularity
  5601. * One or more granularity constants passed to drupal_render_cid_parts().
  5602. *
  5603. * @return
  5604. * A renderable array with the following keys and values:
  5605. * - #query: The passed-in $query.
  5606. * - #pre_render: $function with a _pre_render suffix.
  5607. * - #cache: An associative array prepared for drupal_render_cache_set().
  5608. */
  5609. function drupal_render_cache_by_query($query, $function, $expire = CACHE_TEMPORARY, $granularity = NULL) {
  5610. $cache_keys = array_merge(array($function), drupal_render_cid_parts($granularity));
  5611. $query->preExecute();
  5612. $cache_keys[] = hash('sha256', serialize(array((string) $query, $query->getArguments())));
  5613. return array(
  5614. '#query' => $query,
  5615. '#pre_render' => array($function . '_pre_render'),
  5616. '#cache' => array(
  5617. 'keys' => $cache_keys,
  5618. 'expire' => $expire,
  5619. ),
  5620. );
  5621. }
  5622. /**
  5623. * Returns cache ID parts for building a cache ID.
  5624. *
  5625. * @param $granularity
  5626. * One or more cache granularity constants. For example, to cache separately
  5627. * for each user, use DRUPAL_CACHE_PER_USER. To cache separately for each
  5628. * page and role, use the expression:
  5629. * @code
  5630. * DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE
  5631. * @endcode
  5632. *
  5633. * @return
  5634. * An array of cache ID parts, always containing the active theme. If the
  5635. * locale module is enabled it also contains the active language. If
  5636. * $granularity was passed in, more parts are added.
  5637. */
  5638. function drupal_render_cid_parts($granularity = NULL) {
  5639. global $theme, $base_root, $user;
  5640. $cid_parts[] = $theme;
  5641. // If Locale is enabled but we have only one language we do not need it as cid
  5642. // part.
  5643. if (drupal_multilingual()) {
  5644. foreach (language_types_configurable() as $language_type) {
  5645. $cid_parts[] = $GLOBALS[$language_type]->language;
  5646. }
  5647. }
  5648. if (!empty($granularity)) {
  5649. // 'PER_ROLE' and 'PER_USER' are mutually exclusive. 'PER_USER' can be a
  5650. // resource drag for sites with many users, so when a module is being
  5651. // equivocal, we favor the less expensive 'PER_ROLE' pattern.
  5652. if ($granularity & DRUPAL_CACHE_PER_ROLE) {
  5653. $cid_parts[] = 'r.' . implode(',', array_keys($user->roles));
  5654. }
  5655. elseif ($granularity & DRUPAL_CACHE_PER_USER) {
  5656. $cid_parts[] = "u.$user->uid";
  5657. }
  5658. if ($granularity & DRUPAL_CACHE_PER_PAGE) {
  5659. $cid_parts[] = $base_root . request_uri();
  5660. }
  5661. }
  5662. return $cid_parts;
  5663. }
  5664. /**
  5665. * Creates the cache ID for a renderable element.
  5666. *
  5667. * This creates the cache ID string, either by returning the #cache['cid']
  5668. * property if present or by building the cache ID out of the #cache['keys']
  5669. * and, optionally, the #cache['granularity'] properties.
  5670. *
  5671. * @param $elements
  5672. * A renderable array.
  5673. *
  5674. * @return
  5675. * The cache ID string, or FALSE if the element may not be cached.
  5676. */
  5677. function drupal_render_cid_create($elements) {
  5678. if (isset($elements['#cache']['cid'])) {
  5679. return $elements['#cache']['cid'];
  5680. }
  5681. elseif (isset($elements['#cache']['keys'])) {
  5682. $granularity = isset($elements['#cache']['granularity']) ? $elements['#cache']['granularity'] : NULL;
  5683. // Merge in additional cache ID parts based provided by drupal_render_cid_parts().
  5684. $cid_parts = array_merge($elements['#cache']['keys'], drupal_render_cid_parts($granularity));
  5685. return implode(':', $cid_parts);
  5686. }
  5687. return FALSE;
  5688. }
  5689. /**
  5690. * Function used by uasort to sort structured arrays by weight.
  5691. */
  5692. function element_sort($a, $b) {
  5693. $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
  5694. $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
  5695. if ($a_weight == $b_weight) {
  5696. return 0;
  5697. }
  5698. return ($a_weight < $b_weight) ? -1 : 1;
  5699. }
  5700. /**
  5701. * Array sorting callback; sorts elements by title.
  5702. */
  5703. function element_sort_by_title($a, $b) {
  5704. $a_title = (is_array($a) && isset($a['#title'])) ? $a['#title'] : '';
  5705. $b_title = (is_array($b) && isset($b['#title'])) ? $b['#title'] : '';
  5706. return strnatcasecmp($a_title, $b_title);
  5707. }
  5708. /**
  5709. * Retrieves the default properties for the defined element type.
  5710. *
  5711. * @param $type
  5712. * An element type as defined by hook_element_info().
  5713. */
  5714. function element_info($type) {
  5715. // Use the advanced drupal_static() pattern, since this is called very often.
  5716. static $drupal_static_fast;
  5717. if (!isset($drupal_static_fast)) {
  5718. $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__);
  5719. }
  5720. $cache = &$drupal_static_fast['cache'];
  5721. if (!isset($cache)) {
  5722. $cache = module_invoke_all('element_info');
  5723. foreach ($cache as $element_type => $info) {
  5724. $cache[$element_type]['#type'] = $element_type;
  5725. }
  5726. // Allow modules to alter the element type defaults.
  5727. drupal_alter('element_info', $cache);
  5728. }
  5729. return isset($cache[$type]) ? $cache[$type] : array();
  5730. }
  5731. /**
  5732. * Retrieves a single property for the defined element type.
  5733. *
  5734. * @param $type
  5735. * An element type as defined by hook_element_info().
  5736. * @param $property_name
  5737. * The property within the element type that should be returned.
  5738. * @param $default
  5739. * (Optional) The value to return if the element type does not specify a
  5740. * value for the property. Defaults to NULL.
  5741. */
  5742. function element_info_property($type, $property_name, $default = NULL) {
  5743. return (($info = element_info($type)) && array_key_exists($property_name, $info)) ? $info[$property_name] : $default;
  5744. }
  5745. /**
  5746. * Function used by uasort to sort structured arrays by weight, without the property weight prefix.
  5747. */
  5748. function drupal_sort_weight($a, $b) {
  5749. $a_weight = (is_array($a) && isset($a['weight'])) ? $a['weight'] : 0;
  5750. $b_weight = (is_array($b) && isset($b['weight'])) ? $b['weight'] : 0;
  5751. if ($a_weight == $b_weight) {
  5752. return 0;
  5753. }
  5754. return ($a_weight < $b_weight) ? -1 : 1;
  5755. }
  5756. /**
  5757. * Array sorting callback; sorts elements by 'title' key.
  5758. */
  5759. function drupal_sort_title($a, $b) {
  5760. if (!isset($b['title'])) {
  5761. return -1;
  5762. }
  5763. if (!isset($a['title'])) {
  5764. return 1;
  5765. }
  5766. return strcasecmp($a['title'], $b['title']);
  5767. }
  5768. /**
  5769. * Checks if the key is a property.
  5770. */
  5771. function element_property($key) {
  5772. return $key[0] == '#';
  5773. }
  5774. /**
  5775. * Gets properties of a structured array element (keys beginning with '#').
  5776. */
  5777. function element_properties($element) {
  5778. return array_filter(array_keys((array) $element), 'element_property');
  5779. }
  5780. /**
  5781. * Checks if the key is a child.
  5782. */
  5783. function element_child($key) {
  5784. return !isset($key[0]) || $key[0] != '#';
  5785. }
  5786. /**
  5787. * Identifies the children of an element array, optionally sorted by weight.
  5788. *
  5789. * The children of a element array are those key/value pairs whose key does
  5790. * not start with a '#'. See drupal_render() for details.
  5791. *
  5792. * @param $elements
  5793. * The element array whose children are to be identified.
  5794. * @param $sort
  5795. * Boolean to indicate whether the children should be sorted by weight.
  5796. *
  5797. * @return
  5798. * The array keys of the element's children.
  5799. */
  5800. function element_children(&$elements, $sort = FALSE) {
  5801. // Do not attempt to sort elements which have already been sorted.
  5802. $sort = isset($elements['#sorted']) ? !$elements['#sorted'] : $sort;
  5803. // Filter out properties from the element, leaving only children.
  5804. $children = array();
  5805. $sortable = FALSE;
  5806. foreach ($elements as $key => $value) {
  5807. if ($key === '' || $key[0] !== '#') {
  5808. $children[$key] = $value;
  5809. if (is_array($value) && isset($value['#weight'])) {
  5810. $sortable = TRUE;
  5811. }
  5812. }
  5813. }
  5814. // Sort the children if necessary.
  5815. if ($sort && $sortable) {
  5816. uasort($children, 'element_sort');
  5817. // Put the sorted children back into $elements in the correct order, to
  5818. // preserve sorting if the same element is passed through
  5819. // element_children() twice.
  5820. foreach ($children as $key => $child) {
  5821. unset($elements[$key]);
  5822. $elements[$key] = $child;
  5823. }
  5824. $elements['#sorted'] = TRUE;
  5825. }
  5826. return array_keys($children);
  5827. }
  5828. /**
  5829. * Returns the visible children of an element.
  5830. *
  5831. * @param $elements
  5832. * The parent element.
  5833. *
  5834. * @return
  5835. * The array keys of the element's visible children.
  5836. */
  5837. function element_get_visible_children(array $elements) {
  5838. $visible_children = array();
  5839. foreach (element_children($elements) as $key) {
  5840. $child = $elements[$key];
  5841. // Skip un-accessible children.
  5842. if (isset($child['#access']) && !$child['#access']) {
  5843. continue;
  5844. }
  5845. // Skip value and hidden elements, since they are not rendered.
  5846. if (isset($child['#type']) && in_array($child['#type'], array('value', 'hidden'))) {
  5847. continue;
  5848. }
  5849. $visible_children[$key] = $child;
  5850. }
  5851. return array_keys($visible_children);
  5852. }
  5853. /**
  5854. * Sets HTML attributes based on element properties.
  5855. *
  5856. * @param $element
  5857. * The renderable element to process.
  5858. * @param $map
  5859. * An associative array whose keys are element property names and whose values
  5860. * are the HTML attribute names to set for corresponding the property; e.g.,
  5861. * array('#propertyname' => 'attributename'). If both names are identical
  5862. * except for the leading '#', then an attribute name value is sufficient and
  5863. * no property name needs to be specified.
  5864. */
  5865. function element_set_attributes(array &$element, array $map) {
  5866. foreach ($map as $property => $attribute) {
  5867. // If the key is numeric, the attribute name needs to be taken over.
  5868. if (is_int($property)) {
  5869. $property = '#' . $attribute;
  5870. }
  5871. // Do not overwrite already existing attributes.
  5872. if (isset($element[$property]) && !isset($element['#attributes'][$attribute])) {
  5873. $element['#attributes'][$attribute] = $element[$property];
  5874. }
  5875. }
  5876. }
  5877. /**
  5878. * Sets a value in a nested array with variable depth.
  5879. *
  5880. * This helper function should be used when the depth of the array element you
  5881. * are changing may vary (that is, the number of parent keys is variable). It
  5882. * is primarily used for form structures and renderable arrays.
  5883. *
  5884. * Example:
  5885. * @code
  5886. * // Assume you have a 'signature' element somewhere in a form. It might be:
  5887. * $form['signature_settings']['signature'] = array(
  5888. * '#type' => 'text_format',
  5889. * '#title' => t('Signature'),
  5890. * );
  5891. * // Or, it might be further nested:
  5892. * $form['signature_settings']['user']['signature'] = array(
  5893. * '#type' => 'text_format',
  5894. * '#title' => t('Signature'),
  5895. * );
  5896. * @endcode
  5897. *
  5898. * To deal with the situation, the code needs to figure out the route to the
  5899. * element, given an array of parents that is either
  5900. * @code array('signature_settings', 'signature') @endcode in the first case or
  5901. * @code array('signature_settings', 'user', 'signature') @endcode in the second
  5902. * case.
  5903. *
  5904. * Without this helper function the only way to set the signature element in one
  5905. * line would be using eval(), which should be avoided:
  5906. * @code
  5907. * // Do not do this! Avoid eval().
  5908. * eval('$form[\'' . implode("']['", $parents) . '\'] = $element;');
  5909. * @endcode
  5910. *
  5911. * Instead, use this helper function:
  5912. * @code
  5913. * drupal_array_set_nested_value($form, $parents, $element);
  5914. * @endcode
  5915. *
  5916. * However if the number of array parent keys is static, the value should always
  5917. * be set directly rather than calling this function. For instance, for the
  5918. * first example we could just do:
  5919. * @code
  5920. * $form['signature_settings']['signature'] = $element;
  5921. * @endcode
  5922. *
  5923. * @param $array
  5924. * A reference to the array to modify.
  5925. * @param $parents
  5926. * An array of parent keys, starting with the outermost key.
  5927. * @param $value
  5928. * The value to set.
  5929. * @param $force
  5930. * (Optional) If TRUE, the value is forced into the structure even if it
  5931. * requires the deletion of an already existing non-array parent value. If
  5932. * FALSE, PHP throws an error if trying to add into a value that is not an
  5933. * array. Defaults to FALSE.
  5934. *
  5935. * @see drupal_array_get_nested_value()
  5936. */
  5937. function drupal_array_set_nested_value(array &$array, array $parents, $value, $force = FALSE) {
  5938. $ref = &$array;
  5939. foreach ($parents as $parent) {
  5940. // PHP auto-creates container arrays and NULL entries without error if $ref
  5941. // is NULL, but throws an error if $ref is set, but not an array.
  5942. if ($force && isset($ref) && !is_array($ref)) {
  5943. $ref = array();
  5944. }
  5945. $ref = &$ref[$parent];
  5946. }
  5947. $ref = $value;
  5948. }
  5949. /**
  5950. * Retrieves a value from a nested array with variable depth.
  5951. *
  5952. * This helper function should be used when the depth of the array element being
  5953. * retrieved may vary (that is, the number of parent keys is variable). It is
  5954. * primarily used for form structures and renderable arrays.
  5955. *
  5956. * Without this helper function the only way to get a nested array value with
  5957. * variable depth in one line would be using eval(), which should be avoided:
  5958. * @code
  5959. * // Do not do this! Avoid eval().
  5960. * // May also throw a PHP notice, if the variable array keys do not exist.
  5961. * eval('$value = $array[\'' . implode("']['", $parents) . "'];");
  5962. * @endcode
  5963. *
  5964. * Instead, use this helper function:
  5965. * @code
  5966. * $value = drupal_array_get_nested_value($form, $parents);
  5967. * @endcode
  5968. *
  5969. * The return value will be NULL, regardless of whether the actual value is NULL
  5970. * or whether the requested key does not exist. If it is required to know
  5971. * whether the nested array key actually exists, pass a third argument that is
  5972. * altered by reference:
  5973. * @code
  5974. * $key_exists = NULL;
  5975. * $value = drupal_array_get_nested_value($form, $parents, $key_exists);
  5976. * if ($key_exists) {
  5977. * // ... do something with $value ...
  5978. * }
  5979. * @endcode
  5980. *
  5981. * However if the number of array parent keys is static, the value should always
  5982. * be retrieved directly rather than calling this function. For instance:
  5983. * @code
  5984. * $value = $form['signature_settings']['signature'];
  5985. * @endcode
  5986. *
  5987. * @param $array
  5988. * The array from which to get the value.
  5989. * @param $parents
  5990. * An array of parent keys of the value, starting with the outermost key.
  5991. * @param $key_exists
  5992. * (optional) If given, an already defined variable that is altered by
  5993. * reference.
  5994. *
  5995. * @return
  5996. * The requested nested value. Possibly NULL if the value is NULL or not all
  5997. * nested parent keys exist. $key_exists is altered by reference and is a
  5998. * Boolean that indicates whether all nested parent keys exist (TRUE) or not
  5999. * (FALSE). This allows to distinguish between the two possibilities when NULL
  6000. * is returned.
  6001. *
  6002. * @see drupal_array_set_nested_value()
  6003. */
  6004. function drupal_array_get_nested_value(array &$array, array $parents, &$key_exists = NULL) {
  6005. $ref = &$array;
  6006. foreach ($parents as $parent) {
  6007. if (is_array($ref) && array_key_exists($parent, $ref)) {
  6008. $ref = &$ref[$parent];
  6009. }
  6010. else {
  6011. $key_exists = FALSE;
  6012. return NULL;
  6013. }
  6014. }
  6015. $key_exists = TRUE;
  6016. return $ref;
  6017. }
  6018. /**
  6019. * Determines whether a nested array contains the requested keys.
  6020. *
  6021. * This helper function should be used when the depth of the array element to be
  6022. * checked may vary (that is, the number of parent keys is variable). See
  6023. * drupal_array_set_nested_value() for details. It is primarily used for form
  6024. * structures and renderable arrays.
  6025. *
  6026. * If it is required to also get the value of the checked nested key, use
  6027. * drupal_array_get_nested_value() instead.
  6028. *
  6029. * If the number of array parent keys is static, this helper function is
  6030. * unnecessary and the following code can be used instead:
  6031. * @code
  6032. * $value_exists = isset($form['signature_settings']['signature']);
  6033. * $key_exists = array_key_exists('signature', $form['signature_settings']);
  6034. * @endcode
  6035. *
  6036. * @param $array
  6037. * The array with the value to check for.
  6038. * @param $parents
  6039. * An array of parent keys of the value, starting with the outermost key.
  6040. *
  6041. * @return
  6042. * TRUE if all the parent keys exist, FALSE otherwise.
  6043. *
  6044. * @see drupal_array_get_nested_value()
  6045. */
  6046. function drupal_array_nested_key_exists(array $array, array $parents) {
  6047. // Although this function is similar to PHP's array_key_exists(), its
  6048. // arguments should be consistent with drupal_array_get_nested_value().
  6049. $key_exists = NULL;
  6050. drupal_array_get_nested_value($array, $parents, $key_exists);
  6051. return $key_exists;
  6052. }
  6053. /**
  6054. * Provides theme registration for themes across .inc files.
  6055. */
  6056. function drupal_common_theme() {
  6057. return array(
  6058. // From theme.inc.
  6059. 'html' => array(
  6060. 'render element' => 'page',
  6061. 'template' => 'html',
  6062. ),
  6063. 'page' => array(
  6064. 'render element' => 'page',
  6065. 'template' => 'page',
  6066. ),
  6067. 'region' => array(
  6068. 'render element' => 'elements',
  6069. 'template' => 'region',
  6070. ),
  6071. 'status_messages' => array(
  6072. 'variables' => array('display' => NULL),
  6073. ),
  6074. 'link' => array(
  6075. 'variables' => array('text' => NULL, 'path' => NULL, 'options' => array()),
  6076. ),
  6077. 'links' => array(
  6078. 'variables' => array('links' => NULL, 'attributes' => array('class' => array('links')), 'heading' => array()),
  6079. ),
  6080. 'image' => array(
  6081. // HTML 4 and XHTML 1.0 always require an alt attribute. The HTML 5 draft
  6082. // allows the alt attribute to be omitted in some cases. Therefore,
  6083. // default the alt attribute to an empty string, but allow code calling
  6084. // theme('image') to pass explicit NULL for it to be omitted. Usually,
  6085. // neither omission nor an empty string satisfies accessibility
  6086. // requirements, so it is strongly encouraged for code calling
  6087. // theme('image') to pass a meaningful value for the alt variable.
  6088. // - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
  6089. // - http://www.w3.org/TR/xhtml1/dtds.html
  6090. // - http://dev.w3.org/html5/spec/Overview.html#alt
  6091. // The title attribute is optional in all cases, so it is omitted by
  6092. // default.
  6093. 'variables' => array('path' => NULL, 'width' => NULL, 'height' => NULL, 'alt' => '', 'title' => NULL, 'attributes' => array()),
  6094. ),
  6095. 'breadcrumb' => array(
  6096. 'variables' => array('breadcrumb' => NULL),
  6097. ),
  6098. 'help' => array(
  6099. 'variables' => array(),
  6100. ),
  6101. 'table' => array(
  6102. 'variables' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL, 'colgroups' => array(), 'sticky' => TRUE, 'empty' => ''),
  6103. ),
  6104. 'tablesort_indicator' => array(
  6105. 'variables' => array('style' => NULL),
  6106. ),
  6107. 'mark' => array(
  6108. 'variables' => array('type' => MARK_NEW),
  6109. ),
  6110. 'item_list' => array(
  6111. 'variables' => array('items' => array(), 'title' => NULL, 'type' => 'ul', 'attributes' => array()),
  6112. ),
  6113. 'more_help_link' => array(
  6114. 'variables' => array('url' => NULL),
  6115. ),
  6116. 'feed_icon' => array(
  6117. 'variables' => array('url' => NULL, 'title' => NULL),
  6118. ),
  6119. 'more_link' => array(
  6120. 'variables' => array('url' => NULL, 'title' => NULL)
  6121. ),
  6122. 'username' => array(
  6123. 'variables' => array('account' => NULL),
  6124. ),
  6125. 'progress_bar' => array(
  6126. 'variables' => array('percent' => NULL, 'message' => NULL),
  6127. ),
  6128. 'indentation' => array(
  6129. 'variables' => array('size' => 1),
  6130. ),
  6131. 'html_tag' => array(
  6132. 'render element' => 'element',
  6133. ),
  6134. // From theme.maintenance.inc.
  6135. 'maintenance_page' => array(
  6136. 'variables' => array('content' => NULL, 'show_messages' => TRUE),
  6137. 'template' => 'maintenance-page',
  6138. ),
  6139. 'update_page' => array(
  6140. 'variables' => array('content' => NULL, 'show_messages' => TRUE),
  6141. ),
  6142. 'install_page' => array(
  6143. 'variables' => array('content' => NULL),
  6144. ),
  6145. 'task_list' => array(
  6146. 'variables' => array('items' => NULL, 'active' => NULL),
  6147. ),
  6148. 'authorize_message' => array(
  6149. 'variables' => array('message' => NULL, 'success' => TRUE),
  6150. ),
  6151. 'authorize_report' => array(
  6152. 'variables' => array('messages' => array()),
  6153. ),
  6154. // From pager.inc.
  6155. 'pager' => array(
  6156. 'variables' => array('tags' => array(), 'element' => 0, 'parameters' => array(), 'quantity' => 9),
  6157. ),
  6158. 'pager_first' => array(
  6159. 'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
  6160. ),
  6161. 'pager_previous' => array(
  6162. 'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
  6163. ),
  6164. 'pager_next' => array(
  6165. 'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
  6166. ),
  6167. 'pager_last' => array(
  6168. 'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
  6169. ),
  6170. 'pager_link' => array(
  6171. 'variables' => array('text' => NULL, 'page_new' => NULL, 'element' => NULL, 'parameters' => array(), 'attributes' => array()),
  6172. ),
  6173. // From menu.inc.
  6174. 'menu_link' => array(
  6175. 'render element' => 'element',
  6176. ),
  6177. 'menu_tree' => array(
  6178. 'render element' => 'tree',
  6179. ),
  6180. 'menu_local_task' => array(
  6181. 'render element' => 'element',
  6182. ),
  6183. 'menu_local_action' => array(
  6184. 'render element' => 'element',
  6185. ),
  6186. 'menu_local_tasks' => array(
  6187. 'variables' => array('primary' => array(), 'secondary' => array()),
  6188. ),
  6189. // From form.inc.
  6190. 'select' => array(
  6191. 'render element' => 'element',
  6192. ),
  6193. 'fieldset' => array(
  6194. 'render element' => 'element',
  6195. ),
  6196. 'radio' => array(
  6197. 'render element' => 'element',
  6198. ),
  6199. 'radios' => array(
  6200. 'render element' => 'element',
  6201. ),
  6202. 'date' => array(
  6203. 'render element' => 'element',
  6204. ),
  6205. 'exposed_filters' => array(
  6206. 'render element' => 'form',
  6207. ),
  6208. 'checkbox' => array(
  6209. 'render element' => 'element',
  6210. ),
  6211. 'checkboxes' => array(
  6212. 'render element' => 'element',
  6213. ),
  6214. 'button' => array(
  6215. 'render element' => 'element',
  6216. ),
  6217. 'image_button' => array(
  6218. 'render element' => 'element',
  6219. ),
  6220. 'hidden' => array(
  6221. 'render element' => 'element',
  6222. ),
  6223. 'textfield' => array(
  6224. 'render element' => 'element',
  6225. ),
  6226. 'form' => array(
  6227. 'render element' => 'element',
  6228. ),
  6229. 'textarea' => array(
  6230. 'render element' => 'element',
  6231. ),
  6232. 'password' => array(
  6233. 'render element' => 'element',
  6234. ),
  6235. 'file' => array(
  6236. 'render element' => 'element',
  6237. ),
  6238. 'tableselect' => array(
  6239. 'render element' => 'element',
  6240. ),
  6241. 'form_element' => array(
  6242. 'render element' => 'element',
  6243. ),
  6244. 'form_required_marker' => array(
  6245. 'render element' => 'element',
  6246. ),
  6247. 'form_element_label' => array(
  6248. 'render element' => 'element',
  6249. ),
  6250. 'vertical_tabs' => array(
  6251. 'render element' => 'element',
  6252. ),
  6253. 'container' => array(
  6254. 'render element' => 'element',
  6255. ),
  6256. );
  6257. }
  6258. /**
  6259. * @ingroup schemaapi
  6260. * @{
  6261. */
  6262. /**
  6263. * Creates all tables defined in a module's hook_schema().
  6264. *
  6265. * Note: This function does not pass the module's schema through
  6266. * hook_schema_alter(). The module's tables will be created exactly as the
  6267. * module defines them.
  6268. *
  6269. * @param $module
  6270. * The module for which the tables will be created.
  6271. */
  6272. function drupal_install_schema($module) {
  6273. $schema = drupal_get_schema_unprocessed($module);
  6274. _drupal_schema_initialize($schema, $module, FALSE);
  6275. foreach ($schema as $name => $table) {
  6276. db_create_table($name, $table);
  6277. }
  6278. }
  6279. /**
  6280. * Removes all tables defined in a module's hook_schema().
  6281. *
  6282. * Note: This function does not pass the module's schema through
  6283. * hook_schema_alter(). The module's tables will be created exactly as the
  6284. * module defines them.
  6285. *
  6286. * @param $module
  6287. * The module for which the tables will be removed.
  6288. *
  6289. * @return
  6290. * An array of arrays with the following key/value pairs:
  6291. * - success: a boolean indicating whether the query succeeded.
  6292. * - query: the SQL query(s) executed, passed through check_plain().
  6293. */
  6294. function drupal_uninstall_schema($module) {
  6295. $schema = drupal_get_schema_unprocessed($module);
  6296. _drupal_schema_initialize($schema, $module, FALSE);
  6297. foreach ($schema as $table) {
  6298. if (db_table_exists($table['name'])) {
  6299. db_drop_table($table['name']);
  6300. }
  6301. }
  6302. }
  6303. /**
  6304. * Returns the unprocessed and unaltered version of a module's schema.
  6305. *
  6306. * Use this function only if you explicitly need the original
  6307. * specification of a schema, as it was defined in a module's
  6308. * hook_schema(). No additional default values will be set,
  6309. * hook_schema_alter() is not invoked and these unprocessed
  6310. * definitions won't be cached.
  6311. *
  6312. * This function can be used to retrieve a schema specification in
  6313. * hook_schema(), so it allows you to derive your tables from existing
  6314. * specifications.
  6315. *
  6316. * It is also used by drupal_install_schema() and
  6317. * drupal_uninstall_schema() to ensure that a module's tables are
  6318. * created exactly as specified without any changes introduced by a
  6319. * module that implements hook_schema_alter().
  6320. *
  6321. * @param $module
  6322. * The module to which the table belongs.
  6323. * @param $table
  6324. * The name of the table. If not given, the module's complete schema
  6325. * is returned.
  6326. */
  6327. function drupal_get_schema_unprocessed($module, $table = NULL) {
  6328. // Load the .install file to get hook_schema.
  6329. module_load_install($module);
  6330. $schema = module_invoke($module, 'schema');
  6331. if (isset($table) && isset($schema[$table])) {
  6332. return $schema[$table];
  6333. }
  6334. elseif (!empty($schema)) {
  6335. return $schema;
  6336. }
  6337. return array();
  6338. }
  6339. /**
  6340. * Fills in required default values for table definitions from hook_schema().
  6341. *
  6342. * @param $schema
  6343. * The schema definition array as it was returned by the module's
  6344. * hook_schema().
  6345. * @param $module
  6346. * The module for which hook_schema() was invoked.
  6347. * @param $remove_descriptions
  6348. * (optional) Whether to additionally remove 'description' keys of all tables
  6349. * and fields to improve performance of serialize() and unserialize().
  6350. * Defaults to TRUE.
  6351. */
  6352. function _drupal_schema_initialize(&$schema, $module, $remove_descriptions = TRUE) {
  6353. // Set the name and module key for all tables.
  6354. foreach ($schema as $name => &$table) {
  6355. if (empty($table['module'])) {
  6356. $table['module'] = $module;
  6357. }
  6358. if (!isset($table['name'])) {
  6359. $table['name'] = $name;
  6360. }
  6361. if ($remove_descriptions) {
  6362. unset($table['description']);
  6363. foreach ($table['fields'] as &$field) {
  6364. unset($field['description']);
  6365. }
  6366. }
  6367. }
  6368. }
  6369. /**
  6370. * Retrieves a list of fields from a table schema.
  6371. *
  6372. * The returned list is suitable for use in an SQL query.
  6373. *
  6374. * @param $table
  6375. * The name of the table from which to retrieve fields.
  6376. * @param
  6377. * An optional prefix to to all fields.
  6378. *
  6379. * @return An array of fields.
  6380. */
  6381. function drupal_schema_fields_sql($table, $prefix = NULL) {
  6382. $schema = drupal_get_schema($table);
  6383. $fields = array_keys($schema['fields']);
  6384. if ($prefix) {
  6385. $columns = array();
  6386. foreach ($fields as $field) {
  6387. $columns[] = "$prefix.$field";
  6388. }
  6389. return $columns;
  6390. }
  6391. else {
  6392. return $fields;
  6393. }
  6394. }
  6395. /**
  6396. * Saves (inserts or updates) a record to the database based upon the schema.
  6397. *
  6398. * @param $table
  6399. * The name of the table; this must be defined by a hook_schema()
  6400. * implementation.
  6401. * @param $record
  6402. * An object or array representing the record to write, passed in by
  6403. * reference. If inserting a new record, values not provided in $record will
  6404. * be populated in $record and in the database with the default values from
  6405. * the schema, as well as a single serial (auto-increment) field (if present).
  6406. * If updating an existing record, only provided values are updated in the
  6407. * database, and $record is not modified.
  6408. * @param $primary_keys
  6409. * To indicate that this is a new record to be inserted, omit this argument.
  6410. * If this is an update, this argument specifies the primary keys' field
  6411. * names. If there is only 1 field in the key, you may pass in a string; if
  6412. * there are multiple fields in the key, pass in an array.
  6413. *
  6414. * @return
  6415. * If the record insert or update failed, returns FALSE. If it succeeded,
  6416. * returns SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
  6417. */
  6418. function drupal_write_record($table, &$record, $primary_keys = array()) {
  6419. // Standardize $primary_keys to an array.
  6420. if (is_string($primary_keys)) {
  6421. $primary_keys = array($primary_keys);
  6422. }
  6423. $schema = drupal_get_schema($table);
  6424. if (empty($schema)) {
  6425. return FALSE;
  6426. }
  6427. $object = (object) $record;
  6428. $fields = array();
  6429. // Go through the schema to determine fields to write.
  6430. foreach ($schema['fields'] as $field => $info) {
  6431. if ($info['type'] == 'serial') {
  6432. // Skip serial types if we are updating.
  6433. if (!empty($primary_keys)) {
  6434. continue;
  6435. }
  6436. // Track serial field so we can helpfully populate them after the query.
  6437. // NOTE: Each table should come with one serial field only.
  6438. $serial = $field;
  6439. }
  6440. // Skip field if it is in $primary_keys as it is unnecessary to update a
  6441. // field to the value it is already set to.
  6442. if (in_array($field, $primary_keys)) {
  6443. continue;
  6444. }
  6445. if (!property_exists($object, $field)) {
  6446. // Skip fields that are not provided, default values are already known
  6447. // by the database.
  6448. continue;
  6449. }
  6450. // Build array of fields to update or insert.
  6451. if (empty($info['serialize'])) {
  6452. $fields[$field] = $object->$field;
  6453. }
  6454. else {
  6455. $fields[$field] = serialize($object->$field);
  6456. }
  6457. // Type cast to proper datatype, except when the value is NULL and the
  6458. // column allows this.
  6459. //
  6460. // MySQL PDO silently casts e.g. FALSE and '' to 0 when inserting the value
  6461. // into an integer column, but PostgreSQL PDO does not. Also type cast NULL
  6462. // when the column does not allow this.
  6463. if (isset($object->$field) || !empty($info['not null'])) {
  6464. if ($info['type'] == 'int' || $info['type'] == 'serial') {
  6465. $fields[$field] = (int) $fields[$field];
  6466. }
  6467. elseif ($info['type'] == 'float') {
  6468. $fields[$field] = (float) $fields[$field];
  6469. }
  6470. else {
  6471. $fields[$field] = (string) $fields[$field];
  6472. }
  6473. }
  6474. }
  6475. if (empty($fields)) {
  6476. return;
  6477. }
  6478. // Build the SQL.
  6479. if (empty($primary_keys)) {
  6480. // We are doing an insert.
  6481. $options = array('return' => Database::RETURN_INSERT_ID);
  6482. if (isset($serial) && isset($fields[$serial])) {
  6483. // If the serial column has been explicitly set with an ID, then we don't
  6484. // require the database to return the last insert id.
  6485. if ($fields[$serial]) {
  6486. $options['return'] = Database::RETURN_AFFECTED;
  6487. }
  6488. // If a serial column does exist with no value (i.e. 0) then remove it as
  6489. // the database will insert the correct value for us.
  6490. else {
  6491. unset($fields[$serial]);
  6492. }
  6493. }
  6494. $query = db_insert($table, $options)->fields($fields);
  6495. $return = SAVED_NEW;
  6496. }
  6497. else {
  6498. $query = db_update($table)->fields($fields);
  6499. foreach ($primary_keys as $key) {
  6500. $query->condition($key, $object->$key);
  6501. }
  6502. $return = SAVED_UPDATED;
  6503. }
  6504. // Execute the SQL.
  6505. if ($query_return = $query->execute()) {
  6506. if (isset($serial)) {
  6507. // If the database was not told to return the last insert id, it will be
  6508. // because we already know it.
  6509. if (isset($options) && $options['return'] != Database::RETURN_INSERT_ID) {
  6510. $object->$serial = $fields[$serial];
  6511. }
  6512. else {
  6513. $object->$serial = $query_return;
  6514. }
  6515. }
  6516. }
  6517. // If we have a single-field primary key but got no insert ID, the
  6518. // query failed. Note that we explicitly check for FALSE, because
  6519. // a valid update query which doesn't change any values will return
  6520. // zero (0) affected rows.
  6521. elseif ($query_return === FALSE && count($primary_keys) == 1) {
  6522. $return = FALSE;
  6523. }
  6524. // If we are inserting, populate empty fields with default values.
  6525. if (empty($primary_keys)) {
  6526. foreach ($schema['fields'] as $field => $info) {
  6527. if (isset($info['default']) && !property_exists($object, $field)) {
  6528. $object->$field = $info['default'];
  6529. }
  6530. }
  6531. }
  6532. // If we began with an array, convert back.
  6533. if (is_array($record)) {
  6534. $record = (array) $object;
  6535. }
  6536. return $return;
  6537. }
  6538. /**
  6539. * @} End of "ingroup schemaapi".
  6540. */
  6541. /**
  6542. * Parses Drupal module and theme .info files.
  6543. *
  6544. * Info files are NOT for placing arbitrary theme and module-specific settings.
  6545. * Use variable_get() and variable_set() for that.
  6546. *
  6547. * Information stored in a module .info file:
  6548. * - name: The real name of the module for display purposes.
  6549. * - description: A brief description of the module.
  6550. * - dependencies: An array of shortnames of other modules this module requires.
  6551. * - package: The name of the package of modules this module belongs to.
  6552. *
  6553. * See forum.info for an example of a module .info file.
  6554. *
  6555. * Information stored in a theme .info file:
  6556. * - name: The real name of the theme for display purposes.
  6557. * - description: Brief description.
  6558. * - screenshot: Path to screenshot relative to the theme's .info file.
  6559. * - engine: Theme engine; typically phptemplate.
  6560. * - base: Name of a base theme, if applicable; e.g., base = zen.
  6561. * - regions: Listed regions; e.g., region[left] = Left sidebar.
  6562. * - features: Features available; e.g., features[] = logo.
  6563. * - stylesheets: Theme stylesheets; e.g., stylesheets[all][] = my-style.css.
  6564. * - scripts: Theme scripts; e.g., scripts[] = my-script.js.
  6565. *
  6566. * See bartik.info for an example of a theme .info file.
  6567. *
  6568. * @param $filename
  6569. * The file we are parsing. Accepts file with relative or absolute path.
  6570. *
  6571. * @return
  6572. * The info array.
  6573. *
  6574. * @see drupal_parse_info_format()
  6575. */
  6576. function drupal_parse_info_file($filename) {
  6577. $info = &drupal_static(__FUNCTION__, array());
  6578. if (!isset($info[$filename])) {
  6579. if (!file_exists($filename)) {
  6580. $info[$filename] = array();
  6581. }
  6582. else {
  6583. $data = file_get_contents($filename);
  6584. $info[$filename] = drupal_parse_info_format($data);
  6585. }
  6586. }
  6587. return $info[$filename];
  6588. }
  6589. /**
  6590. * Parses data in Drupal's .info format.
  6591. *
  6592. * Data should be in an .ini-like format to specify values. White-space
  6593. * generally doesn't matter, except inside values:
  6594. * @code
  6595. * key = value
  6596. * key = "value"
  6597. * key = 'value'
  6598. * key = "multi-line
  6599. * value"
  6600. * key = 'multi-line
  6601. * value'
  6602. * key
  6603. * =
  6604. * 'value'
  6605. * @endcode
  6606. *
  6607. * Arrays are created using a HTTP GET alike syntax:
  6608. * @code
  6609. * key[] = "numeric array"
  6610. * key[index] = "associative array"
  6611. * key[index][] = "nested numeric array"
  6612. * key[index][index] = "nested associative array"
  6613. * @endcode
  6614. *
  6615. * PHP constants are substituted in, but only when used as the entire value.
  6616. * Comments should start with a semi-colon at the beginning of a line.
  6617. *
  6618. * @param $data
  6619. * A string to parse.
  6620. *
  6621. * @return
  6622. * The info array.
  6623. *
  6624. * @see drupal_parse_info_file()
  6625. */
  6626. function drupal_parse_info_format($data) {
  6627. $info = array();
  6628. $constants = get_defined_constants();
  6629. if (preg_match_all('
  6630. @^\s* # Start at the beginning of a line, ignoring leading whitespace
  6631. ((?:
  6632. [^=;\[\]]| # Key names cannot contain equal signs, semi-colons or square brackets,
  6633. \[[^\[\]]*\] # unless they are balanced and not nested
  6634. )+?)
  6635. \s*=\s* # Key/value pairs are separated by equal signs (ignoring white-space)
  6636. (?:
  6637. ("(?:[^"]|(?<=\\\\)")*")| # Double-quoted string, which may contain slash-escaped quotes/slashes
  6638. (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
  6639. ([^\r\n]*?) # Non-quoted string
  6640. )\s*$ # Stop at the next end of a line, ignoring trailing whitespace
  6641. @msx', $data, $matches, PREG_SET_ORDER)) {
  6642. foreach ($matches as $match) {
  6643. // Fetch the key and value string.
  6644. $i = 0;
  6645. foreach (array('key', 'value1', 'value2', 'value3') as $var) {
  6646. $$var = isset($match[++$i]) ? $match[$i] : '';
  6647. }
  6648. $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
  6649. // Parse array syntax.
  6650. $keys = preg_split('/\]?\[/', rtrim($key, ']'));
  6651. $last = array_pop($keys);
  6652. $parent = &$info;
  6653. // Create nested arrays.
  6654. foreach ($keys as $key) {
  6655. if ($key == '') {
  6656. $key = count($parent);
  6657. }
  6658. if (!isset($parent[$key]) || !is_array($parent[$key])) {
  6659. $parent[$key] = array();
  6660. }
  6661. $parent = &$parent[$key];
  6662. }
  6663. // Handle PHP constants.
  6664. if (isset($constants[$value])) {
  6665. $value = $constants[$value];
  6666. }
  6667. // Insert actual value.
  6668. if ($last == '') {
  6669. $last = count($parent);
  6670. }
  6671. $parent[$last] = $value;
  6672. }
  6673. }
  6674. return $info;
  6675. }
  6676. /**
  6677. * Returns a list of severity levels, as defined in RFC 3164.
  6678. *
  6679. * @return
  6680. * Array of the possible severity levels for log messages.
  6681. *
  6682. * @see http://www.ietf.org/rfc/rfc3164.txt
  6683. * @see watchdog()
  6684. * @ingroup logging_severity_levels
  6685. */
  6686. function watchdog_severity_levels() {
  6687. return array(
  6688. WATCHDOG_EMERGENCY => t('emergency'),
  6689. WATCHDOG_ALERT => t('alert'),
  6690. WATCHDOG_CRITICAL => t('critical'),
  6691. WATCHDOG_ERROR => t('error'),
  6692. WATCHDOG_WARNING => t('warning'),
  6693. WATCHDOG_NOTICE => t('notice'),
  6694. WATCHDOG_INFO => t('info'),
  6695. WATCHDOG_DEBUG => t('debug'),
  6696. );
  6697. }
  6698. /**
  6699. * Explodes a string of tags into an array.
  6700. *
  6701. * @see drupal_implode_tags()
  6702. */
  6703. function drupal_explode_tags($tags) {
  6704. // This regexp allows the following types of user input:
  6705. // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
  6706. $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
  6707. preg_match_all($regexp, $tags, $matches);
  6708. $typed_tags = array_unique($matches[1]);
  6709. $tags = array();
  6710. foreach ($typed_tags as $tag) {
  6711. // If a user has escaped a term (to demonstrate that it is a group,
  6712. // or includes a comma or quote character), we remove the escape
  6713. // formatting so to save the term into the database as the user intends.
  6714. $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
  6715. if ($tag != "") {
  6716. $tags[] = $tag;
  6717. }
  6718. }
  6719. return $tags;
  6720. }
  6721. /**
  6722. * Implodes an array of tags into a string.
  6723. *
  6724. * @see drupal_explode_tags()
  6725. */
  6726. function drupal_implode_tags($tags) {
  6727. $encoded_tags = array();
  6728. foreach ($tags as $tag) {
  6729. // Commas and quotes in tag names are special cases, so encode them.
  6730. if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
  6731. $tag = '"' . str_replace('"', '""', $tag) . '"';
  6732. }
  6733. $encoded_tags[] = $tag;
  6734. }
  6735. return implode(', ', $encoded_tags);
  6736. }
  6737. /**
  6738. * Flushes all cached data on the site.
  6739. *
  6740. * Empties cache tables, rebuilds the menu cache and theme registries, and
  6741. * invokes a hook so that other modules' cache data can be cleared as well.
  6742. */
  6743. function drupal_flush_all_caches() {
  6744. // Change query-strings on css/js files to enforce reload for all users.
  6745. _drupal_flush_css_js();
  6746. registry_rebuild();
  6747. drupal_clear_css_cache();
  6748. drupal_clear_js_cache();
  6749. // Rebuild the theme data. Note that the module data is rebuilt above, as
  6750. // part of registry_rebuild().
  6751. system_rebuild_theme_data();
  6752. drupal_theme_rebuild();
  6753. entity_info_cache_clear();
  6754. node_types_rebuild();
  6755. // node_menu() defines menu items based on node types so it needs to come
  6756. // after node types are rebuilt.
  6757. menu_rebuild();
  6758. // Synchronize to catch any actions that were added or removed.
  6759. actions_synchronize();
  6760. // Don't clear cache_form - in-progress form submissions may break.
  6761. // Ordered so clearing the page cache will always be the last action.
  6762. $core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
  6763. $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
  6764. foreach ($cache_tables as $table) {
  6765. cache_clear_all('*', $table, TRUE);
  6766. }
  6767. // Rebuild the bootstrap module list. We do this here so that developers
  6768. // can get new hook_boot() implementations registered without having to
  6769. // write a hook_update_N() function.
  6770. _system_update_bootstrap_status();
  6771. }
  6772. /**
  6773. * Changes the dummy query string added to all CSS and JavaScript files.
  6774. *
  6775. * Changing the dummy query string appended to CSS and JavaScript files forces
  6776. * all browsers to reload fresh files.
  6777. */
  6778. function _drupal_flush_css_js() {
  6779. // The timestamp is converted to base 36 in order to make it more compact.
  6780. variable_set('css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
  6781. }
  6782. /**
  6783. * Outputs debug information.
  6784. *
  6785. * The debug information is passed on to trigger_error() after being converted
  6786. * to a string using _drupal_debug_message().
  6787. *
  6788. * @param $data
  6789. * Data to be output.
  6790. * @param $label
  6791. * Label to prefix the data.
  6792. * @param $print_r
  6793. * Flag to switch between print_r() and var_export() for data conversion to
  6794. * string. Set $print_r to TRUE when dealing with a recursive data structure
  6795. * as var_export() will generate an error.
  6796. */
  6797. function debug($data, $label = NULL, $print_r = FALSE) {
  6798. // Print $data contents to string.
  6799. $string = check_plain($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
  6800. // Display values with pre-formatting to increase readability.
  6801. $string = '<pre>' . $string . '</pre>';
  6802. trigger_error(trim($label ? "$label: $string" : $string));
  6803. }
  6804. /**
  6805. * Parses a dependency for comparison by drupal_check_incompatibility().
  6806. *
  6807. * @param $dependency
  6808. * A dependency string, for example 'foo (>=7.x-4.5-beta5, 3.x)'.
  6809. *
  6810. * @return
  6811. * An associative array with three keys:
  6812. * - 'name' includes the name of the thing to depend on (e.g. 'foo').
  6813. * - 'original_version' contains the original version string (which can be
  6814. * used in the UI for reporting incompatibilities).
  6815. * - 'versions' is a list of associative arrays, each containing the keys
  6816. * 'op' and 'version'. 'op' can be one of: '=', '==', '!=', '<>', '<',
  6817. * '<=', '>', or '>='. 'version' is one piece like '4.5-beta3'.
  6818. * Callers should pass this structure to drupal_check_incompatibility().
  6819. *
  6820. * @see drupal_check_incompatibility()
  6821. */
  6822. function drupal_parse_dependency($dependency) {
  6823. // We use named subpatterns and support every op that version_compare
  6824. // supports. Also, op is optional and defaults to equals.
  6825. $p_op = '(?P<operation>!=|==|=|<|<=|>|>=|<>)?';
  6826. // Core version is always optional: 7.x-2.x and 2.x is treated the same.
  6827. $p_core = '(?:' . preg_quote(DRUPAL_CORE_COMPATIBILITY) . '-)?';
  6828. $p_major = '(?P<major>\d+)';
  6829. // By setting the minor version to x, branches can be matched.
  6830. $p_minor = '(?P<minor>(?:\d+|x)(?:-[A-Za-z]+\d+)?)';
  6831. $value = array();
  6832. $parts = explode('(', $dependency, 2);
  6833. $value['name'] = trim($parts[0]);
  6834. if (isset($parts[1])) {
  6835. $value['original_version'] = ' (' . $parts[1];
  6836. foreach (explode(',', $parts[1]) as $version) {
  6837. if (preg_match("/^\s*$p_op\s*$p_core$p_major\.$p_minor/", $version, $matches)) {
  6838. $op = !empty($matches['operation']) ? $matches['operation'] : '=';
  6839. if ($matches['minor'] == 'x') {
  6840. // Drupal considers "2.x" to mean any version that begins with
  6841. // "2" (e.g. 2.0, 2.9 are all "2.x"). PHP's version_compare(),
  6842. // on the other hand, treats "x" as a string; so to
  6843. // version_compare(), "2.x" is considered less than 2.0. This
  6844. // means that >=2.x and <2.x are handled by version_compare()
  6845. // as we need, but > and <= are not.
  6846. if ($op == '>' || $op == '<=') {
  6847. $matches['major']++;
  6848. }
  6849. // Equivalence can be checked by adding two restrictions.
  6850. if ($op == '=' || $op == '==') {
  6851. $value['versions'][] = array('op' => '<', 'version' => ($matches['major'] + 1) . '.x');
  6852. $op = '>=';
  6853. }
  6854. }
  6855. $value['versions'][] = array('op' => $op, 'version' => $matches['major'] . '.' . $matches['minor']);
  6856. }
  6857. }
  6858. }
  6859. return $value;
  6860. }
  6861. /**
  6862. * Checks whether a version is compatible with a given dependency.
  6863. *
  6864. * @param $v
  6865. * The parsed dependency structure from drupal_parse_dependency().
  6866. * @param $current_version
  6867. * The version to check against (like 4.2).
  6868. *
  6869. * @return
  6870. * NULL if compatible, otherwise the original dependency version string that
  6871. * caused the incompatibility.
  6872. *
  6873. * @see drupal_parse_dependency()
  6874. */
  6875. function drupal_check_incompatibility($v, $current_version) {
  6876. if (!empty($v['versions'])) {
  6877. foreach ($v['versions'] as $required_version) {
  6878. if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
  6879. return $v['original_version'];
  6880. }
  6881. }
  6882. }
  6883. }
  6884. /**
  6885. * Get the entity info array of an entity type.
  6886. *
  6887. * @see hook_entity_info()
  6888. * @see hook_entity_info_alter()
  6889. *
  6890. * @param $entity_type
  6891. * The entity type, e.g. node, for which the info shall be returned, or NULL
  6892. * to return an array with info about all types.
  6893. */
  6894. function entity_get_info($entity_type = NULL) {
  6895. global $language;
  6896. // Use the advanced drupal_static() pattern, since this is called very often.
  6897. static $drupal_static_fast;
  6898. if (!isset($drupal_static_fast)) {
  6899. $drupal_static_fast['entity_info'] = &drupal_static(__FUNCTION__);
  6900. }
  6901. $entity_info = &$drupal_static_fast['entity_info'];
  6902. // hook_entity_info() includes translated strings, so each language is cached
  6903. // separately.
  6904. $langcode = $language->language;
  6905. if (empty($entity_info)) {
  6906. if ($cache = cache_get("entity_info:$langcode")) {
  6907. $entity_info = $cache->data;
  6908. }
  6909. else {
  6910. $entity_info = module_invoke_all('entity_info');
  6911. // Merge in default values.
  6912. foreach ($entity_info as $name => $data) {
  6913. $entity_info[$name] += array(
  6914. 'fieldable' => FALSE,
  6915. 'controller class' => 'DrupalDefaultEntityController',
  6916. 'static cache' => TRUE,
  6917. 'field cache' => TRUE,
  6918. 'load hook' => $name . '_load',
  6919. 'bundles' => array(),
  6920. 'view modes' => array(),
  6921. 'entity keys' => array(),
  6922. 'translation' => array(),
  6923. );
  6924. $entity_info[$name]['entity keys'] += array(
  6925. 'revision' => '',
  6926. 'bundle' => '',
  6927. );
  6928. foreach ($entity_info[$name]['view modes'] as $view_mode => $view_mode_info) {
  6929. $entity_info[$name]['view modes'][$view_mode] += array(
  6930. 'custom settings' => FALSE,
  6931. );
  6932. }
  6933. // If no bundle key is provided, assume a single bundle, named after
  6934. // the entity type.
  6935. if (empty($entity_info[$name]['entity keys']['bundle']) && empty($entity_info[$name]['bundles'])) {
  6936. $entity_info[$name]['bundles'] = array($name => array('label' => $entity_info[$name]['label']));
  6937. }
  6938. // Prepare entity schema fields SQL info for
  6939. // DrupalEntityControllerInterface::buildQuery().
  6940. if (isset($entity_info[$name]['base table'])) {
  6941. $entity_info[$name]['schema_fields_sql']['base table'] = drupal_schema_fields_sql($entity_info[$name]['base table']);
  6942. if (isset($entity_info[$name]['revision table'])) {
  6943. $entity_info[$name]['schema_fields_sql']['revision table'] = drupal_schema_fields_sql($entity_info[$name]['revision table']);
  6944. }
  6945. }
  6946. }
  6947. // Let other modules alter the entity info.
  6948. drupal_alter('entity_info', $entity_info);
  6949. cache_set("entity_info:$langcode", $entity_info);
  6950. }
  6951. }
  6952. if (empty($entity_type)) {
  6953. return $entity_info;
  6954. }
  6955. elseif (isset($entity_info[$entity_type])) {
  6956. return $entity_info[$entity_type];
  6957. }
  6958. }
  6959. /**
  6960. * Resets the cached information about entity types.
  6961. */
  6962. function entity_info_cache_clear() {
  6963. drupal_static_reset('entity_get_info');
  6964. // Clear all languages.
  6965. cache_clear_all('entity_info:', 'cache', TRUE);
  6966. }
  6967. /**
  6968. * Helper function to extract id, vid, and bundle name from an entity.
  6969. *
  6970. * @param $entity_type
  6971. * The entity type; e.g. 'node' or 'user'.
  6972. * @param $entity
  6973. * The entity from which to extract values.
  6974. * @return
  6975. * A numerically indexed array (not a hash table) containing these
  6976. * elements:
  6977. * 0: primary id of the entity
  6978. * 1: revision id of the entity, or NULL if $entity_type is not versioned
  6979. * 2: bundle name of the entity
  6980. */
  6981. function entity_extract_ids($entity_type, $entity) {
  6982. $info = entity_get_info($entity_type);
  6983. // Objects being created might not have id/vid yet.
  6984. $id = isset($entity->{$info['entity keys']['id']}) ? $entity->{$info['entity keys']['id']} : NULL;
  6985. $vid = ($info['entity keys']['revision'] && isset($entity->{$info['entity keys']['revision']})) ? $entity->{$info['entity keys']['revision']} : NULL;
  6986. if (!empty($info['entity keys']['bundle'])) {
  6987. // Explicitly fail for malformed entities missing the bundle property.
  6988. if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
  6989. throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
  6990. }
  6991. $bundle = $entity->{$info['entity keys']['bundle']};
  6992. }
  6993. else {
  6994. // The entity type provides no bundle key: assume a single bundle, named
  6995. // after the entity type.
  6996. $bundle = $entity_type;
  6997. }
  6998. return array($id, $vid, $bundle);
  6999. }
  7000. /**
  7001. * Helper function to assemble an object structure with initial ids.
  7002. *
  7003. * This function can be seen as reciprocal to entity_extract_ids().
  7004. *
  7005. * @param $entity_type
  7006. * The entity type; e.g. 'node' or 'user'.
  7007. * @param $ids
  7008. * A numerically indexed array, as returned by entity_extract_ids(),
  7009. * containing these elements:
  7010. * 0: primary id of the entity
  7011. * 1: revision id of the entity, or NULL if $entity_type is not versioned
  7012. * 2: bundle name of the entity, or NULL if $entity_type has no bundles
  7013. * @return
  7014. * An entity structure, initialized with the ids provided.
  7015. */
  7016. function entity_create_stub_entity($entity_type, $ids) {
  7017. $entity = new stdClass();
  7018. $info = entity_get_info($entity_type);
  7019. $entity->{$info['entity keys']['id']} = $ids[0];
  7020. if (!empty($info['entity keys']['revision']) && isset($ids[1])) {
  7021. $entity->{$info['entity keys']['revision']} = $ids[1];
  7022. }
  7023. if (!empty($info['entity keys']['bundle']) && isset($ids[2])) {
  7024. $entity->{$info['entity keys']['bundle']} = $ids[2];
  7025. }
  7026. return $entity;
  7027. }
  7028. /**
  7029. * Load entities from the database.
  7030. *
  7031. * The entities are stored in a static memory cache, and will not require
  7032. * database access if loaded again during the same page request.
  7033. *
  7034. * The actual loading is done through a class that has to implement the
  7035. * DrupalEntityControllerInterface interface. By default,
  7036. * DrupalDefaultEntityController is used. Entity types can specify that a
  7037. * different class should be used by setting the 'controller class' key in
  7038. * hook_entity_info(). These classes can either implement the
  7039. * DrupalEntityControllerInterface interface, or, most commonly, extend the
  7040. * DrupalDefaultEntityController class. See node_entity_info() and the
  7041. * NodeController in node.module as an example.
  7042. *
  7043. * @see hook_entity_info()
  7044. * @see DrupalEntityControllerInterface
  7045. * @see DrupalDefaultEntityController
  7046. * @see EntityFieldQuery
  7047. *
  7048. * @param $entity_type
  7049. * The entity type to load, e.g. node or user.
  7050. * @param $ids
  7051. * An array of entity IDs, or FALSE to load all entities.
  7052. * @param $conditions
  7053. * (deprecated) An associative array of conditions on the base table, where
  7054. * the keys are the database fields and the values are the values those
  7055. * fields must have. Instead, it is preferable to use EntityFieldQuery to
  7056. * retrieve a list of entity IDs loadable by this function.
  7057. * @param $reset
  7058. * Whether to reset the internal cache for the requested entity type.
  7059. *
  7060. * @return
  7061. * An array of entity objects indexed by their ids. When no results are
  7062. * found, an empty array is returned.
  7063. *
  7064. * @todo Remove $conditions in Drupal 8.
  7065. */
  7066. function entity_load($entity_type, $ids = FALSE, $conditions = array(), $reset = FALSE) {
  7067. if ($reset) {
  7068. entity_get_controller($entity_type)->resetCache();
  7069. }
  7070. return entity_get_controller($entity_type)->load($ids, $conditions);
  7071. }
  7072. /**
  7073. * Loads the unchanged, i.e. not modified, entity from the database.
  7074. *
  7075. * Unlike entity_load() this function ensures the entity is directly loaded from
  7076. * the database, thus bypassing any static cache. In particular, this function
  7077. * is useful to determine changes by comparing the entity being saved to the
  7078. * stored entity.
  7079. *
  7080. * @param $entity_type
  7081. * The entity type to load, e.g. node or user.
  7082. * @param $id
  7083. * The id of the entity to load.
  7084. *
  7085. * @return
  7086. * The unchanged entity, or FALSE if the entity cannot be loaded.
  7087. */
  7088. function entity_load_unchanged($entity_type, $id) {
  7089. entity_get_controller($entity_type)->resetCache(array($id));
  7090. $result = entity_get_controller($entity_type)->load(array($id));
  7091. return reset($result);
  7092. }
  7093. /**
  7094. * Get the entity controller class for an entity type.
  7095. */
  7096. function entity_get_controller($entity_type) {
  7097. $controllers = &drupal_static(__FUNCTION__, array());
  7098. if (!isset($controllers[$entity_type])) {
  7099. $type_info = entity_get_info($entity_type);
  7100. $class = $type_info['controller class'];
  7101. $controllers[$entity_type] = new $class($entity_type);
  7102. }
  7103. return $controllers[$entity_type];
  7104. }
  7105. /**
  7106. * Invoke hook_entity_prepare_view().
  7107. *
  7108. * If adding a new entity similar to nodes, comments or users, you should
  7109. * invoke this function during the ENTITY_build_content() or
  7110. * ENTITY_view_multiple() phases of rendering to allow other modules to alter
  7111. * the objects during this phase. This is needed for situations where
  7112. * information needs to be loaded outside of ENTITY_load() - particularly
  7113. * when loading entities into one another - i.e. a user object into a node, due
  7114. * to the potential for unwanted side-effects such as caching and infinite
  7115. * recursion. By convention, entity_prepare_view() is called after
  7116. * field_attach_prepare_view() to allow entity level hooks to act on content
  7117. * loaded by field API.
  7118. * @see hook_entity_prepare_view()
  7119. *
  7120. * @param $entity_type
  7121. * The type of entity, i.e. 'node', 'user'.
  7122. * @param $entities
  7123. * The entity objects which are being prepared for view, keyed by object ID.
  7124. * @param $langcode
  7125. * (optional) A language code to be used for rendering. Defaults to the global
  7126. * content language of the current request.
  7127. */
  7128. function entity_prepare_view($entity_type, $entities, $langcode = NULL) {
  7129. if (!isset($langcode)) {
  7130. $langcode = $GLOBALS['language_content']->language;
  7131. }
  7132. // To ensure hooks are only run once per entity, check for an
  7133. // entity_view_prepared flag and only process items without it.
  7134. // @todo: resolve this more generally for both entity and field level hooks.
  7135. $prepare = array();
  7136. foreach ($entities as $id => $entity) {
  7137. if (empty($entity->entity_view_prepared)) {
  7138. // Add this entity to the items to be prepared.
  7139. $prepare[$id] = $entity;
  7140. // Mark this item as prepared.
  7141. $entity->entity_view_prepared = TRUE;
  7142. }
  7143. }
  7144. if (!empty($prepare)) {
  7145. module_invoke_all('entity_prepare_view', $prepare, $entity_type, $langcode);
  7146. }
  7147. }
  7148. /**
  7149. * Returns the uri elements of an entity.
  7150. *
  7151. * @param $entity_type
  7152. * The entity type; e.g. 'node' or 'user'.
  7153. * @param $entity
  7154. * The entity for which to generate a path.
  7155. * @return
  7156. * An array containing the 'path' and 'options' keys used to build the uri of
  7157. * the entity, and matching the signature of url(). NULL if the entity has no
  7158. * uri of its own.
  7159. */
  7160. function entity_uri($entity_type, $entity) {
  7161. $info = entity_get_info($entity_type);
  7162. list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  7163. // A bundle-specific callback takes precedence over the generic one for the
  7164. // entity type.
  7165. if (isset($info['bundles'][$bundle]['uri callback'])) {
  7166. $uri_callback = $info['bundles'][$bundle]['uri callback'];
  7167. }
  7168. elseif (isset($info['uri callback'])) {
  7169. $uri_callback = $info['uri callback'];
  7170. }
  7171. else {
  7172. return NULL;
  7173. }
  7174. // Invoke the callback to get the URI. If there is no callback, return NULL.
  7175. if (isset($uri_callback) && function_exists($uri_callback)) {
  7176. $uri = $uri_callback($entity);
  7177. // Pass the entity data to url() so that alter functions do not need to
  7178. // lookup this entity again.
  7179. $uri['options']['entity_type'] = $entity_type;
  7180. $uri['options']['entity'] = $entity;
  7181. return $uri;
  7182. }
  7183. }
  7184. /**
  7185. * Returns the label of an entity.
  7186. *
  7187. * See the 'label callback' component of the hook_entity_info() return value
  7188. * for more information.
  7189. *
  7190. * @param $entity_type
  7191. * The entity type; e.g., 'node' or 'user'.
  7192. * @param $entity
  7193. * The entity for which to generate the label.
  7194. *
  7195. * @return
  7196. * The entity label, or FALSE if not found.
  7197. */
  7198. function entity_label($entity_type, $entity) {
  7199. $label = FALSE;
  7200. $info = entity_get_info($entity_type);
  7201. if (isset($info['label callback']) && function_exists($info['label callback'])) {
  7202. $label = $info['label callback']($entity, $entity_type);
  7203. }
  7204. elseif (!empty($info['entity keys']['label']) && isset($entity->{$info['entity keys']['label']})) {
  7205. $label = $entity->{$info['entity keys']['label']};
  7206. }
  7207. return $label;
  7208. }
  7209. /**
  7210. * Helper function for attaching field API validation to entity forms.
  7211. */
  7212. function entity_form_field_validate($entity_type, $form, &$form_state) {
  7213. // All field attach API functions act on an entity object, but during form
  7214. // validation, we don't have one. $form_state contains the entity as it was
  7215. // prior to processing the current form submission, and we must not update it
  7216. // until we have fully validated the submitted input. Therefore, for
  7217. // validation, act on a pseudo entity created out of the form values.
  7218. $pseudo_entity = (object) $form_state['values'];
  7219. field_attach_form_validate($entity_type, $pseudo_entity, $form, $form_state);
  7220. }
  7221. /**
  7222. * Helper function for copying submitted values to entity properties for simple entity forms.
  7223. *
  7224. * During the submission handling of an entity form's "Save", "Preview", and
  7225. * possibly other buttons, the form state's entity needs to be updated with the
  7226. * submitted form values. Each entity form implements its own builder function
  7227. * for doing this, appropriate for the particular entity and form, whereas
  7228. * modules may specify additional builder functions in $form['#entity_builders']
  7229. * for copying the form values of added form elements to entity properties.
  7230. * Many of the main entity builder functions can call this helper function to
  7231. * re-use its logic of copying $form_state['values'][PROPERTY] values to
  7232. * $entity->PROPERTY for all entries in $form_state['values'] that are not field
  7233. * data, and calling field_attach_submit() to copy field data. Apart from that
  7234. * this helper invokes any additional builder functions that have been specified
  7235. * in $form['#entity_builders'].
  7236. *
  7237. * For some entity forms (e.g., forms with complex non-field data and forms that
  7238. * simultaneously edit multiple entities), this behavior may be inappropriate,
  7239. * so the builder function for such forms needs to implement the required
  7240. * functionality instead of calling this function.
  7241. */
  7242. function entity_form_submit_build_entity($entity_type, $entity, $form, &$form_state) {
  7243. $info = entity_get_info($entity_type);
  7244. list(, , $bundle) = entity_extract_ids($entity_type, $entity);
  7245. // Copy top-level form values that are not for fields to entity properties,
  7246. // without changing existing entity properties that are not being edited by
  7247. // this form. Copying field values must be done using field_attach_submit().
  7248. $values_excluding_fields = $info['fieldable'] ? array_diff_key($form_state['values'], field_info_instances($entity_type, $bundle)) : $form_state['values'];
  7249. foreach ($values_excluding_fields as $key => $value) {
  7250. $entity->$key = $value;
  7251. }
  7252. // Invoke all specified builders for copying form values to entity properties.
  7253. if (isset($form['#entity_builders'])) {
  7254. foreach ($form['#entity_builders'] as $function) {
  7255. $function($entity_type, $entity, $form, $form_state);
  7256. }
  7257. }
  7258. // Copy field values to the entity.
  7259. if ($info['fieldable']) {
  7260. field_attach_submit($entity_type, $entity, $form, $form_state);
  7261. }
  7262. }
  7263. /**
  7264. * Performs one or more XML-RPC request(s).
  7265. *
  7266. * Usage example:
  7267. * @code
  7268. * $result = xmlrpc('http://example.com/xmlrpc.php', array(
  7269. * 'service.methodName' => array($parameter, $second, $third),
  7270. * ));
  7271. * @endcode
  7272. *
  7273. * @param $url
  7274. * An absolute URL of the XML-RPC endpoint.
  7275. * @param $args
  7276. * An associative array whose keys are the methods to call and whose values
  7277. * are the arguments to pass to the respective method. If multiple methods
  7278. * are specified, a system.multicall is performed.
  7279. * @param $options
  7280. * (optional) An array of options to pass along to drupal_http_request().
  7281. *
  7282. * @return
  7283. * For one request:
  7284. * Either the return value of the method on success, or FALSE.
  7285. * If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
  7286. * For multiple requests:
  7287. * An array of results. Each result will either be the result
  7288. * returned by the method called, or an xmlrpc_error object if the call
  7289. * failed. See xmlrpc_error().
  7290. */
  7291. function xmlrpc($url, $args, $options = array()) {
  7292. require_once DRUPAL_ROOT . '/includes/xmlrpc.inc';
  7293. return _xmlrpc($url, $args, $options);
  7294. }
  7295. /**
  7296. * Retrieves a list of all available archivers.
  7297. *
  7298. * @see hook_archiver_info()
  7299. * @see hook_archiver_info_alter()
  7300. */
  7301. function archiver_get_info() {
  7302. $archiver_info = &drupal_static(__FUNCTION__, array());
  7303. if (empty($archiver_info)) {
  7304. $cache = cache_get('archiver_info');
  7305. if ($cache === FALSE) {
  7306. // Rebuild the cache and save it.
  7307. $archiver_info = module_invoke_all('archiver_info');
  7308. drupal_alter('archiver_info', $archiver_info);
  7309. uasort($archiver_info, 'drupal_sort_weight');
  7310. cache_set('archiver_info', $archiver_info);
  7311. }
  7312. else {
  7313. $archiver_info = $cache->data;
  7314. }
  7315. }
  7316. return $archiver_info;
  7317. }
  7318. /**
  7319. * Returns a string of supported archive extensions.
  7320. *
  7321. * @return
  7322. * A space-separated string of extensions suitable for use by the file
  7323. * validation system.
  7324. */
  7325. function archiver_get_extensions() {
  7326. $valid_extensions = array();
  7327. foreach (archiver_get_info() as $archive) {
  7328. foreach ($archive['extensions'] as $extension) {
  7329. foreach (explode('.', $extension) as $part) {
  7330. if (!in_array($part, $valid_extensions)) {
  7331. $valid_extensions[] = $part;
  7332. }
  7333. }
  7334. }
  7335. }
  7336. return implode(' ', $valid_extensions);
  7337. }
  7338. /**
  7339. * Creates the appropriate archiver for the specified file.
  7340. *
  7341. * @param $file
  7342. * The full path of the archive file. Note that stream wrapper paths are
  7343. * supported, but not remote ones.
  7344. *
  7345. * @return
  7346. * A newly created instance of the archiver class appropriate
  7347. * for the specified file, already bound to that file.
  7348. * If no appropriate archiver class was found, will return FALSE.
  7349. */
  7350. function archiver_get_archiver($file) {
  7351. // Archivers can only work on local paths
  7352. $filepath = drupal_realpath($file);
  7353. if (!is_file($filepath)) {
  7354. throw new Exception(t('Archivers can only operate on local files: %file not supported', array('%file' => $file)));
  7355. }
  7356. $archiver_info = archiver_get_info();
  7357. foreach ($archiver_info as $implementation) {
  7358. foreach ($implementation['extensions'] as $extension) {
  7359. // Because extensions may be multi-part, such as .tar.gz,
  7360. // we cannot use simpler approaches like substr() or pathinfo().
  7361. // This method isn't quite as clean but gets the job done.
  7362. // Also note that the file may not yet exist, so we cannot rely
  7363. // on fileinfo() or other disk-level utilities.
  7364. if (strrpos($filepath, '.' . $extension) === strlen($filepath) - strlen('.' . $extension)) {
  7365. return new $implementation['class']($filepath);
  7366. }
  7367. }
  7368. }
  7369. }
  7370. /**
  7371. * Assembles the Drupal Updater registry.
  7372. *
  7373. * An Updater is a class that knows how to update various parts of the Drupal
  7374. * file system, for example to update modules that have newer releases, or to
  7375. * install a new theme.
  7376. *
  7377. * @return
  7378. * The Drupal Updater class registry.
  7379. *
  7380. * @see hook_updater_info()
  7381. * @see hook_updater_info_alter()
  7382. */
  7383. function drupal_get_updaters() {
  7384. $updaters = &drupal_static(__FUNCTION__);
  7385. if (!isset($updaters)) {
  7386. $updaters = module_invoke_all('updater_info');
  7387. drupal_alter('updater_info', $updaters);
  7388. uasort($updaters, 'drupal_sort_weight');
  7389. }
  7390. return $updaters;
  7391. }
  7392. /**
  7393. * Assembles the Drupal FileTransfer registry.
  7394. *
  7395. * @return
  7396. * The Drupal FileTransfer class registry.
  7397. *
  7398. * @see FileTransfer
  7399. * @see hook_filetransfer_info()
  7400. * @see hook_filetransfer_info_alter()
  7401. */
  7402. function drupal_get_filetransfer_info() {
  7403. $info = &drupal_static(__FUNCTION__);
  7404. if (!isset($info)) {
  7405. // Since we have to manually set the 'file path' default for each
  7406. // module separately, we can't use module_invoke_all().
  7407. $info = array();
  7408. foreach (module_implements('filetransfer_info') as $module) {
  7409. $function = $module . '_filetransfer_info';
  7410. if (function_exists($function)) {
  7411. $result = $function();
  7412. if (isset($result) && is_array($result)) {
  7413. foreach ($result as &$values) {
  7414. if (empty($values['file path'])) {
  7415. $values['file path'] = drupal_get_path('module', $module);
  7416. }
  7417. }
  7418. $info = array_merge_recursive($info, $result);
  7419. }
  7420. }
  7421. }
  7422. drupal_alter('filetransfer_info', $info);
  7423. uasort($info, 'drupal_sort_weight');
  7424. }
  7425. return $info;
  7426. }