common.inc

Common functions that many Drupal modules will need to reference.

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

Functions

Namesort descending Description
archiver_get_archiver Creates the appropriate archiver for the specified file.
archiver_get_extensions Returns a string of supported archive extensions.
archiver_get_info Retrieves a list of all available archivers.
base_path Returns the base URL path (i.e., directory) of the Drupal installation.
check_url Strips dangerous protocols from a URI and encodes it for output to HTML.
date_iso8601 Returns an ISO8601 formatted date based on the given date.
debug Outputs debug information.
drupal_access_denied Delivers an "access denied" error to the browser.
drupal_add_css Adds a cascading stylesheet to the stylesheet queue.
drupal_add_feed Adds a feed URL for the current page.
drupal_add_html_head Adds output to the HEAD tag of the HTML page.
drupal_add_html_head_link Adds a LINK tag with a distinct 'rel' attribute to the page's HEAD.
drupal_add_js Adds a JavaScript file, setting, or inline code to the page.
drupal_add_library Adds multiple JavaScript or CSS files at the same time.
drupal_add_region_content Adds content to a specified region.
drupal_add_tabledrag Assists in adding the tableDrag JavaScript behavior to a themed table.
drupal_aggregate_css Default callback to aggregate CSS files and inline content.
drupal_array_get_nested_value Retrieves a value from a nested array with variable depth.
drupal_array_nested_key_exists Determines whether a nested array contains the requested keys.
drupal_array_set_nested_value Sets a value in a nested array with variable depth.
drupal_attributes Converts an associative array to an XML/HTML tag attribute string.
drupal_build_css_cache Aggregates and optimizes CSS files into a cache file in the files directory.
drupal_build_js_cache Aggregates JavaScript files into a cache file in the files directory.
drupal_check_incompatibility Checks whether a version is compatible with a given dependency.
drupal_clean_css_identifier Prepares a string for use as a CSS identifier (element, class, or ID name).
drupal_clear_css_cache Deletes old cached CSS files.
drupal_clear_js_cache Deletes old cached JavaScript files and variables.
drupal_common_theme Provides theme registration for themes across .inc files.
drupal_cron_cleanup Shutdown function: Performs cron cleanup.
drupal_cron_run Executes a cron run when called.
drupal_delete_file_if_stale Callback to delete files modified more than a set time ago.
drupal_deliver_html_page Packages and sends the result of a page callback to the browser as HTML.
drupal_deliver_page Delivers a page callback result to the browser in the appropriate format.
drupal_encode_path Encodes a Drupal path for use in a URL.
drupal_exit Performs end-of-request tasks.
drupal_explode_tags Explodes a string of tags into an array.
drupal_flush_all_caches Flushes all cached data on the site.
drupal_get_breadcrumb Gets the breadcrumb trail for the current page.
drupal_get_css Returns a themed representation of all stylesheets to attach to the page.
drupal_get_destination Prepares a 'destination' URL query parameter for use with drupal_goto().
drupal_get_feeds Gets the feed URLs for the current page.
drupal_get_filetransfer_info Assembles the Drupal FileTransfer registry.
drupal_get_hash_salt Gets a salt useful for hardening against SQL injection.
drupal_get_html_head Retrieves output to be displayed in the HEAD tag of the HTML page.
drupal_get_js Returns a themed presentation of all JavaScript code for the current page.
drupal_get_library Retrieves information for a JavaScript/CSS library.
drupal_get_path Returns the path to a system item (module, theme, etc.).
drupal_get_private_key Ensures the private key variable used to generate tokens is set.
drupal_get_profile Gets the name of the currently active installation profile.
drupal_get_query_array Splits a URL-encoded query string into an array.
drupal_get_query_parameters Processes a URL query parameter array to remove unwanted elements.
drupal_get_rdf_namespaces Returns a string containing RDF namespace declarations for use in XML and XHTML output.
drupal_get_region_content Gets assigned content for a given region.
drupal_get_schema_unprocessed Returns the unprocessed and unaltered version of a module's schema.
drupal_get_token Generates a token based on $value, the user session, and the private key.
drupal_get_updaters Assembles the Drupal Updater registry.
drupal_goto Sends the user to a different Drupal page.
drupal_group_css Default callback to group CSS items.
drupal_html_class Prepares a string for use as a valid class name.
drupal_html_id Prepares a string for use as a valid HTML ID and guarantees uniqueness.
drupal_http_build_query Parses an array into a valid, rawurlencoded query string.
drupal_http_header_attributes Formats an attribute string for an HTTP header.
drupal_http_request Performs an HTTP request.
drupal_implode_tags Implodes an array of tags into a string.
drupal_install_schema Creates all tables defined in a module's hook_schema().
drupal_json_decode Converts an HTML-safe JSON string into its PHP equivalent.
drupal_json_encode Converts a PHP variable into its JavaScript equivalent.
drupal_json_output Returns data in JSON format.
drupal_js_defaults Constructs an array of the defaults that are used for JavaScript items.
drupal_load_stylesheet Loads the stylesheet and resolves all @import commands.
drupal_load_stylesheet_content Processes the contents of a stylesheet for aggregation.
drupal_map_assoc Forms an associative array from a linear array.
drupal_not_found Delivers a "page not found" error to the browser.
drupal_page_footer Performs end-of-request tasks.
drupal_page_set_cache Stores the current page in the cache.
drupal_parse_dependency Parses a dependency for comparison by drupal_check_incompatibility().
drupal_parse_info_file Parses Drupal module and theme .info files.
drupal_parse_info_format Parses data in Drupal's .info format.
drupal_parse_url Parses a system URL string into an associative array suitable for url().
drupal_pre_render_conditional_comments #pre_render callback to render #browsers into #prefix and #suffix.
drupal_pre_render_link #pre_render callback to render a link into #markup.
drupal_pre_render_links #pre_render callback that collects child links into a single array.
drupal_pre_render_markup #pre_render callback to append contents in #markup to #children.
drupal_pre_render_styles #pre_render callback to add the elements needed for CSS tags to be rendered.
drupal_process_attached Adds attachments to a render() structure.
drupal_process_states Adds JavaScript to change the state of an element based on another element.
drupal_region_class Provides a standard HTML class name that identifies a page region.
drupal_render Renders HTML given a structured array tree.
drupal_render_cache_by_query Prepares an element for caching based on a query.
drupal_render_cache_get Gets the rendered output of a renderable element from the cache.
drupal_render_cache_set Caches the rendered output of a renderable element.
drupal_render_children Renders children of an element and concatenates them.
drupal_render_cid_create Creates the cache ID for a renderable element.
drupal_render_cid_parts Returns cache ID parts for building a cache ID.
drupal_render_collect_attached Collects #attached for an element and its children into a single array.
drupal_render_page Renders the page, including all theming.
drupal_schema_fields_sql Retrieves a list of fields from a table schema.
drupal_set_breadcrumb Sets the breadcrumb trail for the current page.
drupal_set_page_content Sets the main page content value for later use.
drupal_set_time_limit Attempts to set the PHP maximum execution time.
drupal_site_offline Delivers a "site is under maintenance" message to the browser.
drupal_sort_css_js Sorts CSS and JavaScript resources.
drupal_sort_title Array sorting callback; sorts elements by 'title' key.
drupal_sort_weight Sorts a structured array by the 'weight' element.
drupal_strip_dangerous_protocols Strips dangerous protocols (e.g. 'javascript:') from a URI.
drupal_system_listing Returns information about system object files (modules, themes, etc.).
drupal_uninstall_schema Removes all tables defined in a module's hook_schema().
drupal_valid_token Validates a token based on $value, the user session, and the private key.
drupal_write_record Saves (inserts or updates) a record to the database based upon the schema.
element_child Checks if the key is a child.
element_children Identifies the children of an element array, optionally sorted by weight.
element_get_visible_children Returns the visible children of an element.
element_info Retrieves the default properties for the defined element type.
element_info_property Retrieves a single property for the defined element type.
element_properties Gets properties of a structured array element (keys beginning with '#').
element_property Checks if the key is a property.
element_set_attributes Sets HTML attributes based on element properties.
element_sort Function used by uasort to sort structured arrays by weight.
element_sort_by_title Array sorting callback; sorts elements by title.
entity_create_stub_entity Helper function to assemble an object structure with initial ids.
entity_extract_ids Helper function to extract id, vid, and bundle name from an entity.
entity_form_field_validate Attaches field API validation to entity forms.
entity_form_submit_build_entity Copies submitted values to entity properties for simple entity forms.
entity_get_controller Get the entity controller class for an entity type.
entity_get_info Get the entity info array of an entity type.
entity_info_cache_clear Resets the cached information about entity types.
entity_label Returns the label of an entity.
entity_language Returns the language of an entity.
entity_load Load entities from the database.
entity_load_unchanged Loads the unchanged, i.e. not modified, entity from the database.
entity_prepare_view Invoke hook_entity_prepare_view().
entity_uri Returns the URI elements of an entity.
filter_xss Filters HTML to prevent cross-site-scripting (XSS) vulnerabilities.
filter_xss_admin Applies a very permissive XSS/HTML filter for admin-only use.
filter_xss_bad_protocol Processes an HTML attribute value and strips dangerous protocols from URLs.
fix_gpc_magic Fixes double-escaping caused by "magic quotes" in some PHP installations.
flood_clear_event Makes the flood control mechanism forget an event for the current visitor.
flood_is_allowed Checks whether a user is allowed to proceed with the specified event.
flood_register_event Registers an event for the current visitor to the flood control mechanism.
format_date Formats a date, using a date type or a custom date format string.
format_interval Formats a time interval with the requested granularity.
format_plural Formats a string containing a count of items.
format_rss_channel Formats an RSS channel.
format_rss_item Formats a single RSS item.
format_size Generates a string representation for the given byte count.
format_username Format a username.
format_xml_elements Formats XML elements.
hide Hides an element from later rendering.
l Formats an internal or external URL link as an HTML anchor tag.
parse_size Parses a given byte count.
render Renders an element.
show Shows a hidden element for later rendering.
url Generates an internal or external URL.
url_is_external Returns TRUE if a path is external to Drupal (e.g. http://example.com).
valid_email_address Verifies the syntax of the given e-mail address.
valid_url Verifies the syntax of the given URL.
watchdog_severity_levels Returns a list of severity levels, as defined in RFC 3164.
xmlrpc Performs one or more XML-RPC request(s).
_drupal_bootstrap_full
_drupal_build_css_path Prefixes all paths within a CSS file for drupal_build_css_cache().
_drupal_default_html_head Returns elements that are always displayed in the HEAD tag of the HTML page.
_drupal_flush_css_js Changes the dummy query string added to all CSS and JavaScript files.
_drupal_http_use_proxy Helper function for determining hosts excluded from needing a proxy.
_drupal_load_stylesheet Loads stylesheets recursively and returns contents with corrected paths.
_drupal_schema_initialize Fills in required default values for table definitions from hook_schema().
_filter_xss_attributes Processes a string of HTML attributes.
_filter_xss_split Processes an HTML tag.
_fix_gpc_magic Strips slashes from a string or array of strings.
_fix_gpc_magic_files Strips slashes from $_FILES items.
_format_date_callback Translates a formatted date string.

Constants

Namesort descending Description
CSS_DEFAULT The default group for module CSS files added to the page.
CSS_SYSTEM The default group for system CSS files added to the page.
CSS_THEME The default group for theme CSS files added to the page.
DRUPAL_CACHE_CUSTOM The block is handling its own caching in its hook_block_view().
DRUPAL_CACHE_GLOBAL The block or element is the same for every user and page that it is visible.
DRUPAL_CACHE_PER_PAGE The block or element can change depending on the page being viewed.
DRUPAL_CACHE_PER_ROLE The block or element can change depending on the user's roles.
DRUPAL_CACHE_PER_USER The block or element can change depending on the user.
DRUPAL_NO_CACHE The block should not get cached.
HTTP_REQUEST_TIMEOUT Error code indicating that the request exceeded the specified timeout.
JS_DEFAULT The default group for module JavaScript code added to the page.
JS_LIBRARY The default group for JavaScript and jQuery libraries added to the page.
JS_THEME The default group for theme JavaScript code added to the page.
SAVED_DELETED Return status for saving which deleted an existing item.
SAVED_NEW Return status for saving which involved creating a new item.
SAVED_UPDATED Return status for saving which involved an update to an existing item.

File

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