PageRenderTime 58ms CodeModel.GetById 16ms 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

Large files files are truncated, but you can click here to view the full file

  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:…

Large files files are truncated, but you can click here to view the full file