Skip navigation
Help

common.inc

  1. drupal
    1. 6 drupal/includes/common.inc
    2. 7 drupal/includes/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 & methods

NameDescription
base_pathReturns the base URL path of the Drupal installation. At the very least, this will always default to /.
check_file
check_urlPrepare a URL for use in an HTML attribute. Strips harmful protocols.
drupal_access_deniedGenerates a 403 error if the request is not allowed.
drupal_add_cssAdds a CSS file to the stylesheet queue.
drupal_add_feedAdd a feed URL for the current page.
drupal_add_jsAdd a JavaScript file, setting or inline code to the page.
drupal_add_linkAdd a <link> tag to the page's HEAD.
drupal_add_tabledragAssist in adding the tableDrag JavaScript behavior to a themed table.
drupal_alterHands off alterable variables to type-specific *_alter implementations.
drupal_attributesFormat an attribute string to insert in a tag.
drupal_build_css_cacheAggregate and optimize CSS files, putting them in the files directory.
drupal_build_js_cacheAggregate JS files, putting them in the files directory.
drupal_clear_css_cacheDelete all cached CSS files.
drupal_clear_js_cacheDelete all cached JS files.
drupal_clear_path_cacheReset the static variable which holds the aliases mapped for this request.
drupal_cloneProvide a substitute clone() function for PHP4.
drupal_common_themeProvide theme registration for themes across .inc files.
drupal_cron_cleanupShutdown function for cron cleanup.
drupal_cron_runExecutes a cron run when called
drupal_error_handlerLog errors as defined by administrator.
drupal_evalEvaluate a string of PHP code.
drupal_explode_tagsExplode a string of given tags into an array.
drupal_final_markupMake any final alterations to the rendered xhtml.
drupal_flush_all_cachesFlush all cached data on the site.
drupal_get_breadcrumbGet the breadcrumb trail for the current page.
drupal_get_contentGet assigned content.
drupal_get_cssReturns a themed representation of all stylesheets that should be attached to the page.
drupal_get_destinationPrepare a destination query string for use in combination with drupal_goto().
drupal_get_feedsGet the feed URLs for the current page.
drupal_get_headersGet the HTTP response headers for the current page.
drupal_get_html_headRetrieve output to be displayed in the head tag of the HTML page.
drupal_get_jsReturns a themed presentation of all JavaScript code for the current page.
drupal_get_pathReturns the path to a system item (module, theme, etc.).
drupal_get_private_keyEnsure the private key variable used to generate tokens is set.
drupal_get_schemaGet the schema definition of a table, or the whole database schema.
drupal_get_schema_unprocessedReturns the unprocessed and unaltered version of a module's schema.
drupal_get_tokenGenerate a token based on $value, the current user session and private key.
drupal_gotoSend the user to a different Drupal page.
drupal_http_requestPerform an HTTP request.
drupal_implode_tagsImplode an array of tags into a string.
drupal_install_schemaCreate all tables that a module defines in its hook_schema().
drupal_jsonReturn data in JSON format.
drupal_load_stylesheetLoads the stylesheet and resolves all @import commands.
drupal_map_assocForm an associative array from a linear array.
drupal_not_foundGenerates a 404 error if the request can not be handled.
drupal_page_footerPerform end-of-request tasks.
drupal_parse_info_fileParse Drupal info file format.
drupal_query_string_encodeParse an array into a valid urlencoded query string.
drupal_renderRenders HTML given a structured array tree.
drupal_schema_fields_sqlRetrieve a list of fields from a table schema. The list is suitable for use in a SQL query.
drupal_set_breadcrumbSet the breadcrumb trail for the current page.
drupal_set_contentSet content for a specified region.
drupal_set_headerSet an HTTP response header for the current page.
drupal_set_html_headAdd output to the head tag of the HTML page.
drupal_site_offlineGenerates a site off-line message.
drupal_system_listingReturn an array of system file objects.
drupal_to_jsConverts a PHP variable into its Javascript equivalent.
drupal_uninstall_schemaRemove all tables that a module defines in its hook_schema().
drupal_urlencodeWrapper around urlencode() which avoids Apache quirks.
drupal_valid_tokenValidate a token based on $value, the current user session and private key.
drupal_write_recordSave a record to the database based upon the schema.
element_childCheck if the key is a child.
element_childrenGet keys of a structured array tree element that are not properties (i.e., do not begin with '#').
element_propertiesGet properties of a structured array element. Properties begin with '#'.
element_propertyCheck if the key is a property.
element_sortFunction used by uasort to sort structured arrays by weight.
fix_gpc_magicFix double-escaping problems caused by "magic quotes" in some PHP installations.
flood_is_allowedCheck if the current visitor (hostname/IP) is allowed to proceed with the specified event.
flood_register_eventRegister an event for the current visitor (hostname/IP) to the flood control mechanism.
format_dateFormat a date with the given configured format or a custom format string.
format_intervalFormat a time interval with the requested granularity.
format_pluralFormat a string containing a count of items.
format_rss_channelFormats an RSS channel.
format_rss_itemFormat a single RSS item.
format_sizeGenerate a string representation for the given byte count.
format_xml_elementsFormat XML elements.
lFormats an internal or external URL link as an HTML anchor tag.
page_set_cacheStore the current page in the cache.
parse_sizeParse a given byte count.
tTranslate strings to the page language or a given language.
urlGenerates an internal or external URL.
valid_email_addressVerifies the syntax of the given e-mail address.
valid_urlVerify the syntax of the given URL.
watchdog_severity_levels
xmlrpcPerforms one or more XML-RPC request(s).
_drupal_bootstrap_full
_drupal_build_css_pathHelper function for drupal_build_css_cache().
_drupal_flush_css_jsHelper function to change query-strings on css/js files.
_drupal_initialize_schemaFill in required default values for table definitions returned by hook_schema().
_drupal_load_stylesheetLoads stylesheets recursively and returns contents with corrected paths.
_fix_gpc_magic
_fix_gpc_magic_filesHelper function to strip slashes from $_FILES skipping over the tmp_name keys since PHP generates single backslashes for file paths on Windows systems.
_process_commentProcess comment blocks.

Constants

NameDescription
SAVED_DELETEDReturn status for saving which deleted an existing item.
SAVED_NEWReturn status for saving which involved creating a new item.
SAVED_UPDATEDReturn status for saving which involved an update to an existing item.

File

