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

/site/includes/common.inc

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