PageRenderTime 61ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/common.inc

https://bitbucket.org/norvin/mingen-dts-server
PHP | 2379 lines | 1383 code | 148 blank | 848 comment | 199 complexity | 9db9f91270b0d4efd44aacb1473e0aa4 MD5 | raw file
Possible License(s): AGPL-1.0, BSD-3-Clause, GPL-2.0, LGPL-2.1
  1. <?php
  2. // $Id: common.inc,v 1.611.2.26 2010/03/04 00:16:02 drumm 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. *
  28. * @param $data
  29. * Content to be set.
  30. */
  31. function drupal_set_content($region = NULL, $data = NULL) {
  32. static $content = array();
  33. if (!is_null($region) && !is_null($data)) {
  34. $content[$region][] = $data;
  35. }
  36. return $content;
  37. }
  38. /**
  39. * Get assigned content.
  40. *
  41. * @param $region
  42. * A specified region to fetch content for. If NULL, all regions will be returned.
  43. *
  44. * @param $delimiter
  45. * Content to be inserted between exploded array elements.
  46. */
  47. function drupal_get_content($region = NULL, $delimiter = ' ') {
  48. $content = drupal_set_content();
  49. if (isset($region)) {
  50. if (isset($content[$region]) && is_array($content[$region])) {
  51. return implode($delimiter, $content[$region]);
  52. }
  53. }
  54. else {
  55. foreach (array_keys($content) as $region) {
  56. if (is_array($content[$region])) {
  57. $content[$region] = implode($delimiter, $content[$region]);
  58. }
  59. }
  60. return $content;
  61. }
  62. }
  63. /**
  64. * Set the breadcrumb trail for the current page.
  65. *
  66. * @param $breadcrumb
  67. * Array of links, starting with "home" and proceeding up to but not including
  68. * the current page.
  69. */
  70. function drupal_set_breadcrumb($breadcrumb = NULL) {
  71. static $stored_breadcrumb;
  72. if (!is_null($breadcrumb)) {
  73. $stored_breadcrumb = $breadcrumb;
  74. }
  75. return $stored_breadcrumb;
  76. }
  77. /**
  78. * Get the breadcrumb trail for the current page.
  79. */
  80. function drupal_get_breadcrumb() {
  81. $breadcrumb = drupal_set_breadcrumb();
  82. if (is_null($breadcrumb)) {
  83. $breadcrumb = menu_get_active_breadcrumb();
  84. }
  85. return $breadcrumb;
  86. }
  87. /**
  88. * Add output to the head tag of the HTML page.
  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. * The 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)) {
  153. $stored_feed_links[$url] = theme('feed_icon', $url);
  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. * The 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 nested items.
  183. * @param $parent
  184. * Should not be passed, only used in recursive calls
  185. * @return
  186. * urlencoded string which can be appended to/as the URL query string
  187. */
  188. function drupal_query_string_encode($query, $exclude = array(), $parent = '') {
  189. $params = array();
  190. foreach ($query as $key => $value) {
  191. $key = drupal_urlencode($key);
  192. if ($parent) {
  193. $key = $parent .'['. $key .']';
  194. }
  195. if (in_array($key, $exclude)) {
  196. continue;
  197. }
  198. if (is_array($value)) {
  199. $params[] = drupal_query_string_encode($value, $exclude, $key);
  200. }
  201. else {
  202. $params[] = $key .'='. drupal_urlencode($value);
  203. }
  204. }
  205. return implode('&', $params);
  206. }
  207. /**
  208. * Prepare a destination query string for use in combination with
  209. * drupal_goto(). Used to direct the user back to the referring page
  210. * after completing a form. By default the current URL is returned.
  211. * If a destination exists in the previous request, that destination
  212. * is returned. As such, a destination can persist across multiple
  213. * pages.
  214. *
  215. * @see drupal_goto()
  216. */
  217. function drupal_get_destination() {
  218. if (isset($_REQUEST['destination'])) {
  219. return 'destination='. urlencode($_REQUEST['destination']);
  220. }
  221. else {
  222. // Use $_GET here to retrieve the original path in source form.
  223. $path = isset($_GET['q']) ? $_GET['q'] : '';
  224. $query = drupal_query_string_encode($_GET, array('q'));
  225. if ($query != '') {
  226. $path .= '?'. $query;
  227. }
  228. return 'destination='. urlencode($path);
  229. }
  230. }
  231. /**
  232. * Send the user to a different Drupal page.
  233. *
  234. * This issues an on-site HTTP redirect. The function makes sure the redirected
  235. * URL is formatted correctly.
  236. *
  237. * Usually the redirected URL is constructed from this function's input
  238. * parameters. However you may override that behavior by setting a
  239. * <em>destination</em> in either the $_REQUEST-array (i.e. by using
  240. * the query string of an URI) or the $_REQUEST['edit']-array (i.e. by
  241. * using a hidden form field). This is used to direct the user back to
  242. * the proper page after completing a form. For example, after editing
  243. * a post on the 'admin/content/node'-page or after having logged on using the
  244. * 'user login'-block in a sidebar. The function drupal_get_destination()
  245. * can be used to help set the destination URL.
  246. *
  247. * Drupal will ensure that messages set by drupal_set_message() and other
  248. * session data are written to the database before the user is redirected.
  249. *
  250. * This function ends the request; use it rather than a print theme('page')
  251. * statement in your menu callback.
  252. *
  253. * @param $path
  254. * A Drupal path or a full URL.
  255. * @param $query
  256. * The query string component, if any.
  257. * @param $fragment
  258. * The destination fragment identifier (named anchor).
  259. * @param $http_response_code
  260. * Valid values for an actual "goto" as per RFC 2616 section 10.3 are:
  261. * - 301 Moved Permanently (the recommended value for most redirects)
  262. * - 302 Found (default in Drupal and PHP, sometimes used for spamming search
  263. * engines)
  264. * - 303 See Other
  265. * - 304 Not Modified
  266. * - 305 Use Proxy
  267. * - 307 Temporary Redirect (an alternative to "503 Site Down for Maintenance")
  268. * Note: Other values are defined by RFC 2616, but are rarely used and poorly
  269. * supported.
  270. * @see drupal_get_destination()
  271. */
  272. function drupal_goto($path = '', $query = NULL, $fragment = NULL, $http_response_code = 302) {
  273. $destination = FALSE;
  274. if (isset($_REQUEST['destination'])) {
  275. $destination = $_REQUEST['destination'];
  276. }
  277. else if (isset($_REQUEST['edit']['destination'])) {
  278. $destination = $_REQUEST['edit']['destination'];
  279. }
  280. if ($destination) {
  281. // Do not redirect to an absolute URL originating from user input.
  282. $colonpos = strpos($destination, ':');
  283. $absolute = ($colonpos !== FALSE && !preg_match('![/?#]!', substr($destination, 0, $colonpos)));
  284. if (!$absolute) {
  285. extract(parse_url(urldecode($destination)));
  286. }
  287. }
  288. $url = url($path, $query, $fragment, TRUE);
  289. // Remove newlines from the URL to avoid header injection attacks.
  290. $url = str_replace(array("\n", "\r"), '', $url);
  291. // Before the redirect, allow modules to react to the end of the page request.
  292. module_invoke_all('exit', $url);
  293. // Even though session_write_close() is registered as a shutdown function, we
  294. // need all session data written to the database before redirecting.
  295. session_write_close();
  296. header('Location: '. $url, TRUE, $http_response_code);
  297. // The "Location" header sends a REDIRECT status code to the http
  298. // daemon. In some cases this can go wrong, so we make sure none
  299. // of the code below the drupal_goto() call gets executed when we redirect.
  300. exit();
  301. }
  302. /**
  303. * Generates a site off-line message
  304. */
  305. function drupal_site_offline() {
  306. drupal_set_header('HTTP/1.1 503 Service unavailable');
  307. drupal_set_title(t('Site off-line'));
  308. print theme('maintenance_page', filter_xss_admin(variable_get('site_offline_message',
  309. t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal'))))));
  310. }
  311. /**
  312. * Generates a 404 error if the request can not be handled.
  313. */
  314. function drupal_not_found() {
  315. drupal_set_header('HTTP/1.1 404 Not Found');
  316. watchdog('page not found', check_plain($_GET['q']), WATCHDOG_WARNING);
  317. // Keep old path for reference
  318. if (!isset($_REQUEST['destination'])) {
  319. $_REQUEST['destination'] = $_GET['q'];
  320. }
  321. $path = drupal_get_normal_path(variable_get('site_404', ''));
  322. if ($path && $path != $_GET['q']) {
  323. menu_set_active_item($path);
  324. $return = menu_execute_active_handler();
  325. }
  326. else {
  327. // Redirect to a non-existent menu item to make possible tabs disappear.
  328. menu_set_active_item('');
  329. }
  330. if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
  331. drupal_set_title(t('Page not found'));
  332. menu_set_active_item('');
  333. $return = '';
  334. }
  335. // To conserve CPU and bandwidth, omit the blocks
  336. print theme('page', $return, FALSE);
  337. }
  338. /**
  339. * Generates a 403 error if the request is not allowed.
  340. */
  341. function drupal_access_denied() {
  342. drupal_set_header('HTTP/1.1 403 Forbidden');
  343. watchdog('access denied', check_plain($_GET['q']), WATCHDOG_WARNING);
  344. // Keep old path for reference
  345. if (!isset($_REQUEST['destination'])) {
  346. $_REQUEST['destination'] = $_GET['q'];
  347. }
  348. $path = drupal_get_normal_path(variable_get('site_403', ''));
  349. if ($path && $path != $_GET['q']) {
  350. menu_set_active_item($path);
  351. $return = menu_execute_active_handler();
  352. }
  353. else {
  354. // Redirect to a non-existent menu item to make possible tabs disappear.
  355. menu_set_active_item('');
  356. }
  357. if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
  358. drupal_set_title(t('Access denied'));
  359. menu_set_active_item('');
  360. $return = t('You are not authorized to access this page.');
  361. }
  362. print theme('page', $return);
  363. }
  364. /**
  365. * Perform an HTTP request.
  366. *
  367. * This is a flexible and powerful HTTP client implementation. Correctly handles
  368. * GET, POST, PUT or any other HTTP requests. Handles redirects.
  369. *
  370. * @param $url
  371. * A string containing a fully qualified URI.
  372. * @param $headers
  373. * An array containing an HTTP header => value pair.
  374. * @param $method
  375. * A string defining the HTTP request to use.
  376. * @param $data
  377. * A string containing data to include in the request.
  378. * @param $retry
  379. * An integer representing how many times to retry the request in case of a
  380. * redirect.
  381. * @return
  382. * An object containing the HTTP request headers, response code, headers,
  383. * data, and redirect status.
  384. */
  385. function drupal_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) {
  386. $result = new stdClass();
  387. // Parse the URL, and make sure we can handle the schema.
  388. $uri = parse_url($url);
  389. if ($uri == FALSE) {
  390. $result->error = 'unable to parse URL';
  391. $result->code = -1001;
  392. return $result;
  393. }
  394. if (!isset($uri['scheme'])) {
  395. $result->error = 'missing schema';
  396. $result->code = -1002;
  397. return $result;
  398. }
  399. switch ($uri['scheme']) {
  400. case 'http':
  401. $port = isset($uri['port']) ? $uri['port'] : 80;
  402. $host = $uri['host'] . ($port != 80 ? ':'. $port : '');
  403. $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
  404. break;
  405. case 'https':
  406. // Note: Only works for PHP 4.3 compiled with OpenSSL.
  407. $port = isset($uri['port']) ? $uri['port'] : 443;
  408. $host = $uri['host'] . ($port != 443 ? ':'. $port : '');
  409. $fp = @fsockopen('ssl://'. $uri['host'], $port, $errno, $errstr, 20);
  410. break;
  411. default:
  412. $result->error = 'invalid schema '. $uri['scheme'];
  413. $result->code = -1003;
  414. return $result;
  415. }
  416. // Make sure the socket opened properly.
  417. if (!$fp) {
  418. $result->error = trim($errno .' '. $errstr);
  419. $result->code = -$errno;
  420. return $result;
  421. }
  422. // Construct the path to act on.
  423. $path = isset($uri['path']) ? $uri['path'] : '/';
  424. if (isset($uri['query'])) {
  425. $path .= '?'. $uri['query'];
  426. }
  427. // Create HTTP request.
  428. $defaults = array(
  429. // RFC 2616: "non-standard ports MUST, default ports MAY be included".
  430. // We don't add the port to prevent from breaking rewrite rules checking
  431. // the host that do not take into account the port number.
  432. 'Host' => "Host: $host",
  433. 'User-Agent' => 'User-Agent: Drupal (+http://drupal.org/)',
  434. 'Content-Length' => 'Content-Length: '. strlen($data)
  435. );
  436. // If the server url has a user then attempt to use basic authentication
  437. if (isset($uri['user'])) {
  438. $defaults['Authorization'] = 'Authorization: Basic '. base64_encode($uri['user'] . (!empty($uri['pass']) ? ":". $uri['pass'] : ''));
  439. }
  440. foreach ($headers as $header => $value) {
  441. $defaults[$header] = $header .': '. $value;
  442. }
  443. $request = $method .' '. $path ." HTTP/1.0\r\n";
  444. $request .= implode("\r\n", $defaults);
  445. $request .= "\r\n\r\n";
  446. if ($data) {
  447. $request .= $data ."\r\n";
  448. }
  449. $result->request = $request;
  450. fwrite($fp, $request);
  451. // Fetch response.
  452. $response = '';
  453. while (!feof($fp) && $chunk = fread($fp, 1024)) {
  454. $response .= $chunk;
  455. }
  456. fclose($fp);
  457. // Parse response.
  458. list($split, $result->data) = explode("\r\n\r\n", $response, 2);
  459. $split = preg_split("/\r\n|\n|\r/", $split);
  460. list($protocol, $code, $text) = explode(' ', trim(array_shift($split)), 3);
  461. $result->headers = array();
  462. // Parse headers.
  463. while ($line = trim(array_shift($split))) {
  464. list($header, $value) = explode(':', $line, 2);
  465. if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
  466. // RFC 2109: the Set-Cookie response header comprises the token Set-
  467. // Cookie:, followed by a comma-separated list of one or more cookies.
  468. $result->headers[$header] .= ','. trim($value);
  469. }
  470. else {
  471. $result->headers[$header] = trim($value);
  472. }
  473. }
  474. $responses = array(
  475. 100 => 'Continue', 101 => 'Switching Protocols',
  476. 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
  477. 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
  478. 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',
  479. 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'
  480. );
  481. // RFC 2616 states that all unknown HTTP codes must be treated the same as
  482. // the base code in their class.
  483. if (!isset($responses[$code])) {
  484. $code = floor($code / 100) * 100;
  485. }
  486. switch ($code) {
  487. case 200: // OK
  488. case 304: // Not modified
  489. break;
  490. case 301: // Moved permanently
  491. case 302: // Moved temporarily
  492. case 307: // Moved temporarily
  493. $location = $result->headers['Location'];
  494. if ($retry) {
  495. $result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
  496. $result->redirect_code = $result->code;
  497. }
  498. $result->redirect_url = $location;
  499. break;
  500. default:
  501. $result->error = $text;
  502. }
  503. $result->code = $code;
  504. return $result;
  505. }
  506. /**
  507. * @} End of "HTTP handling".
  508. */
  509. /**
  510. * Log errors as defined by administrator
  511. * Error levels:
  512. * 0 = Log errors to database.
  513. * 1 = Log errors to database and to screen.
  514. */
  515. function error_handler($errno, $message, $filename, $line) {
  516. // If the @ error suppression operator was used, error_reporting is temporarily set to 0
  517. if (error_reporting() == 0) {
  518. return;
  519. }
  520. if ($errno & (E_ALL ^ E_NOTICE)) {
  521. $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');
  522. $entry = $types[$errno] .': '. $message .' in '. $filename .' on line '. $line .'.';
  523. // Force display of error messages in update.php
  524. if (variable_get('error_level', 1) == 1 || strstr($_SERVER['SCRIPT_NAME'], 'update.php')) {
  525. drupal_set_message($entry, 'error');
  526. }
  527. watchdog('php', t('%message in %file on line %line.', array('%error' => $types[$errno], '%message' => $message, '%file' => $filename, '%line' => $line)), WATCHDOG_ERROR);
  528. }
  529. }
  530. function _fix_gpc_magic(&$item) {
  531. if (is_array($item)) {
  532. array_walk($item, '_fix_gpc_magic');
  533. }
  534. else {
  535. $item = stripslashes($item);
  536. }
  537. }
  538. /**
  539. * Helper function to strip slashes from $_FILES skipping over the tmp_name keys
  540. * since PHP generates single backslashes for file paths on Windows systems.
  541. *
  542. * tmp_name does not have backslashes added see
  543. * http://php.net/manual/en/features.file-upload.php#42280
  544. */
  545. function _fix_gpc_magic_files(&$item, $key) {
  546. if ($key != 'tmp_name') {
  547. if (is_array($item)) {
  548. array_walk($item, '_fix_gpc_magic_files');
  549. }
  550. else {
  551. $item = stripslashes($item);
  552. }
  553. }
  554. }
  555. /**
  556. * Correct double-escaping problems caused by "magic quotes" in some PHP
  557. * installations.
  558. */
  559. function fix_gpc_magic() {
  560. static $fixed = FALSE;
  561. if (!$fixed && ini_get('magic_quotes_gpc')) {
  562. array_walk($_GET, '_fix_gpc_magic');
  563. array_walk($_POST, '_fix_gpc_magic');
  564. array_walk($_COOKIE, '_fix_gpc_magic');
  565. array_walk($_REQUEST, '_fix_gpc_magic');
  566. array_walk($_FILES, '_fix_gpc_magic_files');
  567. $fixed = TRUE;
  568. }
  569. }
  570. /**
  571. * Initialize the localization system.
  572. */
  573. function locale_initialize() {
  574. global $user;
  575. if (function_exists('i18n_get_lang')) {
  576. return i18n_get_lang();
  577. }
  578. if (function_exists('locale')) {
  579. $languages = locale_supported_languages();
  580. $languages = $languages['name'];
  581. }
  582. else {
  583. // Ensure the locale/language is correctly returned, even without locale.module.
  584. // Useful for e.g. XML/HTML 'lang' attributes.
  585. $languages = array('en' => 'English');
  586. }
  587. if ($user->uid && isset($languages[$user->language])) {
  588. return $user->language;
  589. }
  590. else {
  591. return key($languages);
  592. }
  593. }
  594. /**
  595. * Translate strings to the current locale.
  596. *
  597. * Human-readable text that will be displayed somewhere within a page should
  598. * be run through the t() function.
  599. *
  600. * Examples:
  601. * @code
  602. * if (!$info || !$info['extension']) {
  603. * form_set_error('picture_upload', t('The uploaded file was not an image.'));
  604. * }
  605. *
  606. * $form['submit'] = array(
  607. * '#type' => 'submit',
  608. * '#value' => t('Log in'),
  609. * );
  610. * @endcode
  611. *
  612. * Any text within t() can be extracted by translators and changed into
  613. * the equivalent text in their native language.
  614. *
  615. * Special variables called "placeholders" are used to signal dynamic
  616. * information in a string which should not be translated. Placeholders
  617. * can also be used for text that may change from time to time
  618. * (such as link paths) to be changed without requiring updates to translations.
  619. *
  620. * For example:
  621. * @code
  622. * $output = t('There are currently %members and %visitors online.', array(
  623. * '%members' => format_plural($total_users, '1 user', '@count users'),
  624. * '%visitors' => format_plural($guests->count, '1 guest', '@count guests')));
  625. * @endcode
  626. *
  627. * There are three styles of placeholders:
  628. * - !variable, which indicates that the text should be inserted as-is. This is
  629. * useful for inserting variables into things like e-mail.
  630. * @code
  631. * $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", NULL, NULL, TRUE)));
  632. * @endcode
  633. *
  634. * - @variable, which indicates that the text should be run through
  635. * check_plain, to escape HTML characters. Use this for any output that's
  636. * displayed within a Drupal page.
  637. * @code
  638. * drupal_set_title($title = t("@name's blog", array('@name' => $account->name)));
  639. * @endcode
  640. *
  641. * - %variable, which indicates that the string should be HTML escaped and
  642. * highlighted with theme_placeholder() which shows up by default as
  643. * <em>emphasized</em>.
  644. * @code
  645. * $message = t('%name-from sent %name-to an e-mail.', array('%name-from' => $user->name, '%name-to' => $account->name));
  646. * @endcode
  647. *
  648. * When using t(), try to put entire sentences and strings in one t() call.
  649. * This makes it easier for translators, as it provides context as to what
  650. * each word refers to. HTML markup within translation strings is allowed, but
  651. * should be avoided if possible. The exception are embedded links; link
  652. * titles add a context for translators, so should be kept in the main string.
  653. *
  654. * Here is an example of incorrect usage of t():
  655. * @code
  656. * $output .= t('<p>Go to the @contact-page.</p>', array('@contact-page' => l(t('contact page'), 'contact')));
  657. * @endcode
  658. *
  659. * Here is an example of t() used correctly:
  660. * @code
  661. * $output .= '<p>'. t('Go to the <a href="@contact-page">contact page</a>.', array('@contact-page' => url('contact'))) .'</p>';
  662. * @endcode
  663. *
  664. * Avoid escaping quotation marks wherever possible.
  665. *
  666. * Incorrect:
  667. * @code
  668. * $output .= t('Don\'t click me.');
  669. * @endcode
  670. *
  671. * Correct:
  672. * @code
  673. * $output .= t("Don't click me.");
  674. * @endcode
  675. *
  676. * Because t() is designed for handling code-based strings, in almost all
  677. * cases, the actual string and not a variable must be passed through t().
  678. *
  679. * Extraction of translations is done based on the strings contained in t()
  680. * calls. If a variable is passed through t(), the content of the variable
  681. * cannot be extracted from the file for translation.
  682. *
  683. * Incorrect:
  684. * @code
  685. * $message = 'An error occurred.';
  686. * drupal_set_message(t($message), 'error');
  687. * $output .= t($message);
  688. * @endcode
  689. *
  690. * Correct:
  691. * @code
  692. * $message = t('An error occurred.');
  693. * drupal_set_message($message, 'error');
  694. * $output .= $message;
  695. * @endcode
  696. *
  697. * The only case in which variables can be passed safely through t() is when
  698. * code-based versions of the same strings will be passed through t() (or
  699. * otherwise extracted) elsewhere.
  700. *
  701. * In some cases, modules may include strings in code that can't use t()
  702. * calls. For example, a module may use an external PHP application that
  703. * produces strings that are loaded into variables in Drupal for output.
  704. * In these cases, module authors may include a dummy file that passes the
  705. * relevant strings through t(). This approach will allow the strings to be
  706. * extracted.
  707. *
  708. * Sample external (non-Drupal) code:
  709. * @code
  710. * class Time {
  711. * public $yesterday = 'Yesterday';
  712. * public $today = 'Today';
  713. * public $tomorrow = 'Tomorrow';
  714. * }
  715. * @endcode
  716. *
  717. * Sample dummy file.
  718. * @code
  719. * // Dummy function included in example.potx.inc.
  720. * function example_potx() {
  721. * $strings = array(
  722. * t('Yesterday'),
  723. * t('Today'),
  724. * t('Tomorrow'),
  725. * );
  726. * // No return value needed, since this is a dummy function.
  727. * }
  728. * @endcode
  729. *
  730. * Having passed strings through t() in a dummy function, it is then
  731. * okay to pass variables through t().
  732. *
  733. * Correct (if a dummy file was used):
  734. * @code
  735. * $time = new Time();
  736. * $output .= t($time->today);
  737. * @endcode
  738. *
  739. * However tempting it is, custom data from user input or other non-code
  740. * sources should not be passed through t(). Doing so leads to the following
  741. * problems and errors:
  742. * - The t() system doesn't support updates to existing strings. When user
  743. * data is updated, the next time it's passed through t() a new record is
  744. * created instead of an update. The database bloats over time and any
  745. * existing translations are orphaned with each update.
  746. * - The t() system assumes any data it receives is in English. User data may
  747. * be in another language, producing translation errors.
  748. * - The "Built-in interface" text group in the locale system is used to
  749. * produce translations for storage in .po files. When non-code strings are
  750. * passed through t(), they are added to this text group, which is rendered
  751. * inaccurate since it is a mix of actual interface strings and various user
  752. * input strings of uncertain origin.
  753. *
  754. * Incorrect:
  755. * @code
  756. * $item = item_load();
  757. * $output .= check_plain(t($item['title']));
  758. * @endcode
  759. *
  760. * Instead, translation of these data can be done through the locale system,
  761. * either directly or through helper functions provided by contributed
  762. * modules.
  763. * @see hook_locale()
  764. *
  765. * During installation, st() is used in place of t(). Code that may be called
  766. * during installation or during normal operation should use the get_t()
  767. * helper function.
  768. * @see st()
  769. * @see get_t()
  770. *
  771. * @param $string
  772. * A string containing the English string to translate.
  773. * @param $args
  774. * An associative array of replacements to make after translation. Incidences
  775. * of any key in this array are replaced with the corresponding value.
  776. * Based on the first character of the key, the value is escaped and/or themed:
  777. * - !variable: inserted as is
  778. * - @variable: escape plain text to HTML (check_plain)
  779. * - %variable: escape text and theme as a placeholder for user-submitted
  780. * content (check_plain + theme_placeholder)
  781. * @return
  782. * The translated string.
  783. */
  784. function t($string, $args = 0) {
  785. global $locale;
  786. if (function_exists('locale') && $locale != 'en') {
  787. $string = locale($string);
  788. }
  789. if (!$args) {
  790. return $string;
  791. }
  792. else {
  793. // Transform arguments before inserting them
  794. foreach ($args as $key => $value) {
  795. switch ($key[0]) {
  796. // Escaped only
  797. case '@':
  798. $args[$key] = check_plain($value);
  799. break;
  800. // Escaped and placeholder
  801. case '%':
  802. default:
  803. $args[$key] = theme('placeholder', $value);
  804. break;
  805. // Pass-through
  806. case '!':
  807. }
  808. }
  809. return strtr($string, $args);
  810. }
  811. }
  812. /**
  813. * @defgroup validation Input validation
  814. * @{
  815. * Functions to validate user input.
  816. */
  817. /**
  818. * Verify the syntax of the given e-mail address.
  819. *
  820. * Empty e-mail addresses are allowed. See RFC 2822 for details.
  821. *
  822. * @param $mail
  823. * A string containing an e-mail address.
  824. * @return
  825. * TRUE if the address is in a valid format.
  826. */
  827. function valid_email_address($mail) {
  828. $user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
  829. $domain = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+';
  830. $ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
  831. $ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';
  832. return preg_match("/^$user@($domain|(\[($ipv4|$ipv6)\]))$/", $mail);
  833. }
  834. /**
  835. * Verify the syntax of the given URL.
  836. *
  837. * This function should only be used on actual URLs. It should not be used for
  838. * Drupal menu paths, which can contain arbitrary characters.
  839. * Valid values per RFC 3986.
  840. * @param $url
  841. * The URL to verify.
  842. * @param $absolute
  843. * Whether the URL is absolute (beginning with a scheme such as "http:").
  844. * @return
  845. * TRUE if the URL is in a valid format.
  846. */
  847. function valid_url($url, $absolute = FALSE) {
  848. if ($absolute) {
  849. return (bool)preg_match("
  850. /^ # Start at the beginning of the text
  851. (?:ftp|https?):\/\/ # Look for ftp, http, or https schemes
  852. (?: # Userinfo (optional) which is typically
  853. (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
  854. (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
  855. )?
  856. (?:
  857. (?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
  858. |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
  859. )
  860. (?::[0-9]+)? # Server port number (optional)
  861. (?:[\/|\?]
  862. (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
  863. *)?
  864. $/xi", $url);
  865. }
  866. else {
  867. return (bool)preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url);
  868. }
  869. }
  870. /**
  871. * Register an event for the current visitor (hostname/IP) to the flood control mechanism.
  872. *
  873. * @param $name
  874. * The name of the event.
  875. */
  876. function flood_register_event($name) {
  877. db_query("INSERT INTO {flood} (event, hostname, timestamp) VALUES ('%s', '%s', %d)", $name, $_SERVER['REMOTE_ADDR'], time());
  878. }
  879. /**
  880. * Check if the current visitor (hostname/IP) is allowed to proceed with the specified event.
  881. * The user is allowed to proceed if he did not trigger the specified event more than
  882. * $threshold times per hour.
  883. *
  884. * @param $name
  885. * The name of the event.
  886. * @param $number
  887. * The maximum number of the specified event per hour (per visitor).
  888. * @return
  889. * True if the user did not exceed the hourly threshold. False otherwise.
  890. */
  891. function flood_is_allowed($name, $threshold) {
  892. $number = db_num_rows(db_query("SELECT event FROM {flood} WHERE event = '%s' AND hostname = '%s' AND timestamp > %d", $name, $_SERVER['REMOTE_ADDR'], time() - 3600));
  893. return ($number < $threshold ? TRUE : FALSE);
  894. }
  895. function check_file($filename) {
  896. return is_uploaded_file($filename);
  897. }
  898. /**
  899. * Prepare a URL for use in an HTML attribute. Strips harmful protocols.
  900. *
  901. */
  902. function check_url($uri) {
  903. return filter_xss_bad_protocol($uri, FALSE);
  904. }
  905. /**
  906. * @defgroup format Formatting
  907. * @{
  908. * Functions to format numbers, strings, dates, etc.
  909. */
  910. /**
  911. * Formats an RSS channel.
  912. *
  913. * Arbitrary elements may be added using the $args associative array.
  914. */
  915. function format_rss_channel($title, $link, $description, $items, $language = 'en', $args = array()) {
  916. // arbitrary elements may be added using the $args associative array
  917. $output = "<channel>\n";
  918. $output .= ' <title>'. check_plain($title) ."</title>\n";
  919. $output .= ' <link>'. check_url($link) ."</link>\n";
  920. // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
  921. // We strip all HTML tags, but need to prevent double encoding from properly
  922. // escaped source data (such as &amp becoming &amp;amp;).
  923. $output .= ' <description>'. check_plain(decode_entities(strip_tags($description))) ."</description>\n";
  924. $output .= ' <language>'. check_plain($language) ."</language>\n";
  925. $output .= format_xml_elements($args);
  926. $output .= $items;
  927. $output .= "</channel>\n";
  928. return $output;
  929. }
  930. /**
  931. * Format a single RSS item.
  932. *
  933. * Arbitrary elements may be added using the $args associative array.
  934. */
  935. function format_rss_item($title, $link, $description, $args = array()) {
  936. $output = "<item>\n";
  937. $output .= ' <title>'. check_plain($title) ."</title>\n";
  938. $output .= ' <link>'. check_url($link) ."</link>\n";
  939. $output .= ' <description>'. check_plain($description) ."</description>\n";
  940. $output .= format_xml_elements($args);
  941. $output .= "</item>\n";
  942. return $output;
  943. }
  944. /**
  945. * Format XML elements.
  946. *
  947. * @param $array
  948. * An array where each item represent an element and is either a:
  949. * - (key => value) pair (<key>value</key>)
  950. * - Associative array with fields:
  951. * - 'key': element name
  952. * - 'value': element contents
  953. * - 'attributes': associative array of element attributes
  954. *
  955. * In both cases, 'value' can be a simple string, or it can be another array
  956. * with the same format as $array itself for nesting.
  957. */
  958. function format_xml_elements($array) {
  959. foreach ($array as $key => $value) {
  960. if (is_numeric($key)) {
  961. if ($value['key']) {
  962. $output .= ' <'. $value['key'];
  963. if (isset($value['attributes']) && is_array($value['attributes'])) {
  964. $output .= drupal_attributes($value['attributes']);
  965. }
  966. if ($value['value'] != '') {
  967. $output .= '>'. (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) .'</'. $value['key'] .">\n";
  968. }
  969. else {
  970. $output .= " />\n";
  971. }
  972. }
  973. }
  974. else {
  975. $output .= ' <'. $key .'>'. (is_array($value) ? format_xml_elements($value) : check_plain($value)) ."</$key>\n";
  976. }
  977. }
  978. return $output;
  979. }
  980. /**
  981. * Format a string containing a count of items.
  982. *
  983. * This function ensures that the string is pluralized correctly. Since t() is
  984. * called by this function, make sure not to pass already-localized strings to it.
  985. *
  986. * @param $count
  987. * The item count to display.
  988. * @param $singular
  989. * The string for the singular case. Please make sure it is clear this is
  990. * singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
  991. * @param $plural
  992. * The string for the plural case. Please make sure it is clear this is plural,
  993. * to ease translation. Use @count in place of the item count, as in "@count
  994. * new comments".
  995. * @return
  996. * A translated string.
  997. */
  998. function format_plural($count, $singular, $plural) {
  999. if ($count == 1) return t($singular, array("@count" => $count));
  1000. // get the plural index through the gettext formula
  1001. $index = (function_exists('locale_get_plural')) ? locale_get_plural($count) : -1;
  1002. if ($index < 0) { // backward compatibility
  1003. return t($plural, array("@count" => $count));
  1004. }
  1005. else {
  1006. switch ($index) {
  1007. case "0":
  1008. return t($singular, array("@count" => $count));
  1009. case "1":
  1010. return t($plural, array("@count" => $count));
  1011. default:
  1012. return t(strtr($plural, array("@count" => '@count['. $index .']')), array('@count['. $index .']' => $count));
  1013. }
  1014. }
  1015. }
  1016. /**
  1017. * Parse a given byte count.
  1018. *
  1019. * @param $size
  1020. * The size expressed as a number of bytes with optional SI size and unit
  1021. * suffix (e.g. 2, 3K, 5MB, 10G).
  1022. * @return
  1023. * An integer representation of the size.
  1024. */
  1025. function parse_size($size) {
  1026. $suffixes = array(
  1027. '' => 1,
  1028. 'k' => 1024,
  1029. 'm' => 1048576, // 1024 * 1024
  1030. 'g' => 1073741824, // 1024 * 1024 * 1024
  1031. );
  1032. if (preg_match('/([0-9]+)\s*(k|m|g)?(b?(ytes?)?)/i', $size, $match)) {
  1033. return $match[1] * $suffixes[drupal_strtolower($match[2])];
  1034. }
  1035. }
  1036. /**
  1037. * Generate a string representation for the given byte count.
  1038. *
  1039. * @param $size
  1040. * The size in bytes.
  1041. * @return
  1042. * A translated string representation of the size.
  1043. */
  1044. function format_size($size) {
  1045. if ($size < 1024) {
  1046. return format_plural($size, '1 byte', '@count bytes');
  1047. }
  1048. else {
  1049. $size = round($size / 1024, 2);
  1050. $suffix = t('KB');
  1051. if ($size >= 1024) {
  1052. $size = round($size / 1024, 2);
  1053. $suffix = t('MB');
  1054. }
  1055. return t('@size @suffix', array('@size' => $size, '@suffix' => $suffix));
  1056. }
  1057. }
  1058. /**
  1059. * Format a time interval with the requested granularity.
  1060. *
  1061. * @param $timestamp
  1062. * The length of the interval in seconds.
  1063. * @param $granularity
  1064. * How many different units to display in the string.
  1065. * @return
  1066. * A translated string representation of the interval.
  1067. */
  1068. function format_interval($timestamp, $granularity = 2) {
  1069. $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);
  1070. $output = '';
  1071. foreach ($units as $key => $value) {
  1072. $key = explode('|', $key);
  1073. if ($timestamp >= $value) {
  1074. $output .= ($output ? ' ' : '') . format_plural(floor($timestamp / $value), $key[0], $key[1]);
  1075. $timestamp %= $value;
  1076. $granularity--;
  1077. }
  1078. if ($granularity == 0) {
  1079. break;
  1080. }
  1081. }
  1082. return $output ? $output : t('0 sec');
  1083. }
  1084. /**
  1085. * Format a date with the given configured format or a custom format string.
  1086. *
  1087. * Drupal allows administrators to select formatting strings for 'small',
  1088. * 'medium' and 'large' date formats. This function can handle these formats,
  1089. * as well as any custom format.
  1090. *
  1091. * @param $timestamp
  1092. * The exact date to format, as a UNIX timestamp.
  1093. * @param $type
  1094. * The format to use. Can be "small", "medium" or "large" for the preconfigured
  1095. * date formats. If "custom" is specified, then $format is required as well.
  1096. * @param $format
  1097. * A PHP date format string as required by date(). A backslash should be used
  1098. * before a character to avoid interpreting the character as part of a date
  1099. * format.
  1100. * @param $timezone
  1101. * Time zone offset in seconds; if omitted, the user's time zone is used.
  1102. * @return
  1103. * A translated date string in the requested format.
  1104. */
  1105. function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL) {
  1106. if (!isset($timezone)) {
  1107. global $user;
  1108. if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
  1109. $timezone = $user->timezone;
  1110. }
  1111. else {
  1112. $timezone = variable_get('date_default_timezone', 0);
  1113. }
  1114. }
  1115. $timestamp += $timezone;
  1116. switch ($type) {
  1117. case 'small':
  1118. $format = variable_get('date_format_short', 'm/d/Y - H:i');
  1119. break;
  1120. case 'large':
  1121. $format = variable_get('date_format_long', 'l, F j, Y - H:i');
  1122. break;
  1123. case 'custom':
  1124. // No change to format
  1125. break;
  1126. case 'medium':
  1127. default:
  1128. $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
  1129. }
  1130. $max = strlen($format);
  1131. $date = '';
  1132. for ($i = 0; $i < $max; $i++) {
  1133. $c = $format[$i];
  1134. if (strpos('AaDFlM', $c) !== FALSE) {
  1135. $date .= t(gmdate($c, $timestamp));
  1136. }
  1137. else if (strpos('BdgGhHiIjLmnsStTUwWYyz', $c) !== FALSE) {
  1138. $date .= gmdate($c, $timestamp);
  1139. }
  1140. else if ($c == 'r') {
  1141. $date .= format_date($timestamp - $timezone, 'custom', 'D, d M Y H:i:s O', $timezone);
  1142. }
  1143. else if ($c == 'O') {
  1144. $date .= sprintf('%s%02d%02d', ($timezone < 0 ? '-' : '+'), abs($timezone / 3600), abs($timezone % 3600) / 60);
  1145. }
  1146. else if ($c == 'Z') {
  1147. $date .= $timezone;
  1148. }
  1149. else if ($c == '\\') {
  1150. $date .= $format[++$i];
  1151. }
  1152. else {
  1153. $date .= $c;
  1154. }
  1155. }
  1156. return $date;
  1157. }
  1158. /**
  1159. * @} End of "defgroup format".
  1160. */
  1161. /**
  1162. * Generate a URL from a Drupal menu path. Will also pass-through existing URLs.
  1163. *
  1164. * @param $path
  1165. * The Drupal path being linked to, such as "admin/content/node", or an existing URL
  1166. * like "http://drupal.org/".
  1167. * @param $query
  1168. * A query string to append to the link or URL.
  1169. * @param $fragment
  1170. * A fragment identifier (named anchor) to append to the link. If an existing
  1171. * URL with a fragment identifier is used, it will be replaced. Note, do not
  1172. * include the '#'.
  1173. * @param $absolute
  1174. * Whether to force the output to be an absolute link (beginning with http:).
  1175. * Useful for links that will be displayed outside the site, such as in an
  1176. * RSS feed.
  1177. * @return
  1178. * a string containing a URL to the given path.
  1179. *
  1180. * When creating links in modules, consider whether l() could be a better
  1181. * alternative than url().
  1182. */
  1183. function url($path = NULL, $query = NULL, $fragment = NULL, $absolute = FALSE) {
  1184. if (isset($fragment)) {
  1185. $fragment = '#'. $fragment;
  1186. }
  1187. // Return an external link if $path contains an allowed absolute URL.
  1188. // Only call the slow filter_xss_bad_protocol if $path contains a ':' before any / ? or #.
  1189. $colonpos = strpos($path, ':');
  1190. if ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && filter_xss_bad_protocol($path, FALSE) == check_plain($path)) {
  1191. // Split off the fragment
  1192. if (strpos($path, '#') !== FALSE) {
  1193. list($path, $old_fragment) = explode('#', $path, 2);
  1194. if (isset($old_fragment) && !isset($fragment)) {
  1195. $fragment = '#'. $old_fragment;
  1196. }
  1197. }
  1198. // Append the query
  1199. if (isset($query)) {
  1200. $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . $query;
  1201. }
  1202. // Reassemble
  1203. return $path . $fragment;
  1204. }
  1205. global $base_url;
  1206. static $script;
  1207. static $clean_url;
  1208. if (!isset($script)) {
  1209. // On some web servers, such as IIS, we can't omit "index.php". So, we
  1210. // generate "index.php?q=foo" instead of "?q=foo" on anything that is not
  1211. // Apache.
  1212. $script = (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') === FALSE) ? 'index.php' : '';
  1213. }
  1214. // Cache the clean_url variable to improve performance.
  1215. if (!isset($clean_url)) {
  1216. $clean_url = (bool)variable_get('clean_url', '0');
  1217. }
  1218. $base = ($absolute ? $base_url . '/' : base_path());
  1219. // The special path '<front>' links to the default front page.
  1220. if (!empty($path) && $path != '<front>') {
  1221. $path = drupal_get_path_alias($path);
  1222. $path = drupal_urlencode($path);
  1223. if (!$clean_url) {
  1224. if (isset($query)) {
  1225. return $base . $script .'?q='. $path .'&'. $query . $fragment;
  1226. }
  1227. else {
  1228. return $base . $script .'?q='. $path . $fragment;
  1229. }
  1230. }
  1231. else {
  1232. if (isset($query)) {
  1233. return $base . $path .'?'. $query . $fragment;
  1234. }
  1235. else {
  1236. return $base . $path . $fragment;
  1237. }
  1238. }
  1239. }
  1240. else {
  1241. if (isset($query)) {
  1242. return $base . $script .'?'. $query . $fragment;
  1243. }
  1244. else {
  1245. return $base . $fragment;
  1246. }
  1247. }
  1248. }
  1249. /**
  1250. * Format an attribute string to insert in a tag.
  1251. *
  1252. * @param $attributes
  1253. * An associative array of HTML attributes.
  1254. * @return
  1255. * An HTML string ready for insertion in a tag.
  1256. */
  1257. function drupal_attributes($attributes = array()) {
  1258. if (is_array($attributes)) {
  1259. $t = '';
  1260. foreach ($attributes as $key => $value) {
  1261. $t .= " $key=".'"'. check_plain($value) .'"';
  1262. }
  1263. return $t;
  1264. }
  1265. }
  1266. /**
  1267. * Format an internal Drupal link.
  1268. *
  1269. * This function correctly handles aliased paths, and allows themes to highlight
  1270. * links to the current page correctly, so all internal links output by modules
  1271. * should be generated by this function if possible.
  1272. *
  1273. * @param $text
  1274. * The text to be enclosed with the anchor tag.
  1275. * @param $path
  1276. * The Drupal path being linked to, such as "admin/content/node". Can be an external
  1277. * or internal URL.
  1278. * - If you provide the full URL, it will be considered an
  1279. * external URL.
  1280. * - If you provide only the path (e.g. "admin/content/node"), it is considered an
  1281. * internal link. In this case, it must be a system URL as the url() function
  1282. * will generate the alias.
  1283. * @param $attributes
  1284. * An associative array of HTML attributes to apply to the anchor tag.
  1285. * @param $query
  1286. * A query string to append to the link.
  1287. * @param $fragment
  1288. * A fragment identifier (named anchor) to append to the link.
  1289. * @param $absolute
  1290. * Whether to force the output to be an absolute link (beginning with http:).
  1291. * Useful for links that will be displayed outside the site, such as in an RSS
  1292. * feed.
  1293. * @param $html
  1294. * Whether the title is HTML, or just plain-text. For example for making an
  1295. * image a link, this must be set to TRUE, or else you will see the encoded
  1296. * HTML.
  1297. * @return
  1298. * an HTML string containing a link to the given path.
  1299. */
  1300. function l($text, $path, $attributes = array(), $query = NULL, $fragment = NULL, $absolute = FALSE, $html = FALSE) {
  1301. if (($path == $_GET['q']) || ($path == '<front>' && drupal_is_front_page())) {
  1302. if (isset($attributes['class'])) {
  1303. $attributes['class'] .= ' active';
  1304. }
  1305. else {
  1306. $attributes['class'] = 'active';
  1307. }
  1308. }
  1309. return '<a href="'. check_url(url($path, $query, $fragment, $absolute)) .'"'. drupal_attributes($attributes) .'>'. ($html ? $text : check_plain($text)) .'</a>';
  1310. }
  1311. /**
  1312. * Perform end-of-request tasks.
  1313. *
  1314. * This function sets the page cache if appropriate, and allows modules to
  1315. * react to the closing of the page by calling hook_exit().
  1316. */
  1317. function drupal_page_footer() {
  1318. if (variable_get('cache', 0)) {
  1319. page_set_cache();
  1320. }
  1321. module_invoke_all('exit');
  1322. }
  1323. /**
  1324. * Form an associative array from a linear array.
  1325. *
  1326. * This function walks through the provided array and constructs an associative
  1327. * array out of it. The keys of the resulting array will be the values of the
  1328. * input array. The values will be the same as the keys unless a function is
  1329. * specified, in which case the output of the function is used for the values
  1330. * instead.
  1331. *
  1332. * @param $array
  1333. * A linear array.
  1334. * @param $function
  1335. * The name of a function to apply to all values before output.
  1336. * @result
  1337. * An associative array.
  1338. */
  1339. function drupal_map_assoc($array, $function = NULL) {
  1340. if (!isset($function)) {
  1341. $result = array();
  1342. foreach ($array as $value) {
  1343. $result[$value] = $value;
  1344. }
  1345. return $result;
  1346. }
  1347. elseif (function_exists($function)) {
  1348. $result = array();
  1349. foreach ($array as $value) {
  1350. $result[$value] = $function($value);
  1351. }
  1352. return $result;
  1353. }
  1354. }
  1355. /**
  1356. * Evaluate a string of PHP code.
  1357. *
  1358. * This is a wrapper around PHP's eval(). It uses output buffering to capture both
  1359. * returned and printed text. Unlike eval(), we require code to be surrounded by
  1360. * <?php ?> tags; in other words, we evaluate the code as if it were a stand-alone
  1361. * PHP file.
  1362. *
  1363. * Using this wrapper also ensures that the PHP code which is evaluated can not
  1364. * overwrite any variables in the calling code, unlike a regular eval() call.
  1365. *
  1366. * @param $code
  1367. * The code to evaluate.
  1368. * @return
  1369. * A string containing the printed output of the code, followed by the returned
  1370. * output of the code.
  1371. */
  1372. function drupal_eval($code) {
  1373. ob_start();
  1374. print eval('?>'. $code);
  1375. $output = ob_get_contents();
  1376. ob_end_clean();
  1377. return $output;
  1378. }
  1379. /**
  1380. * Returns the path to a system item (module, theme, etc.).
  1381. *
  1382. * @param $type
  1383. * The type of the item (i.e. theme, theme_engine, module).
  1384. * @param $name
  1385. * The name of the item for which the path is requested.
  1386. *
  1387. * @return
  1388. * The path to the requested item.
  1389. */
  1390. function drupal_get_path($type, $name) {
  1391. return dirname(drupal_get_filename($type, $name));
  1392. }
  1393. /**
  1394. * Returns the base URL path of the Drupal installation.
  1395. * At the very least, this will always default to /.
  1396. */
  1397. function base_path() {
  1398. return $GLOBALS['base_path'];
  1399. }
  1400. /**
  1401. * Provide a substitute clone() function for PHP4.
  1402. */
  1403. function drupal_clone($object) {
  1404. return version_compare(phpversion(), '5.0') < 0 ? $object : clone($object);
  1405. }
  1406. /**
  1407. * Add a <link> tag to the page's HEAD.
  1408. */
  1409. function drupal_add_link($attributes) {
  1410. drupal_set_html_head('<link'. drupal_attributes($attributes) ." />\n");
  1411. }
  1412. /**
  1413. * Adds a CSS file to the stylesheet queue.
  1414. *
  1415. * @param $path
  1416. * (optional) The path to the CSS file relative to the base_path(), e.g.,
  1417. * /modules/devel/devel.css.
  1418. * @param $type
  1419. * (optional) The type of stylesheet that is being added. Types are: module
  1420. * or theme.
  1421. * @param $media
  1422. * (optional) The media type for the stylesheet, e.g., all, print, screen.
  1423. * @param $preprocess
  1424. * (optional) Should this CSS file be aggregated and compressed if this
  1425. * feature has been turned on under the performance section?
  1426. *
  1427. * What does this actually mean?
  1428. * CSS preprocessing is the process of aggregating a bunch of separate CSS
  1429. * files into one file that is then compressed by removing all extraneous
  1430. * white space.
  1431. *
  1432. * The reason for merging the CSS files is outlined quite thoroughly here:
  1433. * http://www.die.net/musings/page_load_time/
  1434. * "Load fewer external objects. Due to request overhead, one bigger file
  1435. * just loads faster than two smaller ones half its size."
  1436. *
  1437. * However, you should *not* preprocess every file as this can lead to
  1438. * redundant caches. You should set $preprocess = FALSE when:
  1439. *
  1440. * - Your styles are only used rarely on the site. This could be a special
  1441. * admin page, the homepage, or a handful of pages that does not represent
  1442. * the majority of the pages on your site.
  1443. *
  1444. * Typical candidates for caching are for example styles for nodes across
  1445. * the site, or used in the theme.
  1446. * @return
  1447. * An array of CSS files.
  1448. */
  1449. function drupal_add_css($path = NULL, $type = 'module', $media = 'all', $preprocess = TRUE) {
  1450. static $css = array();
  1451. // Create an array of CSS files for each media type first, since each type needs to be served
  1452. // to the browser differently.
  1453. if (isset($path)) {
  1454. // This check is necessary to ensure proper cascading of styles and is faster than an asort().
  1455. if (!isset($css[$media])) {
  1456. $css[$media] = array('module' => array(), 'theme' => array());
  1457. }
  1458. $css[$media][$type][$path] = $preprocess;
  1459. }
  1460. return $css;
  1461. }
  1462. /**
  1463. * Returns a themed representation of all stylesheets that should be attached to the page.
  1464. * It loads the CSS in order, with 'core' CSS first, then 'module' CSS, then 'theme' CSS files.
  1465. * This ensures proper cascading of styles for easy overriding in modules and themes.
  1466. *
  1467. * @param $css
  1468. * (optional) An array of CSS files. If no array is provided, the default stylesheets array is used instead.
  1469. * @return
  1470. * A string of XHTML CSS tags.
  1471. */
  1472. function drupal_get_css($css = NULL) {
  1473. $output = '';
  1474. if (!isset($css)) {
  1475. $css = drupal_add_css();
  1476. }
  1477. $preprocess_css = variable_get('preprocess_css', FALSE);
  1478. $directory = file_directory_path();
  1479. $is_writable = is_dir($directory) && is_writable($directory) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC);
  1480. foreach ($css as $media => $types) {
  1481. // If CSS preprocessing is off, we still need to output the styles.
  1482. // Additionally, go through any remaining styles if CSS preprocessing is on and output the non-cached ones.
  1483. foreach ($types as $type => $files) {
  1484. foreach ($types[$type] as $file => $preprocess) {
  1485. if (!$preprocess || !($is_writable && $preprocess_css)) {
  1486. // If a CSS file is not to be preprocessed and it's a module CSS file, it needs to *always* appear at the *top*,
  1487. // regardless of whether preprocessing is on or off.
  1488. if (!$preprocess && $type == 'module') {
  1489. $no_module_preprocess .= '<style type="text/css" media="'. $media .'">@import "'. base_path() . $file .'";</style>' ."\n";
  1490. }
  1491. // If a CSS file is not to be preprocessed and it's a theme CSS file, it needs to *always* appear at the *bottom*,
  1492. // regardless of whether preprocessing is on or off.
  1493. else if (!$preprocess && $type == 'theme') {
  1494. $no_theme_preprocess .= '<style type="text/css" media="'. $media .'">@import "'. base_path() . $file .'";</style>' ."\n";
  1495. }
  1496. else {
  1497. $output .= '<style type="text/css" media="'. $media .'">@import "'. base_path() . $file .'";</style>' ."\n";
  1498. }
  1499. }
  1500. }
  1501. }
  1502. if ($is_writable && $preprocess_css) {
  1503. $filename = md5(serialize($types)) .'.css';
  1504. $preprocess_file = drupal_build_css_cache($types, $filename);
  1505. $output .= '<style type="text/css" media="'. $media .'">@import "'. base_path() . $preprocess_file .'";</style>'. "\n";
  1506. }
  1507. }
  1508. return $no_module_preprocess . $output . $no_theme_preprocess;
  1509. }
  1510. /**
  1511. * Aggregate and optimize CSS files, putting them in the files directory.
  1512. *
  1513. * @param $types
  1514. * An array of types of CSS files (e.g., screen, print) to aggregate and compress into one file.
  1515. * @param $filename
  1516. * The name of the aggregate CSS file.
  1517. * @return
  1518. * The name of the CSS file.
  1519. */
  1520. function drupal_build_css_cache($types, $filename) {
  1521. $data = '';
  1522. // Create the css/ within the files folder.
  1523. $csspath = file_create_path('css');
  1524. file_check_directory($csspath, FILE_CREATE_DIRECTORY);
  1525. if (!file_exists($csspath .'/'. $filename)) {
  1526. // Build aggregate CSS file.
  1527. foreach ($types as $type) {
  1528. foreach ($type as $file => $cache) {
  1529. if ($cache) {
  1530. $contents = file_get_contents($file);
  1531. // Remove multiple charset declarations for standards compliance (and fixing Safari problems)
  1532. $contents = preg_replace('/^@charset\s+[\'"](\S*)\b[\'"];/i', '', $contents);
  1533. // Return the path to where this CSS file originated from, stripping off the name of the file at the end of the path.
  1534. $path = base_path() . substr($file, 0, strrpos($file, '/')) .'/';
  1535. // Wraps all @import arguments in url().
  1536. $contents = preg_replace('/@import\s+(?!url)[\'"]?(\S*)\b[\'"]?/i', '@import url("\1")', $contents);
  1537. // Fix all paths within this CSS file, ignoring absolute paths.
  1538. $data .= preg_replace('/url\(([\'"]?)(?![a-z]+:)/i', 'url(\1'. $path . '\2', $contents);
  1539. }
  1540. }
  1541. }
  1542. // @import rules must proceed any other style, so we move those to the top.
  1543. $regexp = '/@import[^;]+;/i';
  1544. preg_match_all($regexp, $data, $matches);
  1545. $data = preg_replace($regexp, '', $data);
  1546. $data = implode('', $matches[0]) . $data;
  1547. // Perform some safe CSS optimizations.
  1548. $data = preg_replace('<
  1549. \s*([@{}:;,]|\)\s|\s\()\s* | # Remove whitespace around separators, but keep space around parentheses.
  1550. /\*([^*\\\\]|\*(?!/))+\*/ | # Remove comments that are not CSS hacks.
  1551. [\n\r] # Remove line breaks.
  1552. >x', '\1', $data);
  1553. // Create the CSS file.
  1554. file_save_data($data, $csspath .'/'. $filename, FILE_EXISTS_REPLACE);
  1555. }
  1556. return $csspath .'/'. $filename;
  1557. }
  1558. /**
  1559. * Delete all cached CSS files.
  1560. */
  1561. function drupal_clear_css_cache() {
  1562. file_scan_directory(file_create_path('css'), '.*', array('.', '..', 'CVS'), 'file_delete', TRUE);
  1563. // Clear the page cache, so cached pages do not reference nonexistent CSS.
  1564. cache_clear_all();
  1565. }
  1566. /**
  1567. * Add a JavaScript file, setting or inline code to the page.
  1568. *
  1569. * The behavior of this function depends on the parameters it is called with.
  1570. * Generally, it handles the addition of JavaScript to the page, either as
  1571. * reference to an existing file or as inline code. The following actions can be
  1572. * performed using this function:
  1573. *
  1574. * - Add a file ('core', 'module' and 'theme'):
  1575. * Adds a reference to a JavaScript file to the page. JavaScript files
  1576. * are placed in a certain order, from 'core' first, to 'module' and finally
  1577. * 'theme' so that files, that are added later, can override previously added
  1578. * files with ease.
  1579. *
  1580. * - Add inline JavaScript code ('inline'):
  1581. * Executes a piece of JavaScript code on the current page by placing the code
  1582. * directly in the page. This can, for example, be useful to tell the user that
  1583. * a new message arrived, by opening a pop up, alert box etc.
  1584. *
  1585. * - Add settings ('setting'):
  1586. * Adds a setting to Drupal's global storage of JavaScript settings. Per-page
  1587. * settings are required by some modules to function properly. The settings
  1588. * will be accessible at Drupal.settings.
  1589. *
  1590. * @param $data
  1591. * (optional) If given, the value depends on the $type parameter:
  1592. * - 'core', 'module' or 'theme': Path to the file relative to base_path().
  1593. * - 'inline': The JavaScript code that should be placed in the given scope.
  1594. * - 'setting': An array with configuration options as associative array. The
  1595. * array is directly placed in Drupal.settings. You might want to wrap your
  1596. * actual configuration settings in another variable to prevent the pollution
  1597. * of the Drupal.settings namespace.
  1598. * @param $type
  1599. * (optional) The type of JavaScript that should be added to the page. Allowed
  1600. * values are 'core', 'module', 'theme', 'inline' and 'setting'. You
  1601. * can, however, specify any value. It is treated as a reference to a JavaScript
  1602. * file. Defaults to 'module'.
  1603. * @param $scope
  1604. * (optional) The location in which you want to place the script. Possible
  1605. * values are 'header' and 'footer' by default. If your theme implements
  1606. * different locations, however, you can also use these.
  1607. * @param $defer
  1608. * (optional) If set to TRUE, the defer attribute is set on the <script> tag.
  1609. * Defaults to FALSE. This parameter is not used with $type == 'setting'.
  1610. * @param $cache
  1611. * (optional) If set to FALSE, the JavaScript file is loaded anew on every page
  1612. * call, that means, it is not cached. Defaults to TRUE. Used only when $type
  1613. * references a JavaScript file.
  1614. * @return
  1615. * If the first parameter is NULL, the JavaScript array that has been built so
  1616. * far for $scope is returned.
  1617. */
  1618. function drupal_add_js($data = NULL, $type = 'module', $scope = 'header', $defer = FALSE, $cache = TRUE) {
  1619. if (!is_null($data)) {
  1620. _drupal_add_js('misc/jquery.js', 'core', 'header', FALSE, $cache);
  1621. _drupal_add_js('misc/drupal.js', 'core', 'header', FALSE, $cache);
  1622. }
  1623. return _drupal_add_js($data, $type, $scope, $defer, $cache);
  1624. }
  1625. /**
  1626. * Helper function for drupal_add_js().
  1627. */
  1628. function _drupal_add_js($data, $type, $scope, $defer, $cache) {
  1629. static $javascript = array();
  1630. if (!isset($javascript[$scope])) {
  1631. $javascript[$scope] = array('core' => array(), 'module' => array(), 'theme' => array(), 'setting' => array(), 'inline' => array());
  1632. }
  1633. if (!isset($javascript[$scope][$type])) {
  1634. $javascript[$scope][$type] = array();
  1635. }
  1636. if (!is_null($data)) {
  1637. switch ($type) {
  1638. case 'setting':
  1639. $javascript[$scope][$type][] = $data;
  1640. break;
  1641. case 'inline':
  1642. $javascript[$scope][$type][] = array('code' => $data, 'defer' => $defer);
  1643. break;
  1644. default:
  1645. $javascript[$scope][$type][$data] = array('cache' => $cache, 'defer' => $defer);
  1646. }
  1647. }
  1648. return $javascript[$scope];
  1649. }
  1650. /**
  1651. * Returns a themed presentation of all JavaScript code for the current page.
  1652. * References to JavaScript files are placed in a certain order: first, all
  1653. * 'core' files, then all 'module' and finally all 'theme' JavaScript files
  1654. * are added to the page. Then, all settings are output, followed by 'inline'
  1655. * JavaScript code.
  1656. *
  1657. * @param $scope
  1658. * (optional) The scope for which the JavaScript rules should be returned.
  1659. * Defaults to 'header'.
  1660. * @param $javascript
  1661. * (optional) An array with all JavaScript code. Defaults to the default
  1662. * JavaScript array for the given scope.
  1663. * @return
  1664. * All JavaScript code segments and includes for the scope as HTML tags.
  1665. */
  1666. function drupal_get_js($scope = 'header', $javascript = NULL) {
  1667. $output = '';
  1668. if (is_null($javascript)) {
  1669. $javascript = drupal_add_js(NULL, NULL, $scope);
  1670. }
  1671. foreach ($javascript as $type => $data) {
  1672. if (!$data) continue;
  1673. switch ($type) {
  1674. case 'setting':
  1675. $output .= '<script type="text/javascript">Drupal.extend({ settings: '. drupal_to_js(call_user_func_array('array_merge_recursive', $data)) ." });</script>\n";
  1676. break;
  1677. case 'inline':
  1678. foreach ($data as $info) {
  1679. $output .= '<script type="text/javascript"'. ($info['defer'] ? ' defer="defer"' : '') .'>'. $info['code'] ."</script>\n";
  1680. }
  1681. break;
  1682. default:
  1683. foreach ($data as $path => $info) {
  1684. $output .= '<script type="text/javascript"'. ($info['defer'] ? ' defer="defer"' : '') .' src="'. check_url(base_path() . $path) . ($info['cache'] ? '' : '?'. time()) ."\"></script>\n";
  1685. }
  1686. }
  1687. }
  1688. return $output;
  1689. }
  1690. /**
  1691. * Converts a PHP variable into its Javascript equivalent.
  1692. *
  1693. * We use HTML-safe strings, i.e. with <, > and & escaped.
  1694. */
  1695. function drupal_to_js($var) {
  1696. switch (gettype($var)) {
  1697. case 'boolean':
  1698. return $var ? 'true' : 'false'; // Lowercase necessary!
  1699. case 'integer':
  1700. case 'double':
  1701. return $var;
  1702. case 'resource':
  1703. case 'string':
  1704. return '"'. str_replace(array("\r", "\n", "<", ">", "&"),
  1705. array('\r', '\n', '\x3c', '\x3e', '\x26'),
  1706. addslashes($var)) .'"';
  1707. case 'array':
  1708. // Arrays in JSON can't be associative. If the array is empty or if it
  1709. // has sequential whole number keys starting with 0, it's not associative
  1710. // so we can go ahead and convert it as an array.
  1711. if (empty ($var) || array_keys($var) === range(0, sizeof($var) - 1)) {
  1712. $output = array();
  1713. foreach ($var as $v) {
  1714. $output[] = drupal_to_js($v);
  1715. }
  1716. return '[ '. implode(', ', $output) .' ]';
  1717. }
  1718. // Otherwise, fall through to convert the array as an object.
  1719. case 'object':
  1720. $output = array();
  1721. foreach ($var as $k => $v) {
  1722. $output[] = drupal_to_js(strval($k)) .': '. drupal_to_js($v);
  1723. }
  1724. return '{ '. implode(', ', $output) .' }';
  1725. default:
  1726. return 'null';
  1727. }
  1728. }
  1729. /**
  1730. * Wrapper around urlencode() which avoids Apache quirks.
  1731. *
  1732. * Should be used when placing arbitrary data in an URL. Note that Drupal paths
  1733. * are urlencoded() when passed through url() and do not require urlencoding()
  1734. * of individual components.
  1735. *
  1736. * Notes:
  1737. * - For esthetic reasons, we do not escape slashes. This also avoids a 'feature'
  1738. * in Apache where it 404s on any path containing '%2F'.
  1739. * - mod_rewrite unescapes %-encoded ampersands, hashes, and slashes when clean
  1740. * URLs are used, which are interpreted as delimiters by PHP. These
  1741. * characters are double escaped so PHP will still see the encoded version.
  1742. * - With clean URLs, Apache changes '//' to '/', so every second slash is
  1743. * double escaped.
  1744. *
  1745. * @param $text
  1746. * String to encode
  1747. */
  1748. function drupal_urlencode($text) {
  1749. if (variable_get('clean_url', '0')) {
  1750. return str_replace(array('%2F', '%26', '%23', '//'),
  1751. array('/', '%2526', '%2523', '/%252F'),
  1752. urlencode($text));
  1753. }
  1754. else {
  1755. return str_replace('%2F', '/', urlencode($text));
  1756. }
  1757. }
  1758. /**
  1759. * Ensure the private key variable used to generate tokens is set.
  1760. *
  1761. * @return
  1762. * The private key
  1763. */
  1764. function drupal_get_private_key() {
  1765. if (!($key = variable_get('drupal_private_key', 0))) {
  1766. $key = md5(uniqid(mt_rand(), true)) . md5(uniqid(mt_rand(), true));
  1767. variable_set('drupal_private_key', $key);
  1768. }
  1769. return $key;
  1770. }
  1771. /**
  1772. * Generate a token based on $value, the current user session and private key.
  1773. *
  1774. * @param $value
  1775. * An additional value to base the token on
  1776. */
  1777. function drupal_get_token($value = '') {
  1778. $private_key = drupal_get_private_key();
  1779. return md5(session_id() . $value . $private_key);
  1780. }
  1781. /**
  1782. * Validate a token based on $value, the current user session and private key.
  1783. *
  1784. * @param $token
  1785. * The token to be validated.
  1786. * @param $value
  1787. * An additional value to base the token on.
  1788. * @param $skip_anonymous
  1789. * Set to true to skip token validation for anonymous users.
  1790. * @return
  1791. * True for a valid token, false for an invalid token. When $skip_anonymous is true, the return value will always be true for anonymous users.
  1792. */
  1793. function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
  1794. global $user;
  1795. return (($skip_anonymous && $user->uid == 0) || ($token == md5(session_id() . $value . variable_get('drupal_private_key', ''))));
  1796. }
  1797. /**
  1798. * Performs one or more XML-RPC request(s).
  1799. *
  1800. * @param $url
  1801. * An absolute URL of the XML-RPC endpoint.
  1802. * Example:
  1803. * http://www.example.com/xmlrpc.php
  1804. * @param ...
  1805. * For one request:
  1806. * The method name followed by a variable number of arguments to the method.
  1807. * For multiple requests (system.multicall):
  1808. * An array of call arrays. Each call array follows the pattern of the single
  1809. * request: method name followed by the arguments to the method.
  1810. * @return
  1811. * For one request:
  1812. * Either the return value of the method on success, or FALSE.
  1813. * If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
  1814. * For multiple requests:
  1815. * An array of results. Each result will either be the result
  1816. * returned by the method called, or an xmlrpc_error object if the call
  1817. * failed. See xmlrpc_error().
  1818. */
  1819. function xmlrpc($url) {
  1820. require_once './includes/xmlrpc.inc';
  1821. $args = func_get_args();
  1822. return call_user_func_array('_xmlrpc', $args);
  1823. }
  1824. function _drupal_bootstrap_full() {
  1825. static $called;
  1826. global $locale;
  1827. if ($called) {
  1828. return;
  1829. }
  1830. $called = 1;
  1831. require_once './includes/theme.inc';
  1832. require_once './includes/pager.inc';
  1833. require_once './includes/menu.inc';
  1834. require_once './includes/tablesort.inc';
  1835. require_once './includes/file.inc';
  1836. require_once './includes/unicode.inc';
  1837. require_once './includes/image.inc';
  1838. require_once './includes/form.inc';
  1839. // Set the Drupal custom error handler.
  1840. set_error_handler('error_handler');
  1841. // Emit the correct charset HTTP header.
  1842. drupal_set_header('Content-Type: text/html; charset=utf-8');
  1843. // Detect string handling method
  1844. unicode_check();
  1845. // Undo magic quotes
  1846. fix_gpc_magic();
  1847. // Load all enabled modules
  1848. module_load_all();
  1849. // Initialize the localization system. Depends on i18n.module being loaded already.
  1850. $locale = locale_initialize();
  1851. // Let all modules take action before menu system handles the reqest
  1852. module_invoke_all('init');
  1853. }
  1854. /**
  1855. * Store the current page in the cache.
  1856. *
  1857. * We try to store a gzipped version of the cache. This requires the
  1858. * PHP zlib extension (http://php.net/manual/en/ref.zlib.php).
  1859. * Presence of the extension is checked by testing for the function
  1860. * gzencode. There are two compression algorithms: gzip and deflate.
  1861. * The majority of all modern browsers support gzip or both of them.
  1862. * We thus only deal with the gzip variant and unzip the cache in case
  1863. * the browser does not accept gzip encoding.
  1864. *
  1865. * @see drupal_page_header
  1866. */
  1867. function page_set_cache() {
  1868. global $user, $base_root;
  1869. if (!$user->uid && $_SERVER['REQUEST_METHOD'] == 'GET' && count(drupal_get_messages(NULL, FALSE)) == 0) {
  1870. // This will fail in some cases, see page_get_cache() for the explanation.
  1871. if ($data = ob_get_contents()) {
  1872. $cache = TRUE;
  1873. if (function_exists('gzencode')) {
  1874. // We do not store the data in case the zlib mode is deflate.
  1875. // This should be rarely happening.
  1876. if (zlib_get_coding_type() == 'deflate') {
  1877. $cache = FALSE;
  1878. }
  1879. else if (zlib_get_coding_type() == FALSE) {
  1880. $data = gzencode($data, 9, FORCE_GZIP);
  1881. }
  1882. // The remaining case is 'gzip' which means the data is
  1883. // already compressed and nothing left to do but to store it.
  1884. }
  1885. ob_end_flush();
  1886. if ($cache && $data) {
  1887. cache_set($base_root . request_uri(), 'cache_page', $data, CACHE_TEMPORARY, drupal_get_headers());
  1888. }
  1889. }
  1890. }
  1891. }
  1892. /**
  1893. * Send an e-mail message, using Drupal variables and default settings.
  1894. * More information in the PHP function reference for mail()
  1895. * @param $mailkey
  1896. * A key to identify the mail sent, for altering.
  1897. * @param $to
  1898. * The mail address or addresses where the message will be send to. The
  1899. * formatting of this string must comply with RFC 2822. Some examples are:
  1900. * user@example.com
  1901. * user@example.com, anotheruser@example.com
  1902. * User <user@example.com>
  1903. * User <user@example.com>, Another User <anotheruser@example.com>
  1904. * @param $subject
  1905. * Subject of the e-mail to be sent. This must not contain any newline
  1906. * characters, or the mail may not be sent properly.
  1907. * @param $body
  1908. * Message to be sent. Drupal will format the correct line endings for you.
  1909. * @param $from
  1910. * Sets From to this value, if given.
  1911. * @param $headers
  1912. * Associative array containing the headers to add. This is typically
  1913. * used to add extra headers (From, Cc, and Bcc).
  1914. * <em>When sending mail, the mail must contain a From header.</em>
  1915. * @return Returns TRUE if the mail was successfully accepted for delivery,
  1916. * FALSE otherwise.
  1917. */
  1918. function drupal_mail($mailkey, $to, $subject, $body, $from = NULL, $headers = array()) {
  1919. $defaults = array(
  1920. 'MIME-Version' => '1.0',
  1921. 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed',
  1922. 'Content-Transfer-Encoding' => '8Bit',
  1923. 'X-Mailer' => 'Drupal'
  1924. );
  1925. // To prevent e-mail from looking like spam, the addresses in the Sender and
  1926. // Return-Path headers should have a domain authorized to use the originating
  1927. // SMTP server. Errors-To is redundant, but shouldn't hurt.
  1928. $default_from = variable_get('site_mail', ini_get('sendmail_from'));
  1929. if ($default_from) {
  1930. $defaults['From'] = $defaults['Sender'] = $defaults['Return-Path'] = $defaults['Errors-To'] = $default_from;
  1931. }
  1932. if ($from) {
  1933. $defaults['From'] = $from;
  1934. }
  1935. $headers = array_merge($defaults, $headers);
  1936. // Custom hook traversal to allow pass by reference
  1937. foreach (module_implements('mail_alter') AS $module) {
  1938. $function = $module .'_mail_alter';
  1939. $function($mailkey, $to, $subject, $body, $from, $headers);
  1940. }
  1941. // Allow for custom mail backend
  1942. if (variable_get('smtp_library', '') && file_exists(variable_get('smtp_library', ''))) {
  1943. include_once './' . variable_get('smtp_library', '');
  1944. return drupal_mail_wrapper($mailkey, $to, $subject, $body, $from, $headers);
  1945. }
  1946. else {
  1947. // Note: if you are having problems with sending mail, or mails look wrong
  1948. // when they are received you may have to modify the str_replace to suit
  1949. // your systems.
  1950. // - \r\n will work under dos and windows.
  1951. // - \n will work for linux, unix and BSDs.
  1952. // - \r will work for macs.
  1953. //
  1954. // According to RFC 2646, it's quite rude to not wrap your e-mails:
  1955. //
  1956. // "The Text/Plain media type is the lowest common denominator of
  1957. // Internet e-mail, with lines of no more than 997 characters (by
  1958. // convention usually no more than 80), and where the CRLF sequence
  1959. // represents a line break [MIME-IMT]."
  1960. //
  1961. // CRLF === \r\n
  1962. //
  1963. // http://www.rfc-editor.org/rfc/rfc2646.txt
  1964. $mimeheaders = array();
  1965. foreach ($headers as $name => $value) {
  1966. $mimeheaders[] = $name .': '. mime_header_encode($value);
  1967. }
  1968. return mail(
  1969. $to,
  1970. mime_header_encode($subject),
  1971. str_replace("\r", '', $body),
  1972. join("\n", $mimeheaders)
  1973. );
  1974. }
  1975. }
  1976. /**
  1977. * Executes a cron run when called
  1978. * @return
  1979. * Returns TRUE if ran successfully
  1980. */
  1981. function drupal_cron_run() {
  1982. // If not in 'safe mode', increase the maximum execution time:
  1983. if (!ini_get('safe_mode')) {
  1984. set_time_limit(240);
  1985. }
  1986. // Fetch the cron semaphore
  1987. $semaphore = variable_get('cron_semaphore', FALSE);
  1988. if ($semaphore) {
  1989. if (time() - $semaphore > 3600) {
  1990. // Either cron has been running for more than an hour or the semaphore
  1991. // was not reset due to a database error.
  1992. watchdog('cron', t('Cron has been running for more than an hour and is most likely stuck.'), WATCHDOG_ERROR);
  1993. // Release cron semaphore
  1994. variable_del('cron_semaphore');
  1995. }
  1996. else {
  1997. // Cron is still running normally.
  1998. watchdog('cron', t('Attempting to re-run cron while it is already running.'), WATCHDOG_WARNING);
  1999. }
  2000. }
  2001. else {
  2002. // Register shutdown callback
  2003. register_shutdown_function('drupal_cron_cleanup');
  2004. // Lock cron semaphore
  2005. variable_set('cron_semaphore', time());
  2006. // Iterate through the modules calling their cron handlers (if any):
  2007. module_invoke_all('cron');
  2008. // Record cron time
  2009. variable_set('cron_last', time());
  2010. watchdog('cron', t('Cron run completed.'), WATCHDOG_NOTICE);
  2011. // Release cron semaphore
  2012. variable_del('cron_semaphore');
  2013. // Return TRUE so other functions can check if it did run successfully
  2014. return TRUE;
  2015. }
  2016. }
  2017. /**
  2018. * Shutdown function for cron cleanup.
  2019. */
  2020. function drupal_cron_cleanup() {
  2021. // See if the semaphore is still locked.
  2022. if (variable_get('cron_semaphore', FALSE)) {
  2023. watchdog('cron', t('Cron run exceeded the time limit and was aborted.'), WATCHDOG_WARNING);
  2024. // Release cron semaphore
  2025. variable_del('cron_semaphore');
  2026. }
  2027. }
  2028. /**
  2029. * Returns an array of files objects of the given type from the site-wide
  2030. * directory (i.e. modules/), the all-sites directory (i.e.
  2031. * sites/all/modules/), the profiles directory, and site-specific directory
  2032. * (i.e. sites/somesite/modules/). The returned array will be keyed using the
  2033. * key specified (name, basename, filename). Using name or basename will cause
  2034. * site-specific files to be prioritized over similar files in the default
  2035. * directories. That is, if a file with the same name appears in both the
  2036. * site-wide directory and site-specific directory, only the site-specific
  2037. * version will be included.
  2038. *
  2039. * @param $mask
  2040. * The regular expression of the files to find.
  2041. * @param $directory
  2042. * The subdirectory name in which the files are found. For example,
  2043. * 'modules' will search in both modules/ and
  2044. * sites/somesite/modules/.
  2045. * @param $key
  2046. * The key to be passed to file_scan_directory().
  2047. * @param $min_depth
  2048. * Minimum depth of directories to return files from.
  2049. *
  2050. * @return
  2051. * An array of file objects of the specified type.
  2052. */
  2053. function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
  2054. global $profile;
  2055. $config = conf_path();
  2056. // When this function is called during Drupal's initial installation process,
  2057. // the name of the profile that's about to be installed is stored in the global
  2058. // $profile variable. At all other times, the standard Drupal systems variable
  2059. // table contains the name of the current profile, and we can call variable_get()
  2060. // to determine what one is active.
  2061. if (!isset($profile)) {
  2062. $profile = variable_get('install_profile', 'default');
  2063. }
  2064. $searchdir = array($directory);
  2065. $files = array();
  2066. // Always search sites/all/* as well as the global directories
  2067. $searchdir[] = 'sites/all/'. $directory;
  2068. // The 'profiles' directory contains pristine collections of modules and
  2069. // themes as organized by a distribution. It is pristine in the same way
  2070. // that /modules is pristine for core; users should avoid changing anything
  2071. // there in favor of sites/all or sites/<domain> directories.
  2072. if (file_exists("profiles/$profile/$directory")) {
  2073. $searchdir[] = "profiles/$profile/$directory";
  2074. }
  2075. if (file_exists("$config/$directory")) {
  2076. $searchdir[] = "$config/$directory";
  2077. }
  2078. // Get current list of items
  2079. foreach ($searchdir as $dir) {
  2080. $files = array_merge($files, file_scan_directory($dir, $mask, array('.', '..', 'CVS'), 0, TRUE, $key, $min_depth));
  2081. }
  2082. return $files;
  2083. }
  2084. /**
  2085. * Renders HTML given a structured array tree. Recursively iterates over each
  2086. * of the array elements, generating HTML code. This function is usually
  2087. * called from within a another function, like drupal_get_form() or node_view().
  2088. *
  2089. * @param $elements
  2090. * The structured array describing the data to be rendered.
  2091. * @return
  2092. * The rendered HTML.
  2093. */
  2094. function drupal_render(&$elements) {
  2095. if (!isset($elements) || (isset($elements['#access']) && !$elements['#access'])) {
  2096. return NULL;
  2097. }
  2098. $content = '';
  2099. // Either the elements did not go through form_builder or one of the children
  2100. // has a #weight.
  2101. if (!isset($elements['#sorted'])) {
  2102. uasort($elements, "_element_sort");
  2103. }
  2104. if (!isset($elements['#children'])) {
  2105. $children = element_children($elements);
  2106. /* Render all the children that use a theme function */
  2107. if (isset($elements['#theme']) && empty($elements['#theme_used'])) {
  2108. $elements['#theme_used'] = TRUE;
  2109. $previous = array();
  2110. foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
  2111. $previous[$key] = isset($elements[$key]) ? $elements[$key] : NULL;
  2112. }
  2113. // If we rendered a single element, then we will skip the renderer.
  2114. if (empty($children)) {
  2115. $elements['#printed'] = TRUE;
  2116. }
  2117. else {
  2118. $elements['#value'] = '';
  2119. }
  2120. $elements['#type'] = 'markup';
  2121. unset($elements['#prefix'], $elements['#suffix']);
  2122. $content = theme($elements['#theme'], $elements);
  2123. foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
  2124. $elements[$key] = isset($previous[$key]) ? $previous[$key] : NULL;
  2125. }
  2126. }
  2127. /* render each of the children using drupal_render and concatenate them */
  2128. if (!isset($content) || $content === '') {
  2129. foreach ($children as $key) {
  2130. $content .= drupal_render($elements[$key]);
  2131. }
  2132. }
  2133. }
  2134. if (isset($content) && $content !== '') {
  2135. $elements['#children'] = $content;
  2136. }
  2137. // Until now, we rendered the children, here we render the element itself
  2138. if (!isset($elements['#printed'])) {
  2139. $content = theme(!empty($elements['#type']) ? $elements['#type'] : 'markup', $elements);
  2140. $elements['#printed'] = TRUE;
  2141. }
  2142. if (isset($content) && $content !== '') {
  2143. $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
  2144. $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
  2145. return $prefix . $content . $suffix;
  2146. }
  2147. }
  2148. /**
  2149. * Function used by uasort in drupal_render() to sort structured arrays
  2150. * by weight.
  2151. */
  2152. function _element_sort($a, $b) {
  2153. $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
  2154. $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
  2155. if ($a_weight == $b_weight) {
  2156. return 0;
  2157. }
  2158. return ($a_weight < $b_weight) ? -1 : 1;
  2159. }
  2160. /**
  2161. * Check if the key is a property.
  2162. */
  2163. function element_property($key) {
  2164. return $key[0] == '#';
  2165. }
  2166. /**
  2167. * Get properties of a structured array element. Properties begin with '#'.
  2168. */
  2169. function element_properties($element) {
  2170. return array_filter(array_keys((array) $element), 'element_property');
  2171. }
  2172. /**
  2173. * Check if the key is a child.
  2174. */
  2175. function element_child($key) {
  2176. return $key[0] != '#';
  2177. }
  2178. /**
  2179. * Get keys of a structured array tree element that are not properties
  2180. * (i.e., do not begin with '#').
  2181. */
  2182. function element_children($element) {
  2183. return array_filter(array_keys((array) $element), 'element_child');
  2184. }