drupal/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. * Return status for saving which involved creating a new item.
  11. */
  12. define('SAVED_NEW', 1);
  13. /**
  14. * Return status for saving which involved an update to an existing item.
  15. */
  16. define('SAVED_UPDATED', 2);
  17. /**
  18. * Return status for saving which deleted an existing item.
  19. */
  20. define('SAVED_DELETED', 3);
  21. /**
  22. * Create E_DEPRECATED constant for older PHP versions (<5.3).
  23. */
  24. if (!defined('E_DEPRECATED')) {
  25. define('E_DEPRECATED', 8192);
  26. }
  27. /**
  28. * Set content for a specified region.
  29. *
  30. * @param $region
  31. * Page region the content is assigned to.
  32. * @param $data
  33. * Content to be set.
  34. */
  35. function drupal_set_content($region = NULL, $data = NULL) {
  36. static $content = array();
  37. if (!is_null($region) && !is_null($data)) {
  38. $content[$region][] = $data;
  39. }
  40. return $content;
  41. }
  42. /**
  43. * Get assigned content.
  44. *
  45. * @param $region
  46. * A specified region to fetch content for. If NULL, all regions will be
  47. * returned.
  48. * @param $delimiter
  49. * Content to be inserted between imploded array elements.
  50. */
  51. function drupal_get_content($region = NULL, $delimiter = ' ') {
  52. $content = drupal_set_content();
  53. if (isset($region)) {
  54. if (isset($content[$region]) && is_array($content[$region])) {
  55. return implode($delimiter, $content[$region]);
  56. }
  57. }
  58. else {
  59. foreach (array_keys($content) as $region) {
  60. if (is_array($content[$region])) {
  61. $content[$region] = implode($delimiter, $content[$region]);
  62. }
  63. }
  64. return $content;
  65. }
  66. }
  67. /**
  68. * Set the breadcrumb trail for the current page.
  69. *
  70. * @param $breadcrumb
  71. * Array of links, starting with "home" and proceeding up to but not including
  72. * the current page.
  73. */
  74. function drupal_set_breadcrumb($breadcrumb = NULL) {
  75. static $stored_breadcrumb;
  76. if (!is_null($breadcrumb)) {
  77. $stored_breadcrumb = $breadcrumb;
  78. }
  79. return $stored_breadcrumb;
  80. }
  81. /**
  82. * Get the breadcrumb trail for the current page.
  83. */
  84. function drupal_get_breadcrumb() {
  85. $breadcrumb = drupal_set_breadcrumb();
  86. if (is_null($breadcrumb)) {
  87. $breadcrumb = menu_get_active_breadcrumb();
  88. }
  89. return $breadcrumb;
  90. }
  91. /**
  92. * Add output to the head tag of the HTML page.
  93. *
  94. * This function can be called as long the headers aren't sent.
  95. */
  96. function drupal_set_html_head($data = NULL) {
  97. static $stored_head = '';
  98. if (!is_null($data)) {
  99. $stored_head .= $data ."\n";
  100. }
  101. return $stored_head;
  102. }
  103. /**
  104. * Retrieve output to be displayed in the head tag of the HTML page.
  105. */
  106. function drupal_get_html_head() {
  107. $output = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
  108. return $output . drupal_set_html_head();
  109. }
  110. /**
  111. * Reset the static variable which holds the aliases mapped for this request.
  112. */
  113. function drupal_clear_path_cache() {
  114. drupal_lookup_path('wipe');
  115. }
  116. /**
  117. * Set an HTTP response header for the current page.
  118. *
  119. * Note: When sending a Content-Type header, always include a 'charset' type,
  120. * too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
  121. */
  122. function drupal_set_header($header = NULL) {
  123. // We use an array to guarantee there are no leading or trailing delimiters.
  124. // Otherwise, header('') could get called when serving the page later, which
  125. // ends HTTP headers prematurely on some PHP versions.
  126. static $stored_headers = array();
  127. if (strlen($header)) {
  128. header($header);
  129. $stored_headers[] = $header;
  130. }
  131. return implode("\n", $stored_headers);
  132. }
  133. /**
  134. * Get the HTTP response headers for the current page.
  135. */
  136. function drupal_get_headers() {
  137. return drupal_set_header();
  138. }
  139. /**
  140. * Make any final alterations to the rendered xhtml.
  141. */
  142. function drupal_final_markup($content) {
  143. // Make sure that the charset is always specified as the first element of the
  144. // head region to prevent encoding-based attacks.
  145. return preg_replace('/<head[^>]*>/i', "\$0\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />", $content, 1);
  146. }
  147. /**
  148. * Add a feed URL for the current page.
  149. *
  150. * @param $url
  151. * A url for the feed.
  152. * @param $title
  153. * The title of the feed.
  154. */
  155. function drupal_add_feed($url = NULL, $title = '') {
  156. static $stored_feed_links = array();
  157. if (!is_null($url) && !isset($stored_feed_links[$url])) {
  158. $stored_feed_links[$url] = theme('feed_icon', $url, $title);
  159. drupal_add_link(array('rel' => 'alternate',
  160. 'type' => 'application/rss+xml',
  161. 'title' => $title,
  162. 'href' => $url));
  163. }
  164. return $stored_feed_links;
  165. }
  166. /**
  167. * Get the feed URLs for the current page.
  168. *
  169. * @param $delimiter
  170. * A delimiter to split feeds by.
  171. */
  172. function drupal_get_feeds($delimiter = "\n") {
  173. $feeds = drupal_add_feed();
  174. return implode($feeds, $delimiter);
  175. }
  176. /**
  177. * @defgroup http_handling HTTP handling
  178. * @{
  179. * Functions to properly handle HTTP responses.
  180. */
  181. /**
  182. * Parse an array into a valid urlencoded query string.
  183. *
  184. * @param $query
  185. * The array to be processed e.g. $_GET.
  186. * @param $exclude
  187. * The array filled with keys to be excluded. Use parent[child] to exclude
  188. * nested items.
  189. * @param $parent
  190. * Should not be passed, only used in recursive calls.
  191. * @return
  192. * An urlencoded string which can be appended to/as the URL query string.
  193. */
  194. function drupal_query_string_encode($query, $exclude = array(), $parent = '') {
  195. $params = array();
  196. foreach ($query as $key => $value) {
  197. $key = rawurlencode($key);
  198. if ($parent) {
  199. $key = $parent .'['. $key .']';
  200. }
  201. if (in_array($key, $exclude)) {
  202. continue;
  203. }
  204. if (is_array($value)) {
  205. $params[] = drupal_query_string_encode($value, $exclude, $key);
  206. }
  207. else {
  208. $params[] = $key .'='. rawurlencode($value);
  209. }
  210. }
  211. return implode('&', $params);
  212. }
  213. /**
  214. * Prepare a destination query string for use in combination with drupal_goto().
  215. *
  216. * Used to direct the user back to the referring page after completing a form.
  217. * By default the current URL is returned. If a destination exists in the
  218. * previous request, that destination is returned. As such, a destination can
  219. * persist across multiple pages.
  220. *
  221. * @see drupal_goto()
  222. */
  223. function drupal_get_destination() {
  224. if (isset($_REQUEST['destination'])) {
  225. return 'destination='. urlencode($_REQUEST['destination']);
  226. }
  227. else {
  228. // Use $_GET here to retrieve the original path in source form.
  229. $path = isset($_GET['q']) ? $_GET['q'] : '';
  230. $query = drupal_query_string_encode($_GET, array('q'));
  231. if ($query != '') {
  232. $path .= '?'. $query;
  233. }
  234. return 'destination='. urlencode($path);
  235. }
  236. }
  237. /**
  238. * Send the user to a different Drupal page.
  239. *
  240. * This issues an on-site HTTP redirect. The function makes sure the redirected
  241. * URL is formatted correctly.
  242. *
  243. * Usually the redirected URL is constructed from this function's input
  244. * parameters. However you may override that behavior by setting a
  245. * destination in either the $_REQUEST-array (i.e. by using
  246. * the query string of an URI) or the $_REQUEST['edit']-array (i.e. by
  247. * using a hidden form field). This is used to direct the user back to
  248. * the proper page after completing a form. For example, after editing
  249. * a post on the 'admin/content/node'-page or after having logged on using the
  250. * 'user login'-block in a sidebar. The function drupal_get_destination()
  251. * can be used to help set the destination URL.
  252. *
  253. * Drupal will ensure that messages set by drupal_set_message() and other
  254. * session data are written to the database before the user is redirected.
  255. *
  256. * This function ends the request; use it rather than a print theme('page')
  257. * statement in your menu callback.
  258. *
  259. * @param $path
  260. * A Drupal path or a full URL.
  261. * @param $query
  262. * A query string component, if any.
  263. * @param $fragment
  264. * A destination fragment identifier (named anchor).
  265. * @param $http_response_code
  266. * Valid values for an actual "goto" as per RFC 2616 section 10.3 are:
  267. * - 301 Moved Permanently (the recommended value for most redirects)
  268. * - 302 Found (default in Drupal and PHP, sometimes used for spamming search
  269. * engines)
  270. * - 303 See Other
  271. * - 304 Not Modified
  272. * - 305 Use Proxy
  273. * - 307 Temporary Redirect (alternative to "503 Site Down for Maintenance")
  274. * Note: Other values are defined by RFC 2616, but are rarely used and poorly
  275. * supported.
  276. * @see drupal_get_destination()
  277. */
  278. function drupal_goto($path = '', $query = NULL, $fragment = NULL, $http_response_code = 302) {
  279. $destination = FALSE;
  280. if (isset($_REQUEST['destination'])) {
  281. $destination = $_REQUEST['destination'];
  282. }
  283. else if (isset($_REQUEST['edit']['destination'])) {
  284. $destination = $_REQUEST['edit']['destination'];
  285. }
  286. if ($destination) {
  287. // Do not redirect to an absolute URL originating from user input.
  288. $colonpos = strpos($destination, ':');
  289. $absolute = ($colonpos !== FALSE && !preg_match('![/?#]!', substr($destination, 0, $colonpos)));
  290. if (!$absolute) {
  291. extract(parse_url(urldecode($destination)));
  292. }
  293. }
  294. $url = url($path, array('query' => $query, 'fragment' => $fragment, 'absolute' => TRUE));
  295. // Remove newlines from the URL to avoid header injection attacks.
  296. $url = str_replace(array("\n", "\r"), '', $url);
  297. // Allow modules to react to the end of the page request before redirecting.
  298. // We do not want this while running update.php.
  299. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
  300. module_invoke_all('exit', $url);
  301. }
  302. // Even though session_write_close() is registered as a shutdown function, we
  303. // need all session data written to the database before redirecting.
  304. session_write_close();
  305. header('Location: '. $url, TRUE, $http_response_code);
  306. // The "Location" header sends a redirect status code to the HTTP daemon. In
  307. // some cases this can be wrong, so we make sure none of the code below the
  308. // drupal_goto() call gets executed upon redirection.
  309. exit();
  310. }
  311. /**
  312. * Generates a site off-line message.
  313. */
  314. function drupal_site_offline() {
  315. drupal_maintenance_theme();
  316. drupal_set_header('HTTP/1.1 503 Service unavailable');
  317. drupal_set_title(t('Site off-line'));
  318. print theme('maintenance_page', filter_xss_admin(variable_get('site_offline_message',
  319. t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal'))))));
  320. }
  321. /**
  322. * Generates a 404 error if the request can not be handled.
  323. */
  324. function drupal_not_found() {
  325. drupal_set_header('HTTP/1.1 404 Not Found');
  326. watchdog('page not found', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
  327. // Keep old path for reference, and to allow forms to redirect to it.
  328. if (!isset($_REQUEST['destination'])) {
  329. $_REQUEST['destination'] = $_GET['q'];
  330. }
  331. $path = drupal_get_normal_path(variable_get('site_404', ''));
  332. if ($path && $path != $_GET['q']) {
  333. // Set the active item in case there are tabs to display, or other
  334. // dependencies on the path.
  335. menu_set_active_item($path);
  336. $return = menu_execute_active_handler($path);
  337. }
  338. if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
  339. drupal_set_title(t('Page not found'));
  340. $return = t('The requested page could not be found.');
  341. }
  342. // To conserve CPU and bandwidth, omit the blocks.
  343. print theme('page', $return, FALSE);
  344. }
  345. /**
  346. * Generates a 403 error if the request is not allowed.
  347. */
  348. function drupal_access_denied() {
  349. drupal_set_header('HTTP/1.1 403 Forbidden');
  350. watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
  351. // Keep old path for reference, and to allow forms to redirect to it.
  352. if (!isset($_REQUEST['destination'])) {
  353. $_REQUEST['destination'] = $_GET['q'];
  354. }
  355. $path = drupal_get_normal_path(variable_get('site_403', ''));
  356. if ($path && $path != $_GET['q']) {
  357. // Set the active item in case there are tabs to display or other
  358. // dependencies on the path.
  359. menu_set_active_item($path);
  360. $return = menu_execute_active_handler($path);
  361. }
  362. if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
  363. drupal_set_title(t('Access denied'));
  364. $return = t('You are not authorized to access this page.');
  365. }
  366. print theme('page', $return);
  367. }
  368. /**
  369. * Perform an HTTP request.
  370. *
  371. * This is a flexible and powerful HTTP client implementation. Correctly handles
  372. * GET, POST, PUT or any other HTTP requests. Handles redirects.
  373. *
  374. * @param $url
  375. * A string containing a fully qualified URI.
  376. * @param $headers
  377. * An array containing an HTTP header => value pair.
  378. * @param $method
  379. * A string defining the HTTP request to use.
  380. * @param $data
  381. * A string containing data to include in the request.
  382. * @param $retry
  383. * An integer representing how many times to retry the request in case of a
  384. * redirect.
  385. * @return
  386. * An object containing the HTTP request headers, response code, protocol,
  387. * status message, headers, data and redirect status.
  388. */
  389. function drupal_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) {
  390. global $db_prefix;
  391. $result = new stdClass();
  392. // Parse the URL and make sure we can handle the schema.
  393. $uri = parse_url($url);
  394. if ($uri == FALSE) {
  395. $result->error = 'unable to parse URL';
  396. $result->code = -1001;
  397. return $result;
  398. }
  399. if (!isset($uri['scheme'])) {
  400. $result->error = 'missing schema';
  401. $result->code = -1002;
  402. return $result;
  403. }
  404. switch ($uri['scheme']) {
  405. case 'http':
  406. case 'feed':
  407. $port = isset($uri['port']) ? $uri['port'] : 80;
  408. $host = $uri['host'] . ($port != 80 ? ':'. $port : '');
  409. $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
  410. break;
  411. case 'https':
  412. // Note: Only works for PHP 4.3 compiled with OpenSSL.
  413. $port = isset($uri['port']) ? $uri['port'] : 443;
  414. $host = $uri['host'] . ($port != 443 ? ':'. $port : '');
  415. $fp = @fsockopen('ssl://'. $uri['host'], $port, $errno, $errstr, 20);
  416. break;
  417. default:
  418. $result->error = 'invalid schema '. $uri['scheme'];
  419. $result->code = -1003;
  420. return $result;
  421. }
  422. // Make sure the socket opened properly.
  423. if (!$fp) {
  424. // When a network error occurs, we use a negative number so it does not
  425. // clash with the HTTP status codes.
  426. $result->code = -$errno;
  427. $result->error = trim($errstr);
  428. // Mark that this request failed. This will trigger a check of the web
  429. // server's ability to make outgoing HTTP requests the next time that
  430. // requirements checking is performed.
  431. // @see system_requirements()
  432. variable_set('drupal_http_request_fails', TRUE);
  433. return $result;
  434. }
  435. // Construct the path to act on.
  436. $path = isset($uri['path']) ? $uri['path'] : '/';
  437. if (isset($uri['query'])) {
  438. $path .= '?'. $uri['query'];
  439. }
  440. // Create HTTP request.
  441. $defaults = array(
  442. // RFC 2616: "non-standard ports MUST, default ports MAY be included".
  443. // We don't add the port to prevent from breaking rewrite rules checking the
  444. // host that do not take into account the port number.
  445. 'Host' => "Host: $host",
  446. 'User-Agent' => 'User-Agent: Drupal (+http://drupal.org/)',
  447. );
  448. // Only add Content-Length if we actually have any content or if it is a POST
  449. // or PUT request. Some non-standard servers get confused by Content-Length in
  450. // at least HEAD/GET requests, and Squid always requires Content-Length in
  451. // POST/PUT requests.
  452. $content_length = strlen($data);
  453. if ($content_length > 0 || $method == 'POST' || $method == 'PUT') {
  454. $defaults['Content-Length'] = 'Content-Length: '. $content_length;
  455. }
  456. // If the server url has a user then attempt to use basic authentication
  457. if (isset($uri['user'])) {
  458. $defaults['Authorization'] = 'Authorization: Basic '. base64_encode($uri['user'] . (!empty($uri['pass']) ? ":". $uri['pass'] : ''));
  459. }
  460. // If the database prefix is being used by SimpleTest to run the tests in a copied
  461. // database then set the user-agent header to the database prefix so that any
  462. // calls to other Drupal pages will run the SimpleTest prefixed database. The
  463. // user-agent is used to ensure that multiple testing sessions running at the
  464. // same time won't interfere with each other as they would if the database
  465. // prefix were stored statically in a file or database variable.
  466. if (is_string($db_prefix) && preg_match("/^simpletest\d+$/", $db_prefix, $matches)) {
  467. $defaults['User-Agent'] = 'User-Agent: ' . $matches[0];
  468. }
  469. foreach ($headers as $header => $value) {
  470. $defaults[$header] = $header .': '. $value;
  471. }
  472. $request = $method .' '. $path ." HTTP/1.0\r\n";
  473. $request .= implode("\r\n", $defaults);
  474. $request .= "\r\n\r\n";
  475. $request .= $data;
  476. $result->request = $request;
  477. fwrite($fp, $request);
  478. // Fetch response.
  479. $response = '';
  480. while (!feof($fp) && $chunk = fread($fp, 1024)) {
  481. $response .= $chunk;
  482. }
  483. fclose($fp);
  484. // Parse response.
  485. list($split, $result->data) = explode("\r\n\r\n", $response, 2);
  486. $split = preg_split("/\r\n|\n|\r/", $split);
  487. list($protocol, $code, $status_message) = explode(' ', trim(array_shift($split)), 3);
  488. $result->protocol = $protocol;
  489. $result->status_message = $status_message;
  490. $result->headers = array();
  491. // Parse headers.
  492. while ($line = trim(array_shift($split))) {
  493. list($header, $value) = explode(':', $line, 2);
  494. if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
  495. // RFC 2109: the Set-Cookie response header comprises the token Set-
  496. // Cookie:, followed by a comma-separated list of one or more cookies.
  497. $result->headers[$header] .= ','. trim($value);
  498. }
  499. else {
  500. $result->headers[$header] = trim($value);
  501. }
  502. }
  503. $responses = array(
  504. 100 => 'Continue', 101 => 'Switching Protocols',
  505. 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
  506. 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
  507. 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed',
  508. 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'
  509. );
  510. // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  511. // base code in their class.
  512. if (!isset($responses[$code])) {
  513. $code = floor($code / 100) * 100;
  514. }
  515. switch ($code) {
  516. case 200: // OK
  517. case 304: // Not modified
  518. break;
  519. case 301: // Moved permanently
  520. case 302: // Moved temporarily
  521. case 307: // Moved temporarily
  522. $location = $result->headers['Location'];
  523. if ($retry) {
  524. $result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
  525. $result->redirect_code = $result->code;
  526. }
  527. $result->redirect_url = $location;
  528. break;
  529. default:
  530. $result->error = $status_message;
  531. }
  532. $result->code = $code;
  533. return $result;
  534. }
  535. /**
  536. * @} End of "HTTP handling".
  537. */
  538. /**
  539. * Log errors as defined by administrator.
  540. *
  541. * Error levels:
  542. * - 0 = Log errors to database.
  543. * - 1 = Log errors to database and to screen.
  544. */
  545. function drupal_error_handler($errno, $message, $filename, $line, $context) {
  546. // If the @ error suppression operator was used, error_reporting will have
  547. // been temporarily set to 0.
  548. if (error_reporting() == 0) {
  549. return;
  550. }
  551. if ($errno & (E_ALL ^ E_DEPRECATED)) {
  552. $types = array(1 => 'error', 2 => 'warning', 4 => 'parse error', 8 => 'notice', 16 => 'core error', 32 => 'core warning', 64 => 'compile error', 128 => 'compile warning', 256 => 'user error', 512 => 'user warning', 1024 => 'user notice', 2048 => 'strict warning', 4096 => 'recoverable fatal error');
  553. // For database errors, we want the line number/file name of the place that
  554. // the query was originally called, not _db_query().
  555. if (isset($context[DB_ERROR])) {
  556. $backtrace = array_reverse(debug_backtrace());
  557. // List of functions where SQL queries can originate.
  558. $query_functions = array('db_query', 'pager_query', 'db_query_range', 'db_query_temporary', 'update_sql');
  559. // Determine where query function was called, and adjust line/file
  560. // accordingly.
  561. foreach ($backtrace as $index => $function) {
  562. if (in_array($function['function'], $query_functions)) {
  563. $line = $backtrace[$index]['line'];
  564. $filename = $backtrace[$index]['file'];
  565. break;
  566. }
  567. }
  568. }
  569. $entry = check_plain($types[$errno]) .': '. filter_xss($message) .' in '. check_plain($filename) .' on line '. check_plain($line) .'.';
  570. // Force display of error messages in update.php.
  571. if (variable_get('error_level', 1) == 1 || strstr($_SERVER['SCRIPT_NAME'], 'update.php')) {
  572. drupal_set_message($entry, 'error');
  573. }
  574. watchdog('php', '%message in %file on line %line.', array('%error' => $types[$errno], '%message' => $message, '%file' => $filename, '%line' => $line), WATCHDOG_ERROR);
  575. }
  576. }
  577. function _fix_gpc_magic(&$item) {
  578. if (is_array($item)) {
  579. array_walk($item, '_fix_gpc_magic');
  580. }
  581. else {
  582. $item = stripslashes($item);
  583. }
  584. }
  585. /**
  586. * Helper function to strip slashes from $_FILES skipping over the tmp_name keys
  587. * since PHP generates single backslashes for file paths on Windows systems.
  588. *
  589. * tmp_name does not have backslashes added see
  590. * http://php.net/manual/en/features.file-upload.php#42280
  591. */
  592. function _fix_gpc_magic_files(&$item, $key) {
  593. if ($key != 'tmp_name') {
  594. if (is_array($item)) {
  595. array_walk($item, '_fix_gpc_magic_files');
  596. }
  597. else {
  598. $item = stripslashes($item);
  599. }
  600. }
  601. }
  602. /**
  603. * Fix double-escaping problems caused by "magic quotes" in some PHP installations.
  604. */
  605. function fix_gpc_magic() {
  606. static $fixed = FALSE;
  607. if (!$fixed && ini_get('magic_quotes_gpc')) {
  608. array_walk($_GET, '_fix_gpc_magic');
  609. array_walk($_POST, '_fix_gpc_magic');
  610. array_walk($_COOKIE, '_fix_gpc_magic');
  611. array_walk($_REQUEST, '_fix_gpc_magic');
  612. array_walk($_FILES, '_fix_gpc_magic_files');
  613. $fixed = TRUE;
  614. }
  615. }
  616. /**
  617. * Translate strings to the page language or a given language.
  618. *
  619. * Human-readable text that will be displayed somewhere within a page should
  620. * be run through the t() function.
  621. *
  622. * Examples:
  623. * @code
  624. * if (!$info || !$info['extension']) {
  625. * form_set_error('picture_upload', t('The uploaded file was not an image.'));
  626. * }
  627. *
  628. * $form['submit'] = array(
  629. * '#type' => 'submit',
  630. * '#value' => t('Log in'),
  631. * );
  632. * @endcode
  633. *
  634. * Any text within t() can be extracted by translators and changed into
  635. * the equivalent text in their native language.
  636. *
  637. * Special variables called "placeholders" are used to signal dynamic
  638. * information in a string which should not be translated. Placeholders
  639. * can also be used for text that may change from time to time (such as
  640. * link paths) to be changed without requiring updates to translations.
  641. *
  642. * For example:
  643. * @code
  644. * $output = t('There are currently %members and %visitors online.', array(
  645. * '%members' => format_plural($total_users, '1 user', '@count users'),
  646. * '%visitors' => format_plural($guests->count, '1 guest', '@count guests')));
  647. * @endcode
  648. *
  649. * There are three styles of placeholders:
  650. * - !variable, which indicates that the text should be inserted as-is. This is
  651. * useful for inserting variables into things like e-mail.
  652. * @code
  653. * $message[] = t("If you don't want to receive such e-mails, you can change your settings at !url.", array('!url' => url("user/$account->uid", array('absolute' => TRUE))));
  654. * @endcode
  655. *
  656. * - @variable, which indicates that the text should be run through
  657. * check_plain, to escape HTML characters. Use this for any output that's
  658. * displayed within a Drupal page.
  659. * @code
  660. * drupal_set_title($title = t("@name's blog", array('@name' => $account->name)));
  661. * @endcode
  662. *
  663. * - %variable, which indicates that the string should be HTML escaped and
  664. * highlighted with theme_placeholder() which shows up by default as
  665. * <em>emphasized</em>.
  666. * @code
  667. * $message = t('%name-from sent %name-to an e-mail.', array('%name-from' => $user->name, '%name-to' => $account->name));
  668. * @endcode
  669. *
  670. * When using t(), try to put entire sentences and strings in one t() call.
  671. * This makes it easier for translators, as it provides context as to what
  672. * each word refers to. HTML markup within translation strings is allowed, but
  673. * should be avoided if possible. The exception are embedded links; link
  674. * titles add a context for translators, so should be kept in the main string.
  675. *
  676. * Here is an example of incorrect usage of t():
  677. * @code
  678. * $output .= t('<p>Go to the @contact-page.</p>', array('@contact-page' => l(t('contact page'), 'contact')));
  679. * @endcode
  680. *
  681. * Here is an example of t() used correctly:
  682. * @code
  683. * $output .= '<p>'. t('Go to the <a href="@contact-page">contact page</a>.', array('@contact-page' => url('contact'))) .'</p>';
  684. * @endcode
  685. *
  686. * Avoid escaping quotation marks wherever possible.
  687. *
  688. * Incorrect:
  689. * @code
  690. * $output .= t('Don\'t click me.');
  691. * @endcode
  692. *
  693. * Correct:
  694. * @code
  695. * $output .= t("Don't click me.");
  696. * @endcode
  697. *
  698. * Because t() is designed for handling code-based strings, in almost all
  699. * cases, the actual string and not a variable must be passed through t().
  700. *
  701. * Extraction of translations is done based on the strings contained in t()
  702. * calls. If a variable is passed through t(), the content of the variable
  703. * cannot be extracted from the file for translation.
  704. *
  705. * Incorrect:
  706. * @code
  707. * $message = 'An error occurred.';
  708. * drupal_set_message(t($message), 'error');
  709. * $output .= t($message);
  710. * @endcode
  711. *
  712. * Correct:
  713. * @code
  714. * $message = t('An error occurred.');
  715. * drupal_set_message($message, 'error');
  716. * $output .= $message;
  717. * @endcode
  718. *
  719. * The only case in which variables can be passed safely through t() is when
  720. * code-based versions of the same strings will be passed through t() (or
  721. * otherwise extracted) elsewhere.
  722. *
  723. * In some cases, modules may include strings in code that can't use t()
  724. * calls. For example, a module may use an external PHP application that
  725. * produces strings that are loaded into variables in Drupal for output.
  726. * In these cases, module authors may include a dummy file that passes the
  727. * relevant strings through t(). This approach will allow the strings to be
  728. * extracted.
  729. *
  730. * Sample external (non-Drupal) code:
  731. * @code
  732. * class Time {
  733. * public $yesterday = 'Yesterday';
  734. * public $today = 'Today';
  735. * public $tomorrow = 'Tomorrow';
  736. * }
  737. * @endcode
  738. *
  739. * Sample dummy file.
  740. * @code
  741. * // Dummy function included in example.potx.inc.
  742. * function example_potx() {
  743. * $strings = array(
  744. * t('Yesterday'),
  745. * t('Today'),
  746. * t('Tomorrow'),
  747. * );
  748. * // No return value needed, since this is a dummy function.
  749. * }
  750. * @endcode
  751. *
  752. * Having passed strings through t() in a dummy function, it is then
  753. * okay to pass variables through t().
  754. *
  755. * Correct (if a dummy file was used):
  756. * @code
  757. * $time = new Time();
  758. * $output .= t($time->today);
  759. * @endcode
  760. *
  761. * However tempting it is, custom data from user input or other non-code
  762. * sources should not be passed through t(). Doing so leads to the following
  763. * problems and errors:
  764. * - The t() system doesn't support updates to existing strings. When user
  765. * data is updated, the next time it's passed through t() a new record is
  766. * created instead of an update. The database bloats over time and any
  767. * existing translations are orphaned with each update.
  768. * - The t() system assumes any data it receives is in English. User data may
  769. * be in another language, producing translation errors.
  770. * - The "Built-in interface" text group in the locale system is used to
  771. * produce translations for storage in .po files. When non-code strings are
  772. * passed through t(), they are added to this text group, which is rendered
  773. * inaccurate since it is a mix of actual interface strings and various user
  774. * input strings of uncertain origin.
  775. *
  776. * Incorrect:
  777. * @code
  778. * $item = item_load();
  779. * $output .= check_plain(t($item['title']));
  780. * @endcode
  781. *
  782. * Instead, translation of these data can be done through the locale system,
  783. * either directly or through helper functions provided by contributed
  784. * modules.
  785. * @see hook_locale()
  786. *
  787. * During installation, st() is used in place of t(). Code that may be called
  788. * during installation or during normal operation should use the get_t()
  789. * helper function.
  790. * @see st()
  791. * @see get_t()
  792. *
  793. * @param $string
  794. * A string containing the English string to translate.
  795. * @param $args
  796. * An associative array of replacements to make after translation. Incidences
  797. * of any key in this array are replaced with the corresponding value. Based
  798. * on the first character of the key, the value is escaped and/or themed:
  799. * - !variable: inserted as is
  800. * - @variable: escape plain text to HTML (check_plain)
  801. * - %variable: escape text and theme as a placeholder for user-submitted
  802. * content (check_plain + theme_placeholder)
  803. * @param $langcode
  804. * Optional language code to translate to a language other than what is used
  805. * to display the page.
  806. * @return
  807. * The translated string.
  808. */
  809. function t($string, $args = array(), $langcode = NULL) {
  810. global $language;
  811. static $custom_strings;
  812. $langcode = isset($langcode) ? $langcode : $language->language;
  813. // First, check for an array of customized strings. If present, use the array
  814. // *instead of* database lookups. This is a high performance way to provide a
  815. // handful of string replacements. See settings.php for examples.
  816. // Cache the $custom_strings variable to improve performance.
  817. if (!isset($custom_strings[$langcode])) {
  818. $custom_strings[$langcode] = variable_get('locale_custom_strings_'. $langcode, array());
  819. }
  820. // Custom strings work for English too, even if locale module is disabled.
  821. if (isset($custom_strings[$langcode][$string])) {
  822. $string = $custom_strings[$langcode][$string];
  823. }
  824. // Translate with locale module if enabled.
  825. elseif (function_exists('locale') && $langcode != 'en') {
  826. $string = locale($string, $langcode);
  827. }
  828. if (empty($args)) {
  829. return $string;
  830. }
  831. else {
  832. // Transform arguments before inserting them.
  833. foreach ($args as $key => $value) {
  834. switch ($key[0]) {
  835. case '@':
  836. // Escaped only.
  837. $args[$key] = check_plain($value);
  838. break;
  839. case '%':
  840. default:
  841. // Escaped and placeholder.
  842. $args[$key] = theme('placeholder', $value);
  843. break;
  844. case '!':
  845. // Pass-through.
  846. }
  847. }
  848. return strtr($string, $args);
  849. }
  850. }
  851. /**
  852. * @defgroup validation Input validation
  853. * @{
  854. * Functions to validate user input.
  855. */
  856. /**
  857. * Verifies the syntax of the given e-mail address.
  858. *
  859. * See RFC 2822 for details.
  860. *
  861. * @param $mail
  862. * A string containing an e-mail address.
  863. * @return
  864. * 1 if the email address is valid, 0 if it is invalid or empty, and FALSE if
  865. * there is an input error (such as passing in an array instead of a string).
  866. */
  867. function valid_email_address($mail) {
  868. $user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
  869. $domain = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+';
  870. $ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
  871. $ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';
  872. return preg_match("/^$user@($domain|(\[($ipv4|$ipv6)\]))$/", $mail);
  873. }
  874. /**
  875. * Verify the syntax of the given URL.
  876. *
  877. * This function should only be used on actual URLs. It should not be used for
  878. * Drupal menu paths, which can contain arbitrary characters.
  879. * Valid values per RFC 3986.
  880. *
  881. * @param $url
  882. * The URL to verify.
  883. * @param $absolute
  884. * Whether the URL is absolute (beginning with a scheme such as "http:").
  885. * @return
  886. * TRUE if the URL is in a valid format.
  887. */
  888. function valid_url($url, $absolute = FALSE) {
  889. if ($absolute) {
  890. return (bool)preg_match("
  891. /^ # Start at the beginning of the text
  892. (?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
  893. (?: # Userinfo (optional) which is typically
  894. (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
  895. (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
  896. )?
  897. (?:
  898. (?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
  899. |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
  900. )
  901. (?::[0-9]+)? # Server port number (optional)
  902. (?:[\/|\?]
  903. (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
  904. *)?
  905. $/xi", $url);
  906. }
  907. else {
  908. return (bool)preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url);
  909. }
  910. }
  911. /**
  912. * @} End of "defgroup validation".
  913. */
  914. /**
  915. * Register an event for the current visitor (hostname/IP) to the flood control mechanism.
  916. *
  917. * @param $name
  918. * The name of an event.
  919. */
  920. function flood_register_event($name) {
  921. db_query("INSERT INTO {flood} (event, hostname, timestamp) VALUES ('%s', '%s', %d)", $name, ip_address(), time());
  922. }
  923. /**
  924. * Check if the current visitor (hostname/IP) is allowed to proceed with the specified event.
  925. *
  926. * The user is allowed to proceed if he did not trigger the specified event more
  927. * than $threshold times per hour.
  928. *
  929. * @param $name
  930. * The name of the event.
  931. * @param $threshold
  932. * The maximum number of the specified event per hour (per visitor).
  933. * @return
  934. * True if the user did not exceed the hourly threshold. False otherwise.
  935. */
  936. function flood_is_allowed($name, $threshold) {
  937. $number = db_result(db_query("SELECT COUNT(*) FROM {flood} WHERE event = '%s' AND hostname = '%s' AND timestamp > %d", $name, ip_address(), time() - 3600));
  938. return ($number < $threshold ? TRUE : FALSE);
  939. }
  940. function check_file($filename) {
  941. return is_uploaded_file($filename);
  942. }
  943. /**
  944. * Prepare a URL for use in an HTML attribute. Strips harmful protocols.
  945. */
  946. function check_url($uri) {
  947. return filter_xss_bad_protocol($uri, FALSE);
  948. }
  949. /**
  950. * @defgroup format Formatting
  951. * @{
  952. * Functions to format numbers, strings, dates, etc.
  953. */
  954. /**
  955. * Formats an RSS channel.
  956. *
  957. * Arbitrary elements may be added using the $args associative array.
  958. */
  959. function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
  960. global $language;
  961. $langcode = $langcode ? $langcode : $language->language;
  962. $output = "<channel>\n";
  963. $output .= ' <title>'. check_plain($title) ."</title>\n";
  964. $output .= ' <link>'. check_url($link) ."</link>\n";
  965. // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
  966. // We strip all HTML tags, but need to prevent double encoding from properly
  967. // escaped source data (such as &amp becoming &amp;amp;).
  968. $output .= ' <description>'. check_plain(decode_entities(strip_tags($description))) ."</description>\n";
  969. $output .= ' <language>'. check_plain($langcode) ."</language>\n";
  970. $output .= format_xml_elements($args);
  971. $output .= $items;
  972. $output .= "</channel>\n";
  973. return $output;
  974. }
  975. /**
  976. * Format a single RSS item.
  977. *
  978. * Arbitrary elements may be added using the $args associative array.
  979. */
  980. function format_rss_item($title, $link, $description, $args = array()) {
  981. $output = "<item>\n";
  982. $output .= ' <title>'. check_plain($title) ."</title>\n";
  983. $output .= ' <link>'. check_url($link) ."</link>\n";
  984. $output .= ' <description>'. check_plain($description) ."</description>\n";
  985. $output .= format_xml_elements($args);
  986. $output .= "</item>\n";
  987. return $output;
  988. }
  989. /**
  990. * Format XML elements.
  991. *
  992. * @param $array
  993. * An array where each item represent an element and is either a:
  994. * - (key => value) pair (<key>value</key>)
  995. * - Associative array with fields:
  996. * - 'key': element name
  997. * - 'value': element contents
  998. * - 'attributes': associative array of element attributes
  999. *
  1000. * In both cases, 'value' can be a simple string, or it can be another array
  1001. * with the same format as $array itself for nesting.
  1002. */
  1003. function format_xml_elements($array) {
  1004. $output = '';
  1005. foreach ($array as $key => $value) {
  1006. if (is_numeric($key)) {
  1007. if ($value['key']) {
  1008. $output .= ' <'. $value['key'];
  1009. if (isset($value['attributes']) && is_array($value['attributes'])) {
  1010. $output .= drupal_attributes($value['attributes']);
  1011. }
  1012. if (isset($value['value']) && $value['value'] != '') {
  1013. $output .= '>'. (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) .'</'. $value['key'] .">\n";
  1014. }
  1015. else {
  1016. $output .= " />\n";
  1017. }
  1018. }
  1019. }
  1020. else {
  1021. $output .= ' <'. $key .'>'. (is_array($value) ? format_xml_elements($value) : check_plain($value)) ."</$key>\n";
  1022. }
  1023. }
  1024. return $output;
  1025. }
  1026. /**
  1027. * Format a string containing a count of items.
  1028. *
  1029. * This function ensures that the string is pluralized correctly. Since t() is
  1030. * called by this function, make sure not to pass already-localized strings to
  1031. * it.
  1032. *
  1033. * For example:
  1034. * @code
  1035. * $output = format_plural($node->comment_count, '1 comment', '@count comments');
  1036. * @endcode
  1037. *
  1038. * Example with additional replacements:
  1039. * @code
  1040. * $output = format_plural($update_count,
  1041. * 'Changed the content type of 1 post from %old-type to %new-type.',
  1042. * 'Changed the content type of @count posts from %old-type to %new-type.',
  1043. * array('%old-type' => $info->old_type, '%new-type' => $info->new_type)));
  1044. * @endcode
  1045. *
  1046. * @param $count
  1047. * The item count to display.
  1048. * @param $singular
  1049. * The string for the singular case. Please make sure it is clear this is
  1050. * singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
  1051. * Do not use @count in the singular string.
  1052. * @param $plural
  1053. * The string for the plural case. Please make sure it is clear this is plural,
  1054. * to ease translation. Use @count in place of the item count, as in "@count
  1055. * new comments".
  1056. * @param $args
  1057. * An associative array of replacements to make after translation. Incidences
  1058. * of any key in this array are replaced with the corresponding value.
  1059. * Based on the first character of the key, the value is escaped and/or themed:
  1060. * - !variable: inserted as is
  1061. * - @variable: escape plain text to HTML (check_plain)
  1062. * - %variable: escape text and theme as a placeholder for user-submitted
  1063. * content (check_plain + theme_placeholder)
  1064. * Note that you do not need to include @count in this array.
  1065. * This replacement is done automatically for the plural case.
  1066. * @param $langcode
  1067. * Optional language code to translate to a language other than
  1068. * what is used to display the page.
  1069. * @return
  1070. * A translated string.
  1071. */
  1072. function format_plural($count, $singular, $plural, $args = array(), $langcode = NULL) {
  1073. $args['@count'] = $count;
  1074. if ($count == 1) {
  1075. return t($singular, $args, $langcode);
  1076. }
  1077. // Get the plural index through the gettext formula.
  1078. $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, $langcode) : -1;
  1079. // Backwards compatibility.
  1080. if ($index < 0) {
  1081. return t($plural, $args, $langcode);
  1082. }
  1083. else {
  1084. switch ($index) {
  1085. case "0":
  1086. return t($singular, $args, $langcode);
  1087. case "1":
  1088. return t($plural, $args, $langcode);
  1089. default:
  1090. unset($args['@count']);
  1091. $args['@count['. $index .']'] = $count;
  1092. return t(strtr($plural, array('@count' => '@count['. $index .']')), $args, $langcode);
  1093. }
  1094. }
  1095. }
  1096. /**
  1097. * Parse a given byte count.
  1098. *
  1099. * @param $size
  1100. * A size expressed as a number of bytes with optional SI size and unit
  1101. * suffix (e.g. 2, 3K, 5MB, 10G).
  1102. * @return
  1103. * An integer representation of the size.
  1104. */
  1105. function parse_size($size) {
  1106. $suffixes = array(
  1107. '' => 1,
  1108. 'k' => 1024,
  1109. 'm' => 1048576, // 1024 * 1024
  1110. 'g' => 1073741824, // 1024 * 1024 * 1024
  1111. );
  1112. if (preg_match('/([0-9]+)\s*(k|m|g)?(b?(ytes?)?)/i', $size, $match)) {
  1113. return $match[1] * $suffixes[drupal_strtolower($match[2])];
  1114. }
  1115. }
  1116. /**
  1117. * Generate a string representation for the given byte count.
  1118. *
  1119. * @param $size
  1120. * A size in bytes.
  1121. * @param $langcode
  1122. * Optional language code to translate to a language other than what is used
  1123. * to display the page.
  1124. * @return
  1125. * A translated string representation of the size.
  1126. */
  1127. function format_size($size, $langcode = NULL) {
  1128. if ($size < 1024) {
  1129. return format_plural($size, '1 byte', '@count bytes', array(), $langcode);
  1130. }
  1131. else {
  1132. $size = round($size / 1024, 2);
  1133. $suffix = t('KB', array(), $langcode);
  1134. if ($size >= 1024) {
  1135. $size = round($size / 1024, 2);
  1136. $suffix = t('MB', array(), $langcode);
  1137. }
  1138. return t('@size @suffix', array('@size' => $size, '@suffix' => $suffix), $langcode);
  1139. }
  1140. }
  1141. /**
  1142. * Format a time interval with the requested granularity.
  1143. *
  1144. * @param $timestamp
  1145. * The length of the interval in seconds.
  1146. * @param $granularity
  1147. * How many different units to display in the string.
  1148. * @param $langcode
  1149. * Optional language code to translate to a language other than
  1150. * what is used to display the page.
  1151. * @return
  1152. * A translated string representation of the interval.
  1153. */
  1154. function format_interval($timestamp, $granularity = 2, $langcode = NULL) {
  1155. $units = array('1 year|@count years' => 31536000, '1 week|@count weeks' => 604800, '1 day|@count days' => 86400, '1 hour|@count hours' => 3600, '1 min|@count min' => 60, '1 sec|@count sec' => 1);
  1156. $output = '';
  1157. foreach ($units as $key => $value) {
  1158. $key = explode('|', $key);
  1159. if ($timestamp >= $value) {
  1160. $output .= ($output ? ' ' : '') . format_plural(floor($timestamp / $value), $key[0], $key[1], array(), $langcode);
  1161. $timestamp %= $value;
  1162. $granularity--;
  1163. }
  1164. if ($granularity == 0) {
  1165. break;
  1166. }
  1167. }
  1168. return $output ? $output : t('0 sec', array(), $langcode);
  1169. }
  1170. /**
  1171. * Format a date with the given configured format or a custom format string.
  1172. *
  1173. * Drupal allows administrators to select formatting strings for 'small',
  1174. * 'medium' and 'large' date formats. This function can handle these formats,
  1175. * as well as any custom format.
  1176. *
  1177. * @param $timestamp
  1178. * The exact date to format, as a UNIX timestamp.
  1179. * @param $type
  1180. * The format to use. Can be "small", "medium" or "large" for the preconfigured
  1181. * date formats. If "custom" is specified, then $format is required as well.
  1182. * @param $format
  1183. * A PHP date format string as required by date(). A backslash should be used
  1184. * before a character to avoid interpreting the character as part of a date
  1185. * format.
  1186. * @param $timezone
  1187. * Time zone offset in seconds; if omitted, the user's time zone is used.
  1188. * @param $langcode
  1189. * Optional language code to translate to a language other than what is used
  1190. * to display the page.
  1191. * @return
  1192. * A translated date string in the requested format.
  1193. */
  1194. function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
  1195. if (!isset($timezone)) {
  1196. global $user;
  1197. if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
  1198. $timezone = $user->timezone;
  1199. }
  1200. else {
  1201. $timezone = variable_get('date_default_timezone', 0);
  1202. }
  1203. }
  1204. $timestamp += $timezone;
  1205. switch ($type) {
  1206. case 'small':
  1207. $format = variable_get('date_format_short', 'm/d/Y - H:i');
  1208. break;
  1209. case 'large':
  1210. $format = variable_get('date_format_long', 'l, F j, Y - H:i');
  1211. break;
  1212. case 'custom':
  1213. // No change to format.
  1214. break;
  1215. case 'medium':
  1216. default:
  1217. $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
  1218. }
  1219. $max = strlen($format);
  1220. $date = '';
  1221. for ($i = 0; $i < $max; $i++) {
  1222. $c = $format[$i];
  1223. if (strpos('AaDlM', $c) !== FALSE) {
  1224. $date .= t(gmdate($c, $timestamp), array(), $langcode);
  1225. }
  1226. else if ($c == 'F') {
  1227. // Special treatment for long month names: May is both an abbreviation
  1228. // and a full month name in English, but other languages have
  1229. // different abbreviations.
  1230. $date .= trim(t('!long-month-name '. gmdate($c, $timestamp), array('!long-month-name' => ''), $langcode));
  1231. }
  1232. else if (strpos('BdgGhHiIjLmnsStTUwWYyz', $c) !== FALSE) {
  1233. $date .= gmdate($c, $timestamp);
  1234. }
  1235. else if ($c == 'r') {
  1236. $date .= format_date($timestamp - $timezone, 'custom', 'D, d M Y H:i:s O', $timezone, $langcode);
  1237. }
  1238. else if ($c == 'O') {
  1239. $date .= sprintf('%s%02d%02d', ($timezone < 0 ? '-' : '+'), abs($timezone / 3600), abs($timezone % 3600) / 60);
  1240. }
  1241. else if ($c == 'Z') {
  1242. $date .= $timezone;
  1243. }
  1244. else if ($c == '\\') {
  1245. $date .= $format[++$i];
  1246. }
  1247. else {
  1248. $date .= $c;
  1249. }
  1250. }
  1251. return $date;
  1252. }
  1253. /**
  1254. * @} End of "defgroup format".
  1255. */
  1256. /**
  1257. * Generates an internal or external URL.
  1258. *
  1259. * When creating links in modules, consider whether l() could be a better
  1260. * alternative than url().
  1261. *
  1262. * @param $path
  1263. * The internal path or external URL being linked to, such as "node/34" or
  1264. * "http://example.com/foo". A few notes:
  1265. * - If you provide a full URL, it will be considered an external URL.
  1266. * - If you provide only the path (e.g. "node/34"), it will be
  1267. * considered an internal link. In this case, it should be a system URL,
  1268. * and it will be replaced with the alias, if one exists. Additional query
  1269. * arguments for internal paths must be supplied in $options['query'], not
  1270. * included in $path.
  1271. * - If you provide an internal path and $options['alias'] is set to TRUE, the
  1272. * path is assumed already to be the correct path alias, and the alias is
  1273. * not looked up.
  1274. * - The special string '<front>' generates a link to the site's base URL.
  1275. * - If your external URL contains a query (e.g. http://example.com/foo?a=b),
  1276. * then you can either URL encode the query keys and values yourself and
  1277. * include them in $path, or use $options['query'] to let this function
  1278. * URL encode them.
  1279. * @param $options
  1280. * An associative array of additional options, with the following elements:
  1281. * - 'query': A URL-encoded query string to append to the link, or an array of
  1282. * query key/value-pairs without any URL-encoding.
  1283. * - 'fragment': A fragment identifier (named anchor) to append to the URL.
  1284. * Do not include the leading '#' character.
  1285. * - 'absolute' (default FALSE): Whether to force the output to be an absolute
  1286. * link (beginning with http:). Useful for links that will be displayed
  1287. * outside the site, such as in an RSS feed.
  1288. * - 'alias' (default FALSE): Whether the given path is a URL alias already.
  1289. * - 'external': Whether the given path is an external URL.
  1290. * - 'language': An optional language object. Used to build the URL to link
  1291. * to and look up the proper alias for the link.
  1292. * - 'base_url': Only used internally, to modify the base URL when a language
  1293. * dependent URL requires so.
  1294. * - 'prefix': Only used internally, to modify the path when a language
  1295. * dependent URL requires so.
  1296. *
  1297. * @return
  1298. * A string containing a URL to the given path.
  1299. */
  1300. function url($path = NULL, $options = array()) {
  1301. // Merge in defaults.
  1302. $options += array(
  1303. 'fragment' => '',
  1304. 'query' => '',
  1305. 'absolute' => FALSE,
  1306. 'alias' => FALSE,
  1307. 'prefix' => ''
  1308. );
  1309. if (!isset($options['external'])) {
  1310. // Return an external link if $path contains an allowed absolute URL.
  1311. // Only call the slow filter_xss_bad_protocol if $path contains a ':' before
  1312. // any / ? or #.
  1313. $colonpos = strpos($path, ':');
  1314. $options['external'] = ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && filter_xss_bad_protocol($path, FALSE) == check_plain($path));
  1315. }
  1316. // May need language dependent rewriting if language.inc is present.
  1317. if (function_exists('language_url_rewrite')) {
  1318. language_url_rewrite($path, $options);
  1319. }
  1320. if ($options['fragment']) {
  1321. $options['fragment'] = '#'. $options['fragment'];
  1322. }
  1323. if (is_array($options['query'])) {
  1324. $options['query'] = drupal_query_string_encode($options['query']);
  1325. }
  1326. if ($options['external']) {
  1327. // Split off the fragment.
  1328. if (strpos($path, '#') !== FALSE) {
  1329. list($path, $old_fragment) = explode('#', $path, 2);
  1330. if (isset($old_fragment) && !$options['fragment']) {
  1331. $options['fragment'] = '#'. $old_fragment;
  1332. }
  1333. }
  1334. // Append the query.
  1335. if ($options['query']) {
  1336. $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . $options['query'];
  1337. }
  1338. // Reassemble.
  1339. return $path . $options['fragment'];
  1340. }
  1341. global $base_url;
  1342. static $script;
  1343. if (!isset($script)) {
  1344. // On some web servers, such as IIS, we can't omit "index.php". So, we
  1345. // generate "index.php?q=foo" instead of "?q=foo" on anything that is not
  1346. // Apache.
  1347. $script = (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') === FALSE) ? 'index.php' : '';
  1348. }
  1349. if (!isset($options['base_url'])) {
  1350. // The base_url might be rewritten from the language rewrite in domain mode.
  1351. $options['base_url'] = $base_url;
  1352. }
  1353. // Preserve the original path before aliasing.
  1354. $original_path = $path;
  1355. // The special path '<front>' links to the default front page.
  1356. if ($path == '<front>') {
  1357. $path = '';
  1358. }
  1359. elseif (!empty($path) && !$options['alias']) {
  1360. $path = drupal_get_path_alias($path, isset($options['language']) ? $options['language']->language : '');
  1361. }
  1362. if (function_exists('custom_url_rewrite_outbound')) {
  1363. // Modules may alter outbound links by reference.
  1364. custom_url_rewrite_outbound($path, $options, $original_path);
  1365. }
  1366. $base = $options['absolute'] ? $options['base_url'] .'/' : base_path();
  1367. $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
  1368. $path = drupal_urlencode($prefix . $path);
  1369. if (variable_get('clean_url', '0')) {
  1370. // With Clean URLs.
  1371. if ($options['query']) {
  1372. return $base . $path .'?'. $options['query'] . $options['fragment'];
  1373. }
  1374. else {
  1375. return $base . $path . $options['fragment'];
  1376. }
  1377. }
  1378. else {
  1379. // Without Clean URLs.
  1380. $variables = array();
  1381. if (!empty($path)) {
  1382. $variables[] = 'q='. $path;
  1383. }
  1384. if (!empty($options['query'])) {
  1385. $variables[] = $options['query'];
  1386. }
  1387. if ($query = join('&', $variables)) {
  1388. return $base . $script .'?'. $query . $options['fragment'];
  1389. }
  1390. else {
  1391. return $base . $options['fragment'];
  1392. }
  1393. }
  1394. }
  1395. /**
  1396. * Format an attribute string to insert in a tag.
  1397. *
  1398. * @param $attributes
  1399. * An associative array of HTML attributes.
  1400. * @return
  1401. * An HTML string ready for insertion in a tag.
  1402. */
  1403. function drupal_attributes($attributes = array()) {
  1404. if (is_array($attributes)) {
  1405. $t = '';
  1406. foreach ($attributes as $key => $value) {
  1407. $t .= " $key=".'"'. check_plain($value) .'"';
  1408. }
  1409. return $t;
  1410. }
  1411. }
  1412. /**
  1413. * Formats an internal or external URL link as an HTML anchor tag.
  1414. *
  1415. * This function correctly handles aliased paths, and adds an 'active' class
  1416. * attribute to links that point to the current page (for theming), so all
  1417. * internal links output by modules should be generated by this function if
  1418. * possible.
  1419. *
  1420. * @param $text
  1421. * The link text for the anchor tag.
  1422. * @param $path
  1423. * The internal path or external URL being linked to, such as "node/34" or
  1424. * "http://example.com/foo". After the url() function is called to construct
  1425. * the URL from $path and $options, the resulting URL is passed through
  1426. * check_url() before it is inserted into the HTML anchor tag, to ensure
  1427. * well-formed HTML. See url() for more information and notes.
  1428. * @param $options
  1429. * An associative array of additional options, with the following elements:
  1430. * - 'attributes': An associative array of HTML attributes to apply to the
  1431. * anchor tag.
  1432. * - 'html' (default FALSE): Whether $text is HTML or just plain-text. For
  1433. * example, to make an image tag into a link, this must be set to TRUE, or
  1434. * you will see the escaped HTML image tag.
  1435. * - 'language': An optional language object. If the path being linked to is
  1436. * internal to the site, $options['language'] is used to look up the alias
  1437. * for the URL, and to determine whether the link is "active", or pointing
  1438. * to the current page (the language as well as the path must match).This
  1439. * element is also used by url().
  1440. * - Additional $options elements used by the url() function.
  1441. *
  1442. * @return
  1443. * An HTML string containing a link to the given path.
  1444. */
  1445. function l($text, $path, $options = array()) {
  1446. global $language;
  1447. // Merge in defaults.
  1448. $options += array(
  1449. 'attributes' => array(),
  1450. 'html' => FALSE,
  1451. );
  1452. // Append active class.
  1453. if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
  1454. (empty($options['language']) || $options['language']->language == $language->language)) {
  1455. if (isset($options['attributes']['class'])) {
  1456. $options['attributes']['class'] .= ' active';
  1457. }
  1458. else {
  1459. $options['attributes']['class'] = 'active';
  1460. }
  1461. }
  1462. // Remove all HTML and PHP tags from a tooltip. For best performance, we act only
  1463. // if a quick strpos() pre-check gave a suspicion (because strip_tags() is expensive).
  1464. if (isset($options['attributes']['title']) && strpos($options['attributes']['title'], '<') !== FALSE) {
  1465. $options['attributes']['title'] = strip_tags($options['attributes']['title']);
  1466. }
  1467. return '<a href="'. check_url(url($path, $options)) .'"'. drupal_attributes($options['attributes']) .'>'. ($options['html'] ? $text : check_plain($text)) .'</a>';
  1468. }
  1469. /**
  1470. * Perform end-of-request tasks.
  1471. *
  1472. * This function sets the page cache if appropriate, and allows modules to
  1473. * react to the closing of the page by calling hook_exit().
  1474. */
  1475. function drupal_page_footer() {
  1476. if (variable_get('cache', CACHE_DISABLED) != CACHE_DISABLED) {
  1477. page_set_cache();
  1478. }
  1479. module_invoke_all('exit');
  1480. }
  1481. /**
  1482. * Form an associative array from a linear array.
  1483. *
  1484. * This function walks through the provided array and constructs an associative
  1485. * array out of it. The keys of the resulting array will be the values of the
  1486. * input array. The values will be the same as the keys unless a function is
  1487. * specified, in which case the output of the function is used for the values
  1488. * instead.
  1489. *
  1490. * @param $array
  1491. * A linear array.
  1492. * @param $function
  1493. * A name of a function to apply to all values before output.
  1494. *
  1495. * @return
  1496. * An associative array.
  1497. */
  1498. function drupal_map_assoc($array, $function = NULL) {
  1499. if (!isset($function)) {
  1500. $result = array();
  1501. foreach ($array as $value) {
  1502. $result[$value] = $value;
  1503. }
  1504. return $result;
  1505. }
  1506. elseif (function_exists($function)) {
  1507. $result = array();
  1508. foreach ($array as $value) {
  1509. $result[$value] = $function($value);
  1510. }
  1511. return $result;
  1512. }
  1513. }
  1514. /**
  1515. * Evaluate a string of PHP code.
  1516. *
  1517. * This is a wrapper around PHP's eval(). It uses output buffering to capture both
  1518. * returned and printed text. Unlike eval(), we require code to be surrounded by
  1519. * <?php ?> tags; in other words, we evaluate the code as if it were a stand-alone
  1520. * PHP file.
  1521. *
  1522. * Using this wrapper also ensures that the PHP code which is evaluated can not
  1523. * overwrite any variables in the calling code, unlike a regular eval() call.
  1524. *
  1525. * @param $code
  1526. * The code to evaluate.
  1527. * @return
  1528. * A string containing the printed output of the code, followed by the returned
  1529. * output of the code.
  1530. */
  1531. function drupal_eval($code) {
  1532. global $theme_path, $theme_info, $conf;
  1533. // Store current theme path.
  1534. $old_theme_path = $theme_path;
  1535. // Restore theme_path to the theme, as long as drupal_eval() executes,
  1536. // so code evaluted will not see the caller module as the current theme.
  1537. // If theme info is not initialized get the path from theme_default.
  1538. if (!isset($theme_info)) {
  1539. $theme_path = drupal_get_path('theme', $conf['theme_default']);
  1540. }
  1541. else {
  1542. $theme_path = dirname($theme_info->filename);
  1543. }
  1544. ob_start();
  1545. print eval('?>'. $code);
  1546. $output = ob_get_contents();
  1547. ob_end_clean();
  1548. // Recover original theme path.
  1549. $theme_path = $old_theme_path;
  1550. return $output;
  1551. }
  1552. /**
  1553. * Returns the path to a system item (module, theme, etc.).
  1554. *
  1555. * @param $type
  1556. * The type of the item (i.e. theme, theme_engine, module, profile).
  1557. * @param $name
  1558. * The name of the item for which the path is requested.
  1559. *
  1560. * @return
  1561. * The path to the requested item.
  1562. */
  1563. function drupal_get_path($type, $name) {
  1564. return dirname(drupal_get_filename($type, $name));
  1565. }
  1566. /**
  1567. * Returns the base URL path of the Drupal installation.
  1568. * At the very least, this will always default to /.
  1569. */
  1570. function base_path() {
  1571. return $GLOBALS['base_path'];
  1572. }
  1573. /**
  1574. * Provide a substitute clone() function for PHP4.
  1575. */
  1576. function drupal_clone($object) {
  1577. return version_compare(phpversion(), '5.0') < 0 ? $object : clone($object);
  1578. }
  1579. /**
  1580. * Add a <link> tag to the page's HEAD.
  1581. */
  1582. function drupal_add_link($attributes) {
  1583. drupal_set_html_head('<link'. drupal_attributes($attributes) .' />');
  1584. }
  1585. /**
  1586. * Adds a CSS file to the stylesheet queue.
  1587. *
  1588. * @param $path
  1589. * (optional) The path to the CSS file relative to the base_path(), e.g.,
  1590. * modules/devel/devel.css.
  1591. *
  1592. * Modules should always prefix the names of their CSS files with the module
  1593. * name, for example: system-menus.css rather than simply menus.css. Themes
  1594. * can override module-supplied CSS files based on their filenames, and this
  1595. * prefixing helps prevent confusing name collisions for theme developers.
  1596. * See drupal_get_css where the overrides are performed.
  1597. *
  1598. * If the direction of the current language is right-to-left (Hebrew,
  1599. * Arabic, etc.), the function will also look for an RTL CSS file and append
  1600. * it to the list. The name of this file should have an '-rtl.css' suffix.
  1601. * For example a CSS file called 'name.css' will have a 'name-rtl.css'
  1602. * file added to the list, if exists in the same directory. This CSS file
  1603. * should contain overrides for properties which should be reversed or
  1604. * otherwise different in a right-to-left display.
  1605. * @param $type
  1606. * (optional) The type of stylesheet that is being added. Types are: module
  1607. * or theme.
  1608. * @param $media
  1609. * (optional) The media type for the stylesheet, e.g., all, print, screen.
  1610. * @param $preprocess
  1611. * (optional) Should this CSS file be aggregated and compressed if this
  1612. * feature has been turned on under the performance section?
  1613. *
  1614. * What does this actually mean?
  1615. * CSS preprocessing is the process of aggregating a bunch of separate CSS
  1616. * files into one file that is then compressed by removing all extraneous
  1617. * white space.
  1618. *
  1619. * The reason for merging the CSS files is outlined quite thoroughly here:
  1620. * http://www.die.net/musings/page_load_time/
  1621. * "Load fewer external objects. Due to request overhead, one bigger file
  1622. * just loads faster than two smaller ones half its size."
  1623. *
  1624. * However, you should *not* preprocess every file as this can lead to
  1625. * redundant caches. You should set $preprocess = FALSE when:
  1626. *
  1627. * - Your styles are only used rarely on the site. This could be a special
  1628. * admin page, the homepage, or a handful of pages that does not represent
  1629. * the majority of the pages on your site.
  1630. *
  1631. * Typical candidates for caching are for example styles for nodes across
  1632. * the site, or used in the theme.
  1633. *
  1634. * @return
  1635. * An array of CSS files.
  1636. *
  1637. * @see drupal_get_css()
  1638. */
  1639. function drupal_add_css($path = NULL, $type = 'module', $media = 'all', $preprocess = TRUE) {
  1640. static $css = array();
  1641. global $language;
  1642. // Create an array of CSS files for each media type first, since each type needs to be served
  1643. // to the browser differently.
  1644. if (isset($path)) {
  1645. // This check is necessary to ensure proper cascading of styles and is faster than an asort().
  1646. if (!isset($css[$media])) {
  1647. $css[$media] = array('module' => array(), 'theme' => array());
  1648. }
  1649. $css[$media][$type][$path] = $preprocess;
  1650. // If the current language is RTL, add the CSS file with RTL overrides.
  1651. if ($language->direction == LANGUAGE_RTL) {
  1652. $rtl_path = str_replace('.css', '-rtl.css', $path);
  1653. if (file_exists($rtl_path)) {
  1654. $css[$media][$type][$rtl_path] = $preprocess;
  1655. }
  1656. }
  1657. }
  1658. return $css;
  1659. }
  1660. /**
  1661. * Returns a themed representation of all stylesheets that should be attached to the page.
  1662. *
  1663. * It loads the CSS in order, with 'module' first, then 'theme' afterwards.
  1664. * This ensures proper cascading of styles so themes can easily override
  1665. * module styles through CSS selectors.
  1666. *
  1667. * Themes may replace module-defined CSS files by adding a stylesheet with the
  1668. * same filename. For example, themes/garland/system-menus.css would replace
  1669. * modules/system/system-menus.css. This allows themes to override complete
  1670. * CSS files, rather than specific selectors, when necessary.
  1671. *
  1672. * If the original CSS file is being overridden by a theme, the theme is
  1673. * responsible for supplying an accompanying RTL CSS file to replace the
  1674. * module's.
  1675. *
  1676. * @param $css
  1677. * (optional) An array of CSS files. If no array is provided, the default
  1678. * stylesheets array is used instead.
  1679. *
  1680. * @return
  1681. * A string of XHTML CSS tags.
  1682. *
  1683. * @see drupal_add_css()
  1684. */
  1685. function drupal_get_css($css = NULL) {
  1686. $output = '';
  1687. if (!isset($css)) {
  1688. $css = drupal_add_css();
  1689. }
  1690. $no_module_preprocess = '';
  1691. $no_theme_preprocess = '';
  1692. $preprocess_css = (variable_get('preprocess_css', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
  1693. $directory = file_directory_path();
  1694. $is_writable = is_dir($directory) && is_writable($directory) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC);
  1695. // A dummy query-string is added to filenames, to gain control over
  1696. // browser-caching. The string changes on every update or full cache
  1697. // flush, forcing browsers to load a new copy of the files, as the
  1698. // URL changed.
  1699. $query_string = '?'. substr(variable_get('css_js_query_string', '0'), 0, 1);
  1700. foreach ($css as $media => $types) {
  1701. // If CSS preprocessing is off, we still need to output the styles.
  1702. // Additionally, go through any remaining styles if CSS preprocessing is on and output the non-cached ones.
  1703. foreach ($types as $type => $files) {
  1704. if ($type == 'module') {
  1705. // Setup theme overrides for module styles.
  1706. $theme_styles = array();
  1707. foreach (array_keys($css[$media]['theme']) as $theme_style) {
  1708. $theme_styles[] = basename($theme_style);
  1709. }
  1710. }
  1711. foreach ($types[$type] as $file => $preprocess) {
  1712. // If the theme supplies its own style using the name of the module style, skip its inclusion.
  1713. // This includes any RTL styles associated with its main LTR counterpart.
  1714. if ($type == 'module' && in_array(str_replace('-rtl.css', '.css', basename($file)), $theme_styles)) {
  1715. // Unset the file to prevent its inclusion when CSS aggregation is enabled.
  1716. unset($types[$type][$file]);
  1717. continue;
  1718. }
  1719. // Only include the stylesheet if it exists.
  1720. if (file_exists($file)) {
  1721. if (!$preprocess || !($is_writable && $preprocess_css)) {
  1722. // If a CSS file is not to be preprocessed and it's a module CSS file, it needs to *always* appear at the *top*,
  1723. // regardless of whether preprocessing is on or off.
  1724. if (!$preprocess && $type == 'module') {
  1725. $no_module_preprocess .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. base_path() . $file . $query_string .'" />'."\n";
  1726. }
  1727. // If a CSS file is not to be preprocessed and it's a theme CSS file, it needs to *always* appear at the *bottom*,
  1728. // regardless of whether preprocessing is on or off.
  1729. else if (!$preprocess && $type == 'theme') {
  1730. $no_theme_preprocess .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. base_path() . $file . $query_string .'" />'."\n";
  1731. }
  1732. else {
  1733. $output .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. base_path() . $file . $query_string .'" />'."\n";
  1734. }
  1735. }
  1736. }
  1737. }
  1738. }
  1739. if ($is_writable && $preprocess_css) {
  1740. // Prefix filename to prevent blocking by firewalls which reject files
  1741. // starting with "ad*".
  1742. $filename = 'css_'. md5(serialize($types) . $query_string) .'.css';
  1743. $preprocess_file = drupal_build_css_cache($types, $filename);
  1744. $output .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. base_path() . $preprocess_file .'" />'."\n";
  1745. }
  1746. }
  1747. return $no_module_preprocess . $output . $no_theme_preprocess;
  1748. }
  1749. /**
  1750. * Aggregate and optimize CSS files, putting them in the files directory.
  1751. *
  1752. * @param $types
  1753. * An array of types of CSS files (e.g., screen, print) to aggregate and
  1754. * compress into one file.
  1755. * @param $filename
  1756. * The name of the aggregate CSS file.
  1757. * @return
  1758. * The name of the CSS file.
  1759. */
  1760. function drupal_build_css_cache($types, $filename) {
  1761. $data = '';
  1762. // Create the css/ within the files folder.
  1763. $csspath = file_create_path('css');
  1764. file_check_directory($csspath, FILE_CREATE_DIRECTORY);
  1765. if (!file_exists($csspath .'/'. $filename)) {
  1766. // Build aggregate CSS file.
  1767. foreach ($types as $type) {
  1768. foreach ($type as $file => $cache) {
  1769. if ($cache) {
  1770. $contents = drupal_load_stylesheet($file, TRUE);
  1771. // Return the path to where this CSS file originated from.
  1772. $base = base_path() . dirname($file) .'/';
  1773. _drupal_build_css_path(NULL, $base);
  1774. // Prefix all paths within this CSS file, ignoring external and absolute paths.
  1775. $data .= preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', '_drupal_build_css_path', $contents);
  1776. }
  1777. }
  1778. }
  1779. // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
  1780. // @import rules must proceed any other style, so we move those to the top.
  1781. $regexp = '/@import[^;]+;/i';
  1782. preg_match_all($regexp, $data, $matches);
  1783. $data = preg_replace($regexp, '', $data);
  1784. $data = implode('', $matches[0]) . $data;
  1785. // Create the CSS file.
  1786. file_save_data($data, $csspath .'/'. $filename, FILE_EXISTS_REPLACE);
  1787. }
  1788. return $csspath .'/'. $filename;
  1789. }
  1790. /**
  1791. * Helper function for drupal_build_css_cache().
  1792. *
  1793. * This function will prefix all paths within a CSS file.
  1794. */
  1795. function _drupal_build_css_path($matches, $base = NULL) {
  1796. static $_base;
  1797. // Store base path for preg_replace_callback.
  1798. if (isset($base)) {
  1799. $_base = $base;
  1800. }
  1801. // Prefix with base and remove '../' segments where possible.
  1802. $path = $_base . $matches[1];
  1803. $last = '';
  1804. while ($path != $last) {
  1805. $last = $path;
  1806. $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
  1807. }
  1808. return 'url('. $path .')';
  1809. }
  1810. /**
  1811. * Loads the stylesheet and resolves all @import commands.
  1812. *
  1813. * Loads a stylesheet and replaces @import commands with the contents of the
  1814. * imported file. Use this instead of file_get_contents when processing
  1815. * stylesheets.
  1816. *
  1817. * The returned contents are compressed removing white space and comments only
  1818. * when CSS aggregation is enabled. This optimization will not apply for
  1819. * color.module enabled themes with CSS aggregation turned off.
  1820. *
  1821. * @param $file
  1822. * Name of the stylesheet to be processed.
  1823. * @param $optimize
  1824. * Defines if CSS contents should be compressed or not.
  1825. * @return
  1826. * Contents of the stylesheet including the imported stylesheets.
  1827. */
  1828. function drupal_load_stylesheet($file, $optimize = NULL) {
  1829. static $_optimize;
  1830. // Store optimization parameter for preg_replace_callback with nested @import loops.
  1831. if (isset($optimize)) {
  1832. $_optimize = $optimize;
  1833. }
  1834. $contents = '';
  1835. if (file_exists($file)) {
  1836. // Load the local CSS stylesheet.
  1837. $contents = file_get_contents($file);
  1838. // Change to the current stylesheet's directory.
  1839. $cwd = getcwd();
  1840. chdir(dirname($file));
  1841. // Replaces @import commands with the actual stylesheet content.
  1842. // This happens recursively but omits external files.
  1843. $contents = preg_replace_callback('/@import\s*(?:url\()?[\'"]?(?![a-z]+:)([^\'"\()]+)[\'"]?\)?;/', '_drupal_load_stylesheet', $contents);
  1844. // Remove multiple charset declarations for standards compliance (and fixing Safari problems).
  1845. $contents = preg_replace('/^@charset\s+[\'"](\S*)\b[\'"];/i', '', $contents);
  1846. if ($_optimize) {
  1847. // Perform some safe CSS optimizations.
  1848. // Regexp to match comment blocks.
  1849. $comment = '/\*[^*]*\*+(?:[^/*][^*]*\*+)*/';
  1850. // Regexp to match double quoted strings.
  1851. $double_quot = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
  1852. // Regexp to match single quoted strings.
  1853. $single_quot = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'";
  1854. $contents = preg_replace_callback(
  1855. "<$double_quot|$single_quot|$comment>Ss", // Match all comment blocks along
  1856. "_process_comment", // with double/single quoted strings
  1857. $contents); // and feed them to _process_comment().
  1858. $contents = preg_replace(
  1859. '<\s*([@{}:;,]|\)\s|\s\()\s*>S', // Remove whitespace around separators,
  1860. '\1', $contents); // but keep space around parentheses.
  1861. // End the file with a new line.
  1862. $contents .= "\n";
  1863. }
  1864. // Change back directory.
  1865. chdir($cwd);
  1866. }
  1867. return $contents;
  1868. }
  1869. /**
  1870. * Process comment blocks.
  1871. *
  1872. * This is the callback function for the preg_replace_callback()
  1873. * used in drupal_load_stylesheet_content(). Support for comment
  1874. * hacks is implemented here.
  1875. */
  1876. function _process_comment($matches) {
  1877. static $keep_nextone = FALSE;
  1878. // Quoted string, keep it.
  1879. if ($matches[0][0] == "'" || $matches[0][0] == '"') {
  1880. return $matches[0];
  1881. }
  1882. // End of IE-Mac hack, keep it.
  1883. if ($keep_nextone) {
  1884. $keep_nextone = FALSE;
  1885. return $matches[0];
  1886. }
  1887. switch (strrpos($matches[0], '\\')) {
  1888. case FALSE :
  1889. // No backslash, strip it.
  1890. return '';
  1891. case drupal_strlen($matches[0])-3 :
  1892. // Ends with \*/ so is a multi line IE-Mac hack, keep the next one also.
  1893. $keep_nextone = TRUE;
  1894. return '/*_\*/';
  1895. default :
  1896. // Single line IE-Mac hack.
  1897. return '/*\_*/';
  1898. }
  1899. }
  1900. /**
  1901. * Loads stylesheets recursively and returns contents with corrected paths.
  1902. *
  1903. * This function is used for recursive loading of stylesheets and
  1904. * returns the stylesheet content with all url() paths corrected.
  1905. */
  1906. function _drupal_load_stylesheet($matches) {
  1907. $filename = $matches[1];
  1908. // Load the imported stylesheet and replace @import commands in there as well.
  1909. $file = drupal_load_stylesheet($filename);
  1910. // Determine the file's directory.
  1911. $directory = dirname($filename);
  1912. // If the file is in the current directory, make sure '.' doesn't appear in
  1913. // the url() path.
  1914. $directory = $directory == '.' ? '' : $directory .'/';
  1915. // Alter all internal url() paths. Leave external paths alone. We don't need
  1916. // to normalize absolute paths here (i.e. remove folder/... segments) because
  1917. // that will be done later.
  1918. return preg_replace('/url\s*\(([\'"]?)(?![a-z]+:|\/+)/i', 'url(\1'. $directory, $file);
  1919. }
  1920. /**
  1921. * Delete all cached CSS files.
  1922. */
  1923. function drupal_clear_css_cache() {
  1924. file_scan_directory(file_create_path('css'), '.*', array('.', '..', 'CVS'), 'file_delete', TRUE);
  1925. }
  1926. /**
  1927. * Add a JavaScript file, setting or inline code to the page.
  1928. *
  1929. * The behavior of this function depends on the parameters it is called with.
  1930. * Generally, it handles the addition of JavaScript to the page, either as
  1931. * reference to an existing file or as inline code. The following actions can be
  1932. * performed using this function:
  1933. *
  1934. * - Add a file ('core', 'module' and 'theme'):
  1935. * Adds a reference to a JavaScript file to the page. JavaScript files
  1936. * are placed in a certain order, from 'core' first, to 'module' and finally
  1937. * 'theme' so that files, that are added later, can override previously added
  1938. * files with ease.
  1939. *
  1940. * - Add inline JavaScript code ('inline'):
  1941. * Executes a piece of JavaScript code on the current page by placing the code
  1942. * directly in the page. This can, for example, be useful to tell the user that
  1943. * a new message arrived, by opening a pop up, alert box etc.
  1944. *
  1945. * - Add settings ('setting'):
  1946. * Adds a setting to Drupal's global storage of JavaScript settings. Per-page
  1947. * settings are required by some modules to function properly. The settings
  1948. * will be accessible at Drupal.settings.
  1949. *
  1950. * @param $data
  1951. * (optional) If given, the value depends on the $type parameter:
  1952. * - 'core', 'module' or 'theme': Path to the file relative to base_path().
  1953. * - 'inline': The JavaScript code that should be placed in the given scope.
  1954. * - 'setting': An array with configuration options as associative array. The
  1955. * array is directly placed in Drupal.settings. You might want to wrap your
  1956. * actual configuration settings in another variable to prevent the pollution
  1957. * of the Drupal.settings namespace.
  1958. * @param $type
  1959. * (optional) The type of JavaScript that should be added to the page. Allowed
  1960. * values are 'core', 'module', 'theme', 'inline' and 'setting'. You
  1961. * can, however, specify any value. It is treated as a reference to a JavaScript
  1962. * file. Defaults to 'module'.
  1963. * @param $scope
  1964. * (optional) The location in which you want to place the script. Possible
  1965. * values are 'header' and 'footer' by default. If your theme implements
  1966. * different locations, however, you can also use these.
  1967. * @param $defer
  1968. * (optional) If set to TRUE, the defer attribute is set on the <script> tag.
  1969. * Defaults to FALSE. This parameter is not used with $type == 'setting'.
  1970. * @param $cache
  1971. * (optional) If set to FALSE, the JavaScript file is loaded anew on every page
  1972. * call, that means, it is not cached. Defaults to TRUE. Used only when $type
  1973. * references a JavaScript file.
  1974. * @param $preprocess
  1975. * (optional) Should this JS file be aggregated if this
  1976. * feature has been turned on under the performance section?
  1977. * @return
  1978. * If the first parameter is NULL, the JavaScript array that has been built so
  1979. * far for $scope is returned. If the first three parameters are NULL,
  1980. * an array with all scopes is returned.
  1981. */
  1982. function drupal_add_js($data = NULL, $type = 'module', $scope = 'header', $defer = FALSE, $cache = TRUE, $preprocess = TRUE) {
  1983. static $javascript = array();
  1984. if (isset($data)) {
  1985. // Add jquery.js and drupal.js, as well as the basePath setting, the
  1986. // first time a Javascript file is added.
  1987. if (empty($javascript)) {
  1988. $javascript['header'] = array(
  1989. 'core' => array(
  1990. 'misc/jquery.js' => array('cache' => TRUE, 'defer' => FALSE, 'preprocess' => TRUE),
  1991. 'misc/drupal.js' => array('cache' => TRUE, 'defer' => FALSE, 'preprocess' => TRUE),
  1992. ),
  1993. 'module' => array(),
  1994. 'theme' => array(),
  1995. 'setting' => array(
  1996. array('basePath' => base_path()),
  1997. ),
  1998. 'inline' => array(),
  1999. );
  2000. }
  2001. if (isset($scope) && !isset($javascript[$scope])) {
  2002. $javascript[$scope] = array('core' => array(), 'module' => array(), 'theme' => array(), 'setting' => array(), 'inline' => array());
  2003. }
  2004. if (isset($type) && isset($scope) && !isset($javascript[$scope][$type])) {
  2005. $javascript[$scope][$type] = array();
  2006. }
  2007. switch ($type) {
  2008. case 'setting':
  2009. $javascript[$scope][$type][] = $data;
  2010. break;
  2011. case 'inline':
  2012. $javascript[$scope][$type][] = array('code' => $data, 'defer' => $defer);
  2013. break;
  2014. default:
  2015. // If cache is FALSE, don't preprocess the JS file.
  2016. $javascript[$scope][$type][$data] = array('cache' => $cache, 'defer' => $defer, 'preprocess' => (!$cache ? FALSE : $preprocess));
  2017. }
  2018. }
  2019. if (isset($scope)) {
  2020. if (isset($javascript[$scope])) {
  2021. return $javascript[$scope];
  2022. }
  2023. else {
  2024. return array();
  2025. }
  2026. }
  2027. else {
  2028. return $javascript;
  2029. }
  2030. }
  2031. /**
  2032. * Returns a themed presentation of all JavaScript code for the current page.
  2033. *
  2034. * References to JavaScript files are placed in a certain order: first, all
  2035. * 'core' files, then all 'module' and finally all 'theme' JavaScript files
  2036. * are added to the page. Then, all settings are output, followed by 'inline'
  2037. * JavaScript code. If running update.php, all preprocessing is disabled.
  2038. *
  2039. * @param $scope
  2040. * (optional) The scope for which the JavaScript rules should be returned.
  2041. * Defaults to 'header'.
  2042. * @param $javascript
  2043. * (optional) An array with all JavaScript code. Defaults to the default
  2044. * JavaScript array for the given scope.
  2045. * @return
  2046. * All JavaScript code segments and includes for the scope as HTML tags.
  2047. */
  2048. function drupal_get_js($scope = 'header', $javascript = NULL) {
  2049. if ((!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') && function_exists('locale_update_js_files')) {
  2050. locale_update_js_files();
  2051. }
  2052. if (!isset($javascript)) {
  2053. $javascript = drupal_add_js(NULL, NULL, $scope);
  2054. }
  2055. if (empty($javascript)) {
  2056. return '';
  2057. }
  2058. $output = '';
  2059. $preprocessed = '';
  2060. $no_preprocess = array('core' => '', 'module' => '', 'theme' => '');
  2061. $files = array();
  2062. $preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
  2063. $directory = file_directory_path();
  2064. $is_writable = is_dir($directory) && is_writable($directory) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC);
  2065. // A dummy query-string is added to filenames, to gain control over
  2066. // browser-caching. The string changes on every update or full cache
  2067. // flush, forcing browsers to load a new copy of the files, as the
  2068. // URL changed. Files that should not be cached (see drupal_add_js())
  2069. // get time() as query-string instead, to enforce reload on every
  2070. // page request.
  2071. $query_string = '?'. substr(variable_get('css_js_query_string', '0'), 0, 1);
  2072. // For inline Javascript to validate as XHTML, all Javascript containing
  2073. // XHTML needs to be wrapped in CDATA. To make that backwards compatible
  2074. // with HTML 4, we need to comment out the CDATA-tag.
  2075. $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
  2076. $embed_suffix = "\n//--><!]]>\n";
  2077. foreach ($javascript as $type => $data) {
  2078. if (!$data) continue;
  2079. switch ($type) {
  2080. case 'setting':
  2081. $output .= '<script type="text/javascript">' . $embed_prefix . 'jQuery.extend(Drupal.settings, ' . drupal_to_js(call_user_func_array('array_merge_recursive', $data)) . ");" . $embed_suffix . "</script>\n";
  2082. break;
  2083. case 'inline':
  2084. foreach ($data as $info) {
  2085. $output .= '<script type="text/javascript"' . ($info['defer'] ? ' defer="defer"' : '') . '>' . $embed_prefix . $info['code'] . $embed_suffix . "</script>\n";
  2086. }
  2087. break;
  2088. default:
  2089. // If JS preprocessing is off, we still need to output the scripts.
  2090. // Additionally, go through any remaining scripts if JS preprocessing is on and output the non-cached ones.
  2091. foreach ($data as $path => $info) {
  2092. if (!$info['preprocess'] || !$is_writable || !$preprocess_js) {
  2093. $no_preprocess[$type] .= '<script type="text/javascript"'. ($info['defer'] ? ' defer="defer"' : '') .' src="'. base_path() . $path . ($info['cache'] ? $query_string : '?'. time()) ."\"></script>\n";
  2094. }
  2095. else {
  2096. $files[$path] = $info;
  2097. }
  2098. }
  2099. }
  2100. }
  2101. // Aggregate any remaining JS files that haven't already been output.
  2102. if ($is_writable && $preprocess_js && count($files) > 0) {
  2103. // Prefix filename to prevent blocking by firewalls which reject files
  2104. // starting with "ad*".
  2105. $filename = 'js_'. md5(serialize($files) . $query_string) .'.js';
  2106. $preprocess_file = drupal_build_js_cache($files, $filename);
  2107. $preprocessed .= '<script type="text/javascript" src="'. base_path() . $preprocess_file .'"></script>'."\n";
  2108. }
  2109. // Keep the order of JS files consistent as some are preprocessed and others are not.
  2110. // Make sure any inline or JS setting variables appear last after libraries have loaded.
  2111. $output = $preprocessed . implode('', $no_preprocess) . $output;
  2112. return $output;
  2113. }
  2114. /**
  2115. * Assist in adding the tableDrag JavaScript behavior to a themed table.
  2116. *
  2117. * Draggable tables should be used wherever an outline or list of sortable items
  2118. * needs to be arranged by an end-user. Draggable tables are very flexible and
  2119. * can manipulate the value of form elements placed within individual columns.
  2120. *
  2121. * To set up a table to use drag and drop in place of weight select-lists or
  2122. * in place of a form that contains parent relationships, the form must be
  2123. * themed into a table. The table must have an id attribute set. If using
  2124. * theme_table(), the id may be set as such:
  2125. * @code
  2126. * $output = theme('table', $header, $rows, array('id' => 'my-module-table'));
  2127. * return $output;
  2128. * @endcode
  2129. *
  2130. * In the theme function for the form, a special class must be added to each
  2131. * form element within the same column, "grouping" them together.
  2132. *
  2133. * In a situation where a single weight column is being sorted in the table, the
  2134. * classes could be added like this (in the theme function):
  2135. * @code
  2136. * $form['my_elements'][$delta]['weight']['#attributes']['class'] = "my-elements-weight";
  2137. * @endcode
  2138. *
  2139. * Each row of the table must also have a class of "draggable" in order to enable the
  2140. * drag handles:
  2141. * @code
  2142. * $row = array(...);
  2143. * $rows[] = array(
  2144. * 'data' => $row,
  2145. * 'class' => 'draggable',
  2146. * );
  2147. * @endcode
  2148. *
  2149. * When tree relationships are present, the two additional classes
  2150. * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
  2151. * - Rows with the 'tabledrag-leaf' class cannot have child rows.
  2152. * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
  2153. *
  2154. * Calling drupal_add_tabledrag() would then be written as such:
  2155. * @code
  2156. * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
  2157. * @endcode
  2158. *
  2159. * In a more complex case where there are several groups in one column (such as
  2160. * the block regions on the admin/build/block page), a separate subgroup class
  2161. * must also be added to differentiate the groups.
  2162. * @code
  2163. * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = "my-elements-weight my-elements-weight-". $region;
  2164. * @endcode
  2165. *
  2166. * $group is still 'my-element-weight', and the additional $subgroup variable
  2167. * will be passed in as 'my-elements-weight-'. $region. This also means that
  2168. * you'll need to call drupal_add_tabledrag() once for every region added.
  2169. *
  2170. * @code
  2171. * foreach ($regions as $region) {
  2172. * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight', 'my-elements-weight-'. $region);
  2173. * }
  2174. * @endcode
  2175. *
  2176. * In a situation where tree relationships are present, adding multiple
  2177. * subgroups is not necessary, because the table will contain indentations that
  2178. * provide enough information about the sibling and parent relationships.
  2179. * See theme_menu_overview_form() for an example creating a table containing
  2180. * parent relationships.
  2181. *
  2182. * Please note that this function should be called from the theme layer, such as
  2183. * in a .tpl.php file, theme_ function, or in a template_preprocess function,
  2184. * not in a form declartion. Though the same JavaScript could be added to the
  2185. * page using drupal_add_js() directly, this function helps keep template files
  2186. * clean and readable. It also prevents tabledrag.js from being added twice
  2187. * accidentally.
  2188. *
  2189. * @param $table_id
  2190. * String containing the target table's id attribute. If the table does not
  2191. * have an id, one will need to be set, such as <table id="my-module-table">.
  2192. * @param $action
  2193. * String describing the action to be done on the form item. Either 'match'
  2194. * 'depth', or 'order'. Match is typically used for parent relationships.
  2195. * Order is typically used to set weights on other form elements with the same
  2196. * group. Depth updates the target element with the current indentation.
  2197. * @param $relationship
  2198. * String describing where the $action variable should be performed. Either
  2199. * 'parent', 'sibling', 'group', or 'self'. Parent will only look for fields
  2200. * up the tree. Sibling will look for fields in the same group in rows above
  2201. * and below it. Self affects the dragged row itself. Group affects the
  2202. * dragged row, plus any children below it (the entire dragged group).
  2203. * @param $group
  2204. * A class name applied on all related form elements for this action.
  2205. * @param $subgroup
  2206. * (optional) If the group has several subgroups within it, this string should
  2207. * contain the class name identifying fields in the same subgroup.
  2208. * @param $source
  2209. * (optional) If the $action is 'match', this string should contain the class
  2210. * name identifying what field will be used as the source value when matching
  2211. * the value in $subgroup.
  2212. * @param $hidden
  2213. * (optional) The column containing the field elements may be entirely hidden
  2214. * from view dynamically when the JavaScript is loaded. Set to FALSE if the
  2215. * column should not be hidden.
  2216. * @param $limit
  2217. * (optional) Limit the maximum amount of parenting in this table.
  2218. * @see block-admin-display-form.tpl.php
  2219. * @see theme_menu_overview_form()
  2220. */
  2221. function drupal_add_tabledrag($table_id, $action, $relationship, $group, $subgroup = NULL, $source = NULL, $hidden = TRUE, $limit = 0) {
  2222. static $js_added = FALSE;
  2223. if (!$js_added) {
  2224. drupal_add_js('misc/tabledrag.js', 'core');
  2225. $js_added = TRUE;
  2226. }
  2227. // If a subgroup or source isn't set, assume it is the same as the group.
  2228. $target = isset($subgroup) ? $subgroup : $group;
  2229. $source = isset($source) ? $source : $target;
  2230. $settings['tableDrag'][$table_id][$group][] = array(
  2231. 'target' => $target,
  2232. 'source' => $source,
  2233. 'relationship' => $relationship,
  2234. 'action' => $action,
  2235. 'hidden' => $hidden,
  2236. 'limit' => $limit,
  2237. );
  2238. drupal_add_js($settings, 'setting');
  2239. }
  2240. /**
  2241. * Aggregate JS files, putting them in the files directory.
  2242. *
  2243. * @param $files
  2244. * An array of JS files to aggregate and compress into one file.
  2245. * @param $filename
  2246. * The name of the aggregate JS file.
  2247. * @return
  2248. * The name of the JS file.
  2249. */
  2250. function drupal_build_js_cache($files, $filename) {
  2251. $contents = '';
  2252. // Create the js/ within the files folder.
  2253. $jspath = file_create_path('js');
  2254. file_check_directory($jspath, FILE_CREATE_DIRECTORY);
  2255. if (!file_exists($jspath .'/'. $filename)) {
  2256. // Build aggregate JS file.
  2257. foreach ($files as $path => $info) {
  2258. if ($info['preprocess']) {
  2259. // Append a ';' and a newline after each JS file to prevent them from running together.
  2260. $contents .= file_get_contents($path) .";\n";
  2261. }
  2262. }
  2263. // Create the JS file.
  2264. file_save_data($contents, $jspath .'/'. $filename, FILE_EXISTS_REPLACE);
  2265. }
  2266. return $jspath .'/'. $filename;
  2267. }
  2268. /**
  2269. * Delete all cached JS files.
  2270. */
  2271. function drupal_clear_js_cache() {
  2272. file_scan_directory(file_create_path('js'), '.*', array('.', '..', 'CVS'), 'file_delete', TRUE);
  2273. variable_set('javascript_parsed', array());
  2274. }
  2275. /**
  2276. * Converts a PHP variable into its Javascript equivalent.
  2277. *
  2278. * We use HTML-safe strings, i.e. with <, > and & escaped.
  2279. */
  2280. function drupal_to_js($var) {
  2281. switch (gettype($var)) {
  2282. case 'boolean':
  2283. return $var ? 'true' : 'false'; // Lowercase necessary!
  2284. case 'integer':
  2285. case 'double':
  2286. return $var;
  2287. case 'resource':
  2288. case 'string':
  2289. return '"'. str_replace(array("\r", "\n", "<", ">", "&"),
  2290. array('\r', '\n', '\x3c', '\x3e', '\x26'),
  2291. addslashes($var)) .'"';
  2292. case 'array':
  2293. // Arrays in JSON can't be associative. If the array is empty or if it
  2294. // has sequential whole number keys starting with 0, it's not associative
  2295. // so we can go ahead and convert it as an array.
  2296. if (empty ($var) || array_keys($var) === range(0, sizeof($var) - 1)) {
  2297. $output = array();
  2298. foreach ($var as $v) {
  2299. $output[] = drupal_to_js($v);
  2300. }
  2301. return '[ '. implode(', ', $output) .' ]';
  2302. }
  2303. // Otherwise, fall through to convert the array as an object.
  2304. case 'object':
  2305. $output = array();
  2306. foreach ($var as $k => $v) {
  2307. $output[] = drupal_to_js(strval($k)) .': '. drupal_to_js($v);
  2308. }
  2309. return '{ '. implode(', ', $output) .' }';
  2310. default:
  2311. return 'null';
  2312. }
  2313. }
  2314. /**
  2315. * Return data in JSON format.
  2316. *
  2317. * This function should be used for JavaScript callback functions returning
  2318. * data in JSON format. It sets the header for JavaScript output.
  2319. *
  2320. * @param $var
  2321. * (optional) If set, the variable will be converted to JSON and output.
  2322. */
  2323. function drupal_json($var = NULL) {
  2324. // We are returning JavaScript, so tell the browser.
  2325. drupal_set_header('Content-Type: text/javascript; charset=utf-8');
  2326. if (isset($var)) {
  2327. echo drupal_to_js($var);
  2328. }
  2329. }
  2330. /**
  2331. * Wrapper around urlencode() which avoids Apache quirks.
  2332. *
  2333. * Should be used when placing arbitrary data in an URL. Note that Drupal paths
  2334. * are urlencoded() when passed through url() and do not require urlencoding()
  2335. * of individual components.
  2336. *
  2337. * Notes:
  2338. * - For esthetic reasons, we do not escape slashes. This also avoids a 'feature'
  2339. * in Apache where it 404s on any path containing '%2F'.
  2340. * - mod_rewrite unescapes %-encoded ampersands, hashes, and slashes when clean
  2341. * URLs are used, which are interpreted as delimiters by PHP. These
  2342. * characters are double escaped so PHP will still see the encoded version.
  2343. * - With clean URLs, Apache changes '//' to '/', so every second slash is
  2344. * double escaped.
  2345. * - This function should only be used on paths, not on query string arguments,
  2346. * otherwise unwanted double encoding will occur.
  2347. *
  2348. * @param $text
  2349. * String to encode
  2350. */
  2351. function drupal_urlencode($text) {
  2352. if (variable_get('clean_url', '0')) {
  2353. return str_replace(array('%2F', '%26', '%23', '//'),
  2354. array('/', '%2526', '%2523', '/%252F'),
  2355. rawurlencode($text));
  2356. }
  2357. else {
  2358. return str_replace('%2F', '/', rawurlencode($text));
  2359. }
  2360. }
  2361. /**
  2362. * Ensure the private key variable used to generate tokens is set.
  2363. *
  2364. * @return
  2365. * The private key.
  2366. */
  2367. function drupal_get_private_key() {
  2368. if (!($key = variable_get('drupal_private_key', 0))) {
  2369. $key = md5(uniqid(mt_rand(), true)) . md5(uniqid(mt_rand(), true));
  2370. variable_set('drupal_private_key', $key);
  2371. }
  2372. return $key;
  2373. }
  2374. /**
  2375. * Generate a token based on $value, the current user session and private key.
  2376. *
  2377. * @param $value
  2378. * An additional value to base the token on.
  2379. */
  2380. function drupal_get_token($value = '') {
  2381. $private_key = drupal_get_private_key();
  2382. return md5(session_id() . $value . $private_key);
  2383. }
  2384. /**
  2385. * Validate a token based on $value, the current user session and private key.
  2386. *
  2387. * @param $token
  2388. * The token to be validated.
  2389. * @param $value
  2390. * An additional value to base the token on.
  2391. * @param $skip_anonymous
  2392. * Set to true to skip token validation for anonymous users.
  2393. * @return
  2394. * True for a valid token, false for an invalid token. When $skip_anonymous
  2395. * is true, the return value will always be true for anonymous users.
  2396. */
  2397. function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
  2398. global $user;
  2399. return (($skip_anonymous && $user->uid == 0) || ($token == md5(session_id() . $value . variable_get('drupal_private_key', ''))));
  2400. }
  2401. /**
  2402. * Performs one or more XML-RPC request(s).
  2403. *
  2404. * @param $url
  2405. * An absolute URL of the XML-RPC endpoint.
  2406. * Example:
  2407. * http://www.example.com/xmlrpc.php
  2408. * @param ...
  2409. * For one request:
  2410. * The method name followed by a variable number of arguments to the method.
  2411. * For multiple requests (system.multicall):
  2412. * An array of call arrays. Each call array follows the pattern of the single
  2413. * request: method name followed by the arguments to the method.
  2414. * @return
  2415. * For one request:
  2416. * Either the return value of the method on success, or FALSE.
  2417. * If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
  2418. * For multiple requests:
  2419. * An array of results. Each result will either be the result
  2420. * returned by the method called, or an xmlrpc_error object if the call
  2421. * failed. See xmlrpc_error().
  2422. */
  2423. function xmlrpc($url) {
  2424. require_once './includes/xmlrpc.inc';
  2425. $args = func_get_args();
  2426. return call_user_func_array('_xmlrpc', $args);
  2427. }
  2428. function _drupal_bootstrap_full() {
  2429. static $called;
  2430. if ($called) {
  2431. return;
  2432. }
  2433. $called = 1;
  2434. require_once './includes/theme.inc';
  2435. require_once './includes/pager.inc';
  2436. require_once './includes/menu.inc';
  2437. require_once './includes/tablesort.inc';
  2438. require_once './includes/file.inc';
  2439. require_once './includes/unicode.inc';
  2440. require_once './includes/image.inc';
  2441. require_once './includes/form.inc';
  2442. require_once './includes/mail.inc';
  2443. require_once './includes/actions.inc';
  2444. // Set the Drupal custom error handler.
  2445. set_error_handler('drupal_error_handler');
  2446. // Emit the correct charset HTTP header.
  2447. drupal_set_header('Content-Type: text/html; charset=utf-8');
  2448. // Detect string handling method
  2449. unicode_check();
  2450. // Undo magic quotes
  2451. fix_gpc_magic();
  2452. // Load all enabled modules
  2453. module_load_all();
  2454. // Let all modules take action before menu system handles the request
  2455. // We do not want this while running update.php.
  2456. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
  2457. module_invoke_all('init');
  2458. }
  2459. }
  2460. /**
  2461. * Store the current page in the cache.
  2462. *
  2463. * If page_compression is enabled, a gzipped version of the page is stored in
  2464. * the cache to avoid compressing the output on each request. The cache entry
  2465. * is unzipped in the relatively rare event that the page is requested by a
  2466. * client without gzip support.
  2467. *
  2468. * Page compression requires the PHP zlib extension
  2469. * (http://php.net/manual/en/ref.zlib.php).
  2470. *
  2471. * @see drupal_page_header
  2472. */
  2473. function page_set_cache() {
  2474. global $user, $base_root;
  2475. if (!$user->uid && $_SERVER['REQUEST_METHOD'] == 'GET' && page_get_cache(TRUE)) {
  2476. // This will fail in some cases, see page_get_cache() for the explanation.
  2477. if ($data = ob_get_contents()) {
  2478. if (variable_get('page_compression', TRUE) && extension_loaded('zlib')) {
  2479. $data = gzencode($data, 9, FORCE_GZIP);
  2480. }
  2481. ob_end_flush();
  2482. cache_set($base_root . request_uri(), $data, 'cache_page', CACHE_TEMPORARY, drupal_get_headers());
  2483. }
  2484. }
  2485. }
  2486. /**
  2487. * Executes a cron run when called
  2488. * @return
  2489. * Returns TRUE if ran successfully
  2490. */
  2491. function drupal_cron_run() {
  2492. // Try to allocate enough time to run all the hook_cron implementations.
  2493. if (function_exists('set_time_limit')) {
  2494. @set_time_limit(240);
  2495. }
  2496. // Fetch the cron semaphore
  2497. $semaphore = variable_get('cron_semaphore', FALSE);
  2498. if ($semaphore) {
  2499. if (time() - $semaphore > 3600) {
  2500. // Either cron has been running for more than an hour or the semaphore
  2501. // was not reset due to a database error.
  2502. watchdog('cron', 'Cron has been running for more than an hour and is most likely stuck.', array(), WATCHDOG_ERROR);
  2503. // Release cron semaphore
  2504. variable_del('cron_semaphore');
  2505. }
  2506. else {
  2507. // Cron is still running normally.
  2508. watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
  2509. }
  2510. }
  2511. else {
  2512. // Register shutdown callback
  2513. register_shutdown_function('drupal_cron_cleanup');
  2514. // Lock cron semaphore
  2515. variable_set('cron_semaphore', time());
  2516. // Iterate through the modules calling their cron handlers (if any):
  2517. module_invoke_all('cron');
  2518. // Record cron time
  2519. variable_set('cron_last', time());
  2520. watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
  2521. // Release cron semaphore
  2522. variable_del('cron_semaphore');
  2523. // Return TRUE so other functions can check if it did run successfully
  2524. return TRUE;
  2525. }
  2526. }
  2527. /**
  2528. * Shutdown function for cron cleanup.
  2529. */
  2530. function drupal_cron_cleanup() {
  2531. // See if the semaphore is still locked.
  2532. if (variable_get('cron_semaphore', FALSE)) {
  2533. watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);
  2534. // Release cron semaphore
  2535. variable_del('cron_semaphore');
  2536. }
  2537. }
  2538. /**
  2539. * Return an array of system file objects.
  2540. *
  2541. * Returns an array of file objects of the given type from the site-wide
  2542. * directory (i.e. modules/), the all-sites directory (i.e.
  2543. * sites/all/modules/), the profiles directory, and site-specific directory
  2544. * (i.e. sites/somesite/modules/). The returned array will be keyed using the
  2545. * key specified (name, basename, filename). Using name or basename will cause
  2546. * site-specific files to be prioritized over similar files in the default
  2547. * directories. That is, if a file with the same name appears in both the
  2548. * site-wide directory and site-specific directory, only the site-specific
  2549. * version will be included.
  2550. *
  2551. * @param $mask
  2552. * The regular expression of the files to find.
  2553. * @param $directory
  2554. * The subdirectory name in which the files are found. For example,
  2555. * 'modules' will search in both modules/ and
  2556. * sites/somesite/modules/.
  2557. * @param $key
  2558. * The key to be passed to file_scan_directory().
  2559. * @param $min_depth
  2560. * Minimum depth of directories to return files from.
  2561. *
  2562. * @return
  2563. * An array of file objects of the specified type.
  2564. */
  2565. function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
  2566. global $profile;
  2567. $config = conf_path();
  2568. // When this function is called during Drupal's initial installation process,
  2569. // the name of the profile that's about to be installed is stored in the global
  2570. // $profile variable. At all other times, the standard Drupal systems variable
  2571. // table contains the name of the current profile, and we can call variable_get()
  2572. // to determine what one is active.
  2573. if (!isset($profile)) {
  2574. $profile = variable_get('install_profile', 'default');
  2575. }
  2576. $searchdir = array($directory);
  2577. $files = array();
  2578. // The 'profiles' directory contains pristine collections of modules and
  2579. // themes as organized by a distribution. It is pristine in the same way
  2580. // that /modules is pristine for core; users should avoid changing anything
  2581. // there in favor of sites/all or sites/<domain> directories.
  2582. if (file_exists("profiles/$profile/$directory")) {
  2583. $searchdir[] = "profiles/$profile/$directory";
  2584. }
  2585. // Always search sites/all/* as well as the global directories
  2586. $searchdir[] = 'sites/all/'. $directory;
  2587. if (file_exists("$config/$directory")) {
  2588. $searchdir[] = "$config/$directory";
  2589. }
  2590. // Get current list of items
  2591. foreach ($searchdir as $dir) {
  2592. $files = array_merge($files, file_scan_directory($dir, $mask, array('.', '..', 'CVS'), 0, TRUE, $key, $min_depth));
  2593. }
  2594. return $files;
  2595. }
  2596. /**
  2597. * Hands off alterable variables to type-specific *_alter implementations.
  2598. *
  2599. * This dispatch function hands off the passed in variables to type-specific
  2600. * hook_TYPE_alter() implementations in modules. It ensures a consistent
  2601. * interface for all altering operations.
  2602. *
  2603. * @param $type
  2604. * A string describing the type of the alterable $data (e.g. 'form',
  2605. * 'profile').
  2606. * @param $data
  2607. * The variable that will be passed to hook_TYPE_alter() implementations to
  2608. * be altered. The type of this variable depends on $type. For example, when
  2609. * altering a 'form', $data will be a structured array. When altering a
  2610. * 'profile', $data will be an object. If you need to pass additional
  2611. * parameters by reference to the hook_TYPE_alter() functions, include them
  2612. * as an array in $data['__drupal_alter_by_ref']. They will be unpacked and
  2613. * passed to the hook_TYPE_alter() functions, before the additional
  2614. * ... parameters (see below).
  2615. * @param ...
  2616. * Any additional parameters will be passed on to the hook_TYPE_alter()
  2617. * functions (not by reference), after any by-reference parameters included
  2618. * in $data (see above)
  2619. */
  2620. function drupal_alter($type, &$data) {
  2621. // PHP's func_get_args() always returns copies of params, not references, so
  2622. // drupal_alter() can only manipulate data that comes in via the required first
  2623. // param. For the edge case functions that must pass in an arbitrary number of
  2624. // alterable parameters (hook_form_alter() being the best example), an array of
  2625. // those params can be placed in the __drupal_alter_by_ref key of the $data
  2626. // array. This is somewhat ugly, but is an unavoidable consequence of a flexible
  2627. // drupal_alter() function, and the limitations of func_get_args().
  2628. // @todo: Remove this in Drupal 7.
  2629. if (is_array($data) && isset($data['__drupal_alter_by_ref'])) {
  2630. $by_ref_parameters = $data['__drupal_alter_by_ref'];
  2631. unset($data['__drupal_alter_by_ref']);
  2632. }
  2633. // Hang onto a reference to the data array so that it isn't blown away later.
  2634. // Also, merge in any parameters that need to be passed by reference.
  2635. $args = array(&$data);
  2636. if (isset($by_ref_parameters)) {
  2637. $args = array_merge($args, $by_ref_parameters);
  2638. }
  2639. // Now, use func_get_args() to pull in any additional parameters passed into
  2640. // the drupal_alter() call.
  2641. $additional_args = func_get_args();
  2642. array_shift($additional_args);
  2643. array_shift($additional_args);
  2644. $args = array_merge($args, $additional_args);
  2645. foreach (module_implements($type .'_alter') as $module) {
  2646. $function = $module .'_'. $type .'_alter';
  2647. call_user_func_array($function, $args);
  2648. }
  2649. }
  2650. /**
  2651. * Renders HTML given a structured array tree.
  2652. *
  2653. * Recursively iterates over each of the array elements, generating HTML code.
  2654. * This function is usually called from within another function, like
  2655. * drupal_get_form() or node_view().
  2656. *
  2657. * drupal_render() flags each element with a '#printed' status to indicate that
  2658. * the element has been rendered, which allows individual elements of a given
  2659. * array to be rendered independently. This prevents elements from being
  2660. * rendered more than once on subsequent calls to drupal_render() if, for example,
  2661. * they are part of a larger array. If the same array or array element is passed
  2662. * more than once to drupal_render(), it simply returns a NULL value.
  2663. *
  2664. * @param $elements
  2665. * The structured array describing the data to be rendered.
  2666. * @return
  2667. * The rendered HTML.
  2668. */
  2669. function drupal_render(&$elements) {
  2670. if (!isset($elements) || (isset($elements['#access']) && !$elements['#access'])) {
  2671. return NULL;
  2672. }
  2673. // If the default values for this element haven't been loaded yet, populate
  2674. // them.
  2675. if (!isset($elements['#defaults_loaded']) || !$elements['#defaults_loaded']) {
  2676. if ((!empty($elements['#type'])) && ($info = _element_info($elements['#type']))) {
  2677. $elements += $info;
  2678. }
  2679. }
  2680. // Make any final changes to the element before it is rendered. This means
  2681. // that the $element or the children can be altered or corrected before the
  2682. // element is rendered into the final text.
  2683. if (isset($elements['#pre_render'])) {
  2684. foreach ($elements['#pre_render'] as $function) {
  2685. if (function_exists($function)) {
  2686. $elements = $function($elements);
  2687. }
  2688. }
  2689. }
  2690. $content = '';
  2691. // Either the elements did not go through form_builder or one of the children
  2692. // has a #weight.
  2693. if (!isset($elements['#sorted'])) {
  2694. uasort($elements, "element_sort");
  2695. }
  2696. $elements += array('#title' => NULL, '#description' => NULL);
  2697. if (!isset($elements['#children'])) {
  2698. $children = element_children($elements);
  2699. // Render all the children that use a theme function.
  2700. if (isset($elements['#theme']) && empty($elements['#theme_used'])) {
  2701. $elements['#theme_used'] = TRUE;
  2702. $previous = array();
  2703. foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
  2704. $previous[$key] = isset($elements[$key]) ? $elements[$key] : NULL;
  2705. }
  2706. // If we rendered a single element, then we will skip the renderer.
  2707. if (empty($children)) {
  2708. $elements['#printed'] = TRUE;
  2709. }
  2710. else {
  2711. $elements['#value'] = '';
  2712. }
  2713. $elements['#type'] = 'markup';
  2714. unset($elements['#prefix'], $elements['#suffix']);
  2715. $content = theme($elements['#theme'], $elements);
  2716. foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
  2717. $elements[$key] = isset($previous[$key]) ? $previous[$key] : NULL;
  2718. }
  2719. }
  2720. // Render each of the children using drupal_render and concatenate them.
  2721. if (!isset($content) || $content === '') {
  2722. foreach ($children as $key) {
  2723. $content .= drupal_render($elements[$key]);
  2724. }
  2725. }
  2726. }
  2727. if (isset($content) && $content !== '') {
  2728. $elements['#children'] = $content;
  2729. }
  2730. // Until now, we rendered the children, here we render the element itself
  2731. if (!isset($elements['#printed'])) {
  2732. $content = theme(!empty($elements['#type']) ? $elements['#type'] : 'markup', $elements);
  2733. $elements['#printed'] = TRUE;
  2734. }
  2735. if (isset($content) && $content !== '') {
  2736. // Filter the outputted content and make any last changes before the
  2737. // content is sent to the browser. The changes are made on $content
  2738. // which allows the output'ed text to be filtered.
  2739. if (isset($elements['#post_render'])) {
  2740. foreach ($elements['#post_render'] as $function) {
  2741. if (function_exists($function)) {
  2742. $content = $function($content, $elements);
  2743. }
  2744. }
  2745. }
  2746. $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
  2747. $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
  2748. return $prefix . $content . $suffix;
  2749. }
  2750. }
  2751. /**
  2752. * Function used by uasort to sort structured arrays by weight.
  2753. */
  2754. function element_sort($a, $b) {
  2755. $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
  2756. $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
  2757. if ($a_weight == $b_weight) {
  2758. return 0;
  2759. }
  2760. return ($a_weight < $b_weight) ? -1 : 1;
  2761. }
  2762. /**
  2763. * Check if the key is a property.
  2764. */
  2765. function element_property($key) {
  2766. return $key[0] == '#';
  2767. }
  2768. /**
  2769. * Get properties of a structured array element. Properties begin with '#'.
  2770. */
  2771. function element_properties($element) {
  2772. return array_filter(array_keys((array) $element), 'element_property');
  2773. }
  2774. /**
  2775. * Check if the key is a child.
  2776. */
  2777. function element_child($key) {
  2778. return !isset($key[0]) || $key[0] != '#';
  2779. }
  2780. /**
  2781. * Get keys of a structured array tree element that are not properties (i.e., do not begin with '#').
  2782. */
  2783. function element_children($element) {
  2784. return array_filter(array_keys((array) $element), 'element_child');
  2785. }
  2786. /**
  2787. * Provide theme registration for themes across .inc files.
  2788. */
  2789. function drupal_common_theme() {
  2790. return array(
  2791. // theme.inc
  2792. 'placeholder' => array(
  2793. 'arguments' => array('text' => NULL)
  2794. ),
  2795. 'page' => array(
  2796. 'arguments' => array('content' => NULL, 'show_blocks' => TRUE, 'show_messages' => TRUE),
  2797. 'template' => 'page',
  2798. ),
  2799. 'maintenance_page' => array(
  2800. 'arguments' => array('content' => NULL, 'show_blocks' => TRUE, 'show_messages' => TRUE),
  2801. 'template' => 'maintenance-page',
  2802. ),
  2803. 'update_page' => array(
  2804. 'arguments' => array('content' => NULL, 'show_messages' => TRUE),
  2805. ),
  2806. 'install_page' => array(
  2807. 'arguments' => array('content' => NULL),
  2808. ),
  2809. 'task_list' => array(
  2810. 'arguments' => array('items' => NULL, 'active' => NULL),
  2811. ),
  2812. 'status_messages' => array(
  2813. 'arguments' => array('display' => NULL),
  2814. ),
  2815. 'links' => array(
  2816. 'arguments' => array('links' => NULL, 'attributes' => array('class' => 'links')),
  2817. ),
  2818. 'image' => array(
  2819. 'arguments' => array('path' => NULL, 'alt' => '', 'title' => '', 'attributes' => NULL, 'getsize' => TRUE),
  2820. ),
  2821. 'breadcrumb' => array(
  2822. 'arguments' => array('breadcrumb' => NULL),
  2823. ),
  2824. 'help' => array(
  2825. 'arguments' => array(),
  2826. ),
  2827. 'submenu' => array(
  2828. 'arguments' => array('links' => NULL),
  2829. ),
  2830. 'table' => array(
  2831. 'arguments' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL),
  2832. ),
  2833. 'table_select_header_cell' => array(
  2834. 'arguments' => array(),
  2835. ),
  2836. 'tablesort_indicator' => array(
  2837. 'arguments' => array('style' => NULL),
  2838. ),
  2839. 'box' => array(
  2840. 'arguments' => array('title' => NULL, 'content' => NULL, 'region' => 'main'),
  2841. 'template' => 'box',
  2842. ),
  2843. 'block' => array(
  2844. 'arguments' => array('block' => NULL),
  2845. 'template' => 'block',
  2846. ),
  2847. 'mark' => array(
  2848. 'arguments' => array('type' => MARK_NEW),
  2849. ),
  2850. 'item_list' => array(
  2851. 'arguments' => array('items' => array(), 'title' => NULL, 'type' => 'ul', 'attributes' => NULL),
  2852. ),
  2853. 'more_help_link' => array(
  2854. 'arguments' => array('url' => NULL),
  2855. ),
  2856. 'xml_icon' => array(
  2857. 'arguments' => array('url' => NULL),
  2858. ),
  2859. 'feed_icon' => array(
  2860. 'arguments' => array('url' => NULL, 'title' => NULL),
  2861. ),
  2862. 'more_link' => array(
  2863. 'arguments' => array('url' => NULL, 'title' => NULL)
  2864. ),
  2865. 'closure' => array(
  2866. 'arguments' => array('main' => 0),
  2867. ),
  2868. 'blocks' => array(
  2869. 'arguments' => array('region' => NULL),
  2870. ),
  2871. 'username' => array(
  2872. 'arguments' => array('object' => NULL),
  2873. ),
  2874. 'progress_bar' => array(
  2875. 'arguments' => array('percent' => NULL, 'message' => NULL),
  2876. ),
  2877. 'indentation' => array(
  2878. 'arguments' => array('size' => 1),
  2879. ),
  2880. // from pager.inc
  2881. 'pager' => array(
  2882. 'arguments' => array('tags' => array(), 'limit' => 10, 'element' => 0, 'parameters' => array()),
  2883. ),
  2884. 'pager_first' => array(
  2885. 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'parameters' => array()),
  2886. ),
  2887. 'pager_previous' => array(
  2888. 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
  2889. ),
  2890. 'pager_next' => array(
  2891. 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
  2892. ),
  2893. 'pager_last' => array(
  2894. 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'parameters' => array()),
  2895. ),
  2896. 'pager_link' => array(
  2897. 'arguments' => array('text' => NULL, 'page_new' => NULL, 'element' => NULL, 'parameters' => array(), 'attributes' => array()),
  2898. ),
  2899. // from menu.inc
  2900. 'menu_item_link' => array(
  2901. 'arguments' => array('item' => NULL),
  2902. ),
  2903. 'menu_tree' => array(
  2904. 'arguments' => array('tree' => NULL),
  2905. ),
  2906. 'menu_item' => array(
  2907. 'arguments' => array('link' => NULL, 'has_children' => NULL, 'menu' => ''),
  2908. ),
  2909. 'menu_local_task' => array(
  2910. 'arguments' => array('link' => NULL, 'active' => FALSE),
  2911. ),
  2912. 'menu_local_tasks' => array(
  2913. 'arguments' => array(),
  2914. ),
  2915. // from form.inc
  2916. 'select' => array(
  2917. 'arguments' => array('element' => NULL),
  2918. ),
  2919. 'fieldset' => array(
  2920. 'arguments' => array('element' => NULL),
  2921. ),
  2922. 'radio' => array(
  2923. 'arguments' => array('element' => NULL),
  2924. ),
  2925. 'radios' => array(
  2926. 'arguments' => array('element' => NULL),
  2927. ),
  2928. 'password_confirm' => array(
  2929. 'arguments' => array('element' => NULL),
  2930. ),
  2931. 'date' => array(
  2932. 'arguments' => array('element' => NULL),
  2933. ),
  2934. 'item' => array(
  2935. 'arguments' => array('element' => NULL),
  2936. ),
  2937. 'checkbox' => array(
  2938. 'arguments' => array('element' => NULL),
  2939. ),
  2940. 'checkboxes' => array(
  2941. 'arguments' => array('element' => NULL),
  2942. ),
  2943. 'submit' => array(
  2944. 'arguments' => array('element' => NULL),
  2945. ),
  2946. 'button' => array(
  2947. 'arguments' => array('element' => NULL),
  2948. ),
  2949. 'image_button' => array(
  2950. 'arguments' => array('element' => NULL),
  2951. ),
  2952. 'hidden' => array(
  2953. 'arguments' => array('element' => NULL),
  2954. ),
  2955. 'token' => array(
  2956. 'arguments' => array('element' => NULL),
  2957. ),
  2958. 'textfield' => array(
  2959. 'arguments' => array('element' => NULL),
  2960. ),
  2961. 'form' => array(
  2962. 'arguments' => array('element' => NULL),
  2963. ),
  2964. 'textarea' => array(
  2965. 'arguments' => array('element' => NULL),
  2966. ),
  2967. 'markup' => array(
  2968. 'arguments' => array('element' => NULL),
  2969. ),
  2970. 'password' => array(
  2971. 'arguments' => array('element' => NULL),
  2972. ),
  2973. 'file' => array(
  2974. 'arguments' => array('element' => NULL),
  2975. ),
  2976. 'form_element' => array(
  2977. 'arguments' => array('element' => NULL, 'value' => NULL),
  2978. ),
  2979. );
  2980. }
  2981. /**
  2982. * @ingroup schemaapi
  2983. * @{
  2984. */
  2985. /**
  2986. * Get the schema definition of a table, or the whole database schema.
  2987. *
  2988. * The returned schema will include any modifications made by any
  2989. * module that implements hook_schema_alter().
  2990. *
  2991. * @param $table
  2992. * The name of the table. If not given, the schema of all tables is returned.
  2993. * @param $rebuild
  2994. * If true, the schema will be rebuilt instead of retrieved from the cache.
  2995. */
  2996. function drupal_get_schema($table = NULL, $rebuild = FALSE) {
  2997. static $schema = array();
  2998. if (empty($schema) || $rebuild) {
  2999. // Try to load the schema from cache.
  3000. if (!$rebuild && $cached = cache_get('schema')) {
  3001. $schema = $cached->data;
  3002. }
  3003. // Otherwise, rebuild the schema cache.
  3004. else {
  3005. $schema = array();
  3006. // Load the .install files to get hook_schema.
  3007. module_load_all_includes('install');
  3008. // Invoke hook_schema for all modules.
  3009. foreach (module_implements('schema') as $module) {
  3010. // Cast the result of hook_schema() to an array, as a NULL return value
  3011. // would cause array_merge() to set the $schema variable to NULL as well.
  3012. // That would break modules which use $schema further down the line.
  3013. $current = (array) module_invoke($module, 'schema');
  3014. _drupal_initialize_schema($module, $current);
  3015. $schema = array_merge($schema, $current);
  3016. }
  3017. drupal_alter('schema', $schema);
  3018. cache_set('schema', $schema);
  3019. }
  3020. }
  3021. if (!isset($table)) {
  3022. return $schema;
  3023. }
  3024. elseif (isset($schema[$table])) {
  3025. return $schema[$table];
  3026. }
  3027. else {
  3028. return FALSE;
  3029. }
  3030. }
  3031. /**
  3032. * Create all tables that a module defines in its hook_schema().
  3033. *
  3034. * Note: This function does not pass the module's schema through
  3035. * hook_schema_alter(). The module's tables will be created exactly as the
  3036. * module defines them.
  3037. *
  3038. * @param $module
  3039. * The module for which the tables will be created.
  3040. * @return
  3041. * An array of arrays with the following key/value pairs:
  3042. * - success: a boolean indicating whether the query succeeded.
  3043. * - query: the SQL query(s) executed, passed through check_plain().
  3044. */
  3045. function drupal_install_schema($module) {
  3046. $schema = drupal_get_schema_unprocessed($module);
  3047. _drupal_initialize_schema($module, $schema);
  3048. $ret = array();
  3049. foreach ($schema as $name => $table) {
  3050. db_create_table($ret, $name, $table);
  3051. }
  3052. return $ret;
  3053. }
  3054. /**
  3055. * Remove all tables that a module defines in its hook_schema().
  3056. *
  3057. * Note: This function does not pass the module's schema through
  3058. * hook_schema_alter(). The module's tables will be created exactly as the
  3059. * module defines them.
  3060. *
  3061. * @param $module
  3062. * The module for which the tables will be removed.
  3063. * @return
  3064. * An array of arrays with the following key/value pairs:
  3065. * - success: a boolean indicating whether the query succeeded.
  3066. * - query: the SQL query(s) executed, passed through check_plain().
  3067. */
  3068. function drupal_uninstall_schema($module) {
  3069. $schema = drupal_get_schema_unprocessed($module);
  3070. _drupal_initialize_schema($module, $schema);
  3071. $ret = array();
  3072. foreach ($schema as $table) {
  3073. db_drop_table($ret, $table['name']);
  3074. }
  3075. return $ret;
  3076. }
  3077. /**
  3078. * Returns the unprocessed and unaltered version of a module's schema.
  3079. *
  3080. * Use this function only if you explicitly need the original
  3081. * specification of a schema, as it was defined in a module's
  3082. * hook_schema(). No additional default values will be set,
  3083. * hook_schema_alter() is not invoked and these unprocessed
  3084. * definitions won't be cached.
  3085. *
  3086. * This function can be used to retrieve a schema specification in
  3087. * hook_schema(), so it allows you to derive your tables from existing
  3088. * specifications.
  3089. *
  3090. * It is also used by drupal_install_schema() and
  3091. * drupal_uninstall_schema() to ensure that a module's tables are
  3092. * created exactly as specified without any changes introduced by a
  3093. * module that implements hook_schema_alter().
  3094. *
  3095. * @param $module
  3096. * The module to which the table belongs.
  3097. * @param $table
  3098. * The name of the table. If not given, the module's complete schema
  3099. * is returned.
  3100. */
  3101. function drupal_get_schema_unprocessed($module, $table = NULL) {
  3102. // Load the .install file to get hook_schema.
  3103. module_load_install($module);
  3104. $schema = module_invoke($module, 'schema');
  3105. if (!is_null($table) && isset($schema[$table])) {
  3106. return $schema[$table];
  3107. }
  3108. elseif (!empty($schema)) {
  3109. return $schema;
  3110. }
  3111. return array();
  3112. }
  3113. /**
  3114. * Fill in required default values for table definitions returned by hook_schema().
  3115. *
  3116. * @param $module
  3117. * The module for which hook_schema() was invoked.
  3118. * @param $schema
  3119. * The schema definition array as it was returned by the module's
  3120. * hook_schema().
  3121. */
  3122. function _drupal_initialize_schema($module, &$schema) {
  3123. // Set the name and module key for all tables.
  3124. foreach ($schema as $name => $table) {
  3125. if (empty($table['module'])) {
  3126. $schema[$name]['module'] = $module;
  3127. }
  3128. if (!isset($table['name'])) {
  3129. $schema[$name]['name'] = $name;
  3130. }
  3131. }
  3132. }
  3133. /**
  3134. * Retrieve a list of fields from a table schema. The list is suitable for use in a SQL query.
  3135. *
  3136. * @param $table
  3137. * The name of the table from which to retrieve fields.
  3138. * @param
  3139. * An optional prefix to to all fields.
  3140. *
  3141. * @return An array of fields.
  3142. **/
  3143. function drupal_schema_fields_sql($table, $prefix = NULL) {
  3144. $schema = drupal_get_schema($table);
  3145. $fields = array_keys($schema['fields']);
  3146. if ($prefix) {
  3147. $columns = array();
  3148. foreach ($fields as $field) {
  3149. $columns[] = "$prefix.$field";
  3150. }
  3151. return $columns;
  3152. }
  3153. else {
  3154. return $fields;
  3155. }
  3156. }
  3157. /**
  3158. * Save a record to the database based upon the schema.
  3159. *
  3160. * Default values are filled in for missing items, and 'serial' (auto increment)
  3161. * types are filled in with IDs.
  3162. *
  3163. * @param $table
  3164. * The name of the table; this must exist in schema API.
  3165. * @param $object
  3166. * The object to write. This is a reference, as defaults according to
  3167. * the schema may be filled in on the object, as well as ID on the serial
  3168. * type(s). Both array an object types may be passed.
  3169. * @param $update
  3170. * If this is an update, specify the primary keys' field names. It is the
  3171. * caller's responsibility to know if a record for this object already
  3172. * exists in the database. If there is only 1 key, you may pass a simple string.
  3173. * @return
  3174. * Failure to write a record will return FALSE. Otherwise SAVED_NEW or
  3175. * SAVED_UPDATED is returned depending on the operation performed. The
  3176. * $object parameter contains values for any serial fields defined by
  3177. * the $table. For example, $object->nid will be populated after inserting
  3178. * a new node.
  3179. */
  3180. function drupal_write_record($table, &$object, $update = array()) {
  3181. // Standardize $update to an array.
  3182. if (is_string($update)) {
  3183. $update = array($update);
  3184. }
  3185. $schema = drupal_get_schema($table);
  3186. if (empty($schema)) {
  3187. return FALSE;
  3188. }
  3189. // Convert to an object if needed.
  3190. if (is_array($object)) {
  3191. $object = (object) $object;
  3192. $array = TRUE;
  3193. }
  3194. else {
  3195. $array = FALSE;
  3196. }
  3197. $fields = $defs = $values = $serials = $placeholders = array();
  3198. // Go through our schema, build SQL, and when inserting, fill in defaults for
  3199. // fields that are not set.
  3200. foreach ($schema['fields'] as $field => $info) {
  3201. // Special case -- skip serial types if we are updating.
  3202. if ($info['type'] == 'serial' && count($update)) {
  3203. continue;
  3204. }
  3205. // For inserts, populate defaults from Schema if not already provided
  3206. if (!isset($object->$field) && !count($update) && isset($info['default'])) {
  3207. $object->$field = $info['default'];
  3208. }
  3209. // Track serial fields so we can helpfully populate them after the query.
  3210. if ($info['type'] == 'serial') {
  3211. $serials[] = $field;
  3212. // Ignore values for serials when inserting data. Unsupported.
  3213. unset($object->$field);
  3214. }
  3215. // Build arrays for the fields, placeholders, and values in our query.
  3216. if (isset($object->$field)) {
  3217. $fields[] = $field;
  3218. $placeholders[] = db_type_placeholder($info['type']);
  3219. if (empty($info['serialize'])) {
  3220. $values[] = $object->$field;
  3221. }
  3222. else {
  3223. $values[] = serialize($object->$field);
  3224. }
  3225. }
  3226. }
  3227. // Build the SQL.
  3228. $query = '';
  3229. if (!count($update)) {
  3230. $query = "INSERT INTO {". $table ."} (". implode(', ', $fields) .') VALUES ('. implode(', ', $placeholders) .')';
  3231. $return = SAVED_NEW;
  3232. }
  3233. else {
  3234. $query = '';
  3235. foreach ($fields as $id => $field) {
  3236. if ($query) {
  3237. $query .= ', ';
  3238. }
  3239. $query .= $field .' = '. $placeholders[$id];
  3240. }
  3241. foreach ($update as $key){
  3242. $conditions[] = "$key = ". db_type_placeholder($schema['fields'][$key]['type']);
  3243. $values[] = $object->$key;
  3244. }
  3245. $query = "UPDATE {". $table ."} SET $query WHERE ". implode(' AND ', $conditions);
  3246. $return = SAVED_UPDATED;
  3247. }
  3248. // Execute the SQL.
  3249. if (db_query($query, $values)) {
  3250. if ($serials) {
  3251. // Get last insert ids and fill them in.
  3252. foreach ($serials as $field) {
  3253. $object->$field = db_last_insert_id($table, $field);
  3254. }
  3255. }
  3256. }
  3257. else {
  3258. $return = FALSE;
  3259. }
  3260. // If we began with an array, convert back so we don't surprise the caller.
  3261. if ($array) {
  3262. $object = (array) $object;
  3263. }
  3264. return $return;
  3265. }
  3266. /**
  3267. * @} End of "ingroup schemaapi".
  3268. */
  3269. /**
  3270. * Parse Drupal info file format.
  3271. *
  3272. * Files should use an ini-like format to specify values.
  3273. * White-space generally doesn't matter, except inside values.
  3274. * e.g.
  3275. *
  3276. * @code
  3277. * key = value
  3278. * key = "value"
  3279. * key = 'value'
  3280. * key = "multi-line
  3281. *
  3282. * value"
  3283. * key = 'multi-line
  3284. *
  3285. * value'
  3286. * key
  3287. * =
  3288. * 'value'
  3289. * @endcode
  3290. *
  3291. * Arrays are created using a GET-like syntax:
  3292. *
  3293. * @code
  3294. * key[] = "numeric array"
  3295. * key[index] = "associative array"
  3296. * key[index][] = "nested numeric array"
  3297. * key[index][index] = "nested associative array"
  3298. * @endcode
  3299. *
  3300. * PHP constants are substituted in, but only when used as the entire value:
  3301. *
  3302. * Comments should start with a semi-colon at the beginning of a line.
  3303. *
  3304. * This function is NOT for placing arbitrary module-specific settings. Use
  3305. * variable_get() and variable_set() for that.
  3306. *
  3307. * Information stored in the module.info file:
  3308. * - name: The real name of the module for display purposes.
  3309. * - description: A brief description of the module.
  3310. * - dependencies: An array of shortnames of other modules this module depends on.
  3311. * - package: The name of the package of modules this module belongs to.
  3312. *
  3313. * Example of .info file:
  3314. * @code
  3315. * name = Forum
  3316. * description = Enables threaded discussions about general topics.
  3317. * dependencies[] = taxonomy
  3318. * dependencies[] = comment
  3319. * package = Core - optional
  3320. * version = VERSION
  3321. * @endcode
  3322. *
  3323. * @param $filename
  3324. * The file we are parsing. Accepts file with relative or absolute path.
  3325. * @return
  3326. * The info array.
  3327. */
  3328. function drupal_parse_info_file($filename) {
  3329. $info = array();
  3330. $constants = get_defined_constants();
  3331. if (!file_exists($filename)) {
  3332. return $info;
  3333. }
  3334. $data = file_get_contents($filename);
  3335. if (preg_match_all('
  3336. @^\s* # Start at the beginning of a line, ignoring leading whitespace
  3337. ((?:
  3338. [^=;\[\]]| # Key names cannot contain equal signs, semi-colons or square brackets,
  3339. \[[^\[\]]*\] # unless they are balanced and not nested
  3340. )+?)
  3341. \s*=\s* # Key/value pairs are separated by equal signs (ignoring white-space)
  3342. (?:
  3343. ("(?:[^"]|(?<=\\\\)")*")| # Double-quoted string, which may contain slash-escaped quotes/slashes
  3344. (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
  3345. ([^\r\n]*?) # Non-quoted string
  3346. )\s*$ # Stop at the next end of a line, ignoring trailing whitespace
  3347. @msx', $data, $matches, PREG_SET_ORDER)) {
  3348. foreach ($matches as $match) {
  3349. // Fetch the key and value string
  3350. $i = 0;
  3351. foreach (array('key', 'value1', 'value2', 'value3') as $var) {
  3352. $$var = isset($match[++$i]) ? $match[$i] : '';
  3353. }
  3354. $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
  3355. // Parse array syntax
  3356. $keys = preg_split('/\]?\[/', rtrim($key, ']'));
  3357. $last = array_pop($keys);
  3358. $parent = &$info;
  3359. // Create nested arrays
  3360. foreach ($keys as $key) {
  3361. if ($key == '') {
  3362. $key = count($parent);
  3363. }
  3364. if (!isset($parent[$key]) || !is_array($parent[$key])) {
  3365. $parent[$key] = array();
  3366. }
  3367. $parent = &$parent[$key];
  3368. }
  3369. // Handle PHP constants.
  3370. if (isset($constants[$value])) {
  3371. $value = $constants[$value];
  3372. }
  3373. // Insert actual value
  3374. if ($last == '') {
  3375. $last = count($parent);
  3376. }
  3377. $parent[$last] = $value;
  3378. }
  3379. }
  3380. return $info;
  3381. }
  3382. /**
  3383. * @return
  3384. * Array of the possible severity levels for log messages.
  3385. *
  3386. * @see watchdog
  3387. */
  3388. function watchdog_severity_levels() {
  3389. return array(
  3390. WATCHDOG_EMERG => t('emergency'),
  3391. WATCHDOG_ALERT => t('alert'),
  3392. WATCHDOG_CRITICAL => t('critical'),
  3393. WATCHDOG_ERROR => t('error'),
  3394. WATCHDOG_WARNING => t('warning'),
  3395. WATCHDOG_NOTICE => t('notice'),
  3396. WATCHDOG_INFO => t('info'),
  3397. WATCHDOG_DEBUG => t('debug'),
  3398. );
  3399. }
  3400. /**
  3401. * Explode a string of given tags into an array.
  3402. *
  3403. * @see drupal_implode_tags()
  3404. */
  3405. function drupal_explode_tags($tags) {
  3406. // This regexp allows the following types of user input:
  3407. // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
  3408. $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
  3409. preg_match_all($regexp, $tags, $matches);
  3410. $typed_tags = array_unique($matches[1]);
  3411. $tags = array();
  3412. foreach ($typed_tags as $tag) {
  3413. // If a user has escaped a term (to demonstrate that it is a group,
  3414. // or includes a comma or quote character), we remove the escape
  3415. // formatting so to save the term into the database as the user intends.
  3416. $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
  3417. if ($tag != "") {
  3418. $tags[] = $tag;
  3419. }
  3420. }
  3421. return $tags;
  3422. }
  3423. /**
  3424. * Implode an array of tags into a string.
  3425. *
  3426. * @see drupal_explode_tags()
  3427. */
  3428. function drupal_implode_tags($tags) {
  3429. $encoded_tags = array();
  3430. foreach ($tags as $tag) {
  3431. // Commas and quotes in tag names are special cases, so encode them.
  3432. if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
  3433. $tag = '"'. str_replace('"', '""', $tag) .'"';
  3434. }
  3435. $encoded_tags[] = $tag;
  3436. }
  3437. return implode(', ', $encoded_tags);
  3438. }
  3439. /**
  3440. * Flush all cached data on the site.
  3441. *
  3442. * Empties cache tables, rebuilds the menu cache and theme registries, and
  3443. * invokes a hook so that other modules' cache data can be cleared as well.
  3444. */
  3445. function drupal_flush_all_caches() {
  3446. // Change query-strings on css/js files to enforce reload for all users.
  3447. _drupal_flush_css_js();
  3448. drupal_clear_css_cache();
  3449. drupal_clear_js_cache();
  3450. // If invoked from update.php, we must not update the theme information in the
  3451. // database, or this will result in all themes being disabled.
  3452. if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
  3453. _system_theme_data();
  3454. }
  3455. else {
  3456. system_theme_data();
  3457. }
  3458. drupal_rebuild_theme_registry();
  3459. menu_rebuild();
  3460. node_types_rebuild();
  3461. // Don't clear cache_form - in-progress form submissions may break.
  3462. // Ordered so clearing the page cache will always be the last action.
  3463. $core = array('cache', 'cache_block', 'cache_filter', 'cache_page');
  3464. $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
  3465. foreach ($cache_tables as $table) {
  3466. cache_clear_all('*', $table, TRUE);
  3467. }
  3468. }
  3469. /**
  3470. * Helper function to change query-strings on css/js files.
  3471. *
  3472. * Changes the character added to all css/js files as dummy query-string,
  3473. * so that all browsers are forced to reload fresh files. We keep
  3474. * 20 characters history (FIFO) to avoid repeats, but only the first
  3475. * (newest) character is actually used on urls, to keep them short.
  3476. * This is also called from update.php.
  3477. */
  3478. function _drupal_flush_css_js() {
  3479. $string_history = variable_get('css_js_query_string', '00000000000000000000');
  3480. $new_character = $string_history[0];
  3481. // Not including 'q' to allow certain JavaScripts to re-use query string.
  3482. $characters = 'abcdefghijklmnoprstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  3483. while (strpos($string_history, $new_character) !== FALSE) {
  3484. $new_character = $characters[mt_rand(0, strlen($characters) - 1)];
  3485. }
  3486. variable_set('css_js_query_string', $new_character . substr($string_history, 0, 19));
  3487. }