PageRenderTime 112ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 1ms

/includes/common.inc

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