PageRenderTime 90ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/includes/common.inc

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