PageRenderTime 74ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/common.inc

https://bitbucket.org/Schnitzel/osec
PHP | 4055 lines | 2800 code | 202 blank | 1053 comment | 263 complexity | 5da247440aaad8049545961f51562367 MD5 | raw file
Possible License(s): AGPL-1.0, BSD-3-Clause, GPL-2.0, AGPL-3.0, LGPL-2.1

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

  1. <?php
  2. /**
  3. * @file
  4. * Common functions that many Drupal modules will need to reference.
  5. *
  6. * The functions that are critical and need to be available even when serving
  7. * a cached page are instead located in bootstrap.inc.
  8. */
  9. /**
  10. * Return status for saving which involved creating a new item.
  11. */
  12. define('SAVED_NEW', 1);
  13. /**
  14. * Return status for saving which involved an update to an existing item.
  15. */
  16. define('SAVED_UPDATED', 2);
  17. /**
  18. * Return status for saving which deleted an existing item.
  19. */
  20. define('SAVED_DELETED', 3);
  21. /**
  22. * Create E_DEPRECATED constant for older PHP versions (<5.3).
  23. */
  24. if (!defined('E_DEPRECATED')) {
  25. define('E_DEPRECATED', 8192);
  26. }
  27. /**
  28. * Set content for a specified region.
  29. *
  30. * @param $region
  31. * Page region the content is assigned to.
  32. * @param $data
  33. * Content to be set.
  34. */
  35. function drupal_set_content($region = NULL, $data = NULL) {
  36. static $content = array();
  37. if (!is_null($region) && !is_null($data)) {
  38. $content[$region][] = $data;
  39. }
  40. return $content;
  41. }
  42. /**
  43. * Get assigned content.
  44. *
  45. * @param $region
  46. * A specified region to fetch content for. If NULL, all regions will be
  47. * returned.
  48. * @param $delimiter
  49. * Content to be inserted between imploded array elements.
  50. */
  51. function drupal_get_content($region = NULL, $delimiter = ' ') {
  52. $content = drupal_set_content();
  53. if (isset($region)) {
  54. if (isset($content[$region]) && is_array($content[$region])) {
  55. return implode($delimiter, $content[$region]);
  56. }
  57. }
  58. else {
  59. foreach (array_keys($content) as $region) {
  60. if (is_array($content[$region])) {
  61. $content[$region] = implode($delimiter, $content[$region]);
  62. }
  63. }
  64. return $content;
  65. }
  66. }
  67. /**
  68. * Set the breadcrumb trail for the current page.
  69. *
  70. * @param $breadcrumb
  71. * Array of links, starting with "home" and proceeding up to but not including
  72. * the current page.
  73. */
  74. function drupal_set_breadcrumb($breadcrumb = NULL) {
  75. static $stored_breadcrumb;
  76. if (!is_null($breadcrumb)) {
  77. $stored_breadcrumb = $breadcrumb;
  78. }
  79. return $stored_breadcrumb;
  80. }
  81. /**
  82. * Get the breadcrumb trail for the current page.
  83. */
  84. function drupal_get_breadcrumb() {
  85. $breadcrumb = drupal_set_breadcrumb();
  86. if (is_null($breadcrumb)) {
  87. $breadcrumb = menu_get_active_breadcrumb();
  88. }
  89. return $breadcrumb;
  90. }
  91. /**
  92. * Add output to the head tag of the HTML page.
  93. *
  94. * This function can be called as long the headers aren't sent.
  95. */
  96. function drupal_set_html_head($data = NULL) {
  97. static $stored_head = '';
  98. if (!is_null($data)) {
  99. $stored_head .= $data ."\n";
  100. }
  101. return $stored_head;
  102. }
  103. /**
  104. * Retrieve output to be displayed in the head tag of the HTML page.
  105. */
  106. function drupal_get_html_head() {
  107. $output = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
  108. return $output . drupal_set_html_head();
  109. }
  110. /**
  111. * Reset the static variable which holds the aliases mapped for this request.
  112. */
  113. function drupal_clear_path_cache() {
  114. drupal_lookup_path('wipe');
  115. }
  116. /*
  117. * The function drupal_set_header() has been moved to includes/bootstrap.inc in Pressflow.
  118. */
  119. /**
  120. * Get the HTTP response headers for the current page.
  121. *
  122. * This function is not called by Pressflow and remains here
  123. * only for Drupal 5/6 API compatibility.
  124. */
  125. function drupal_get_headers() {
  126. $headers = drupal_set_header();
  127. $header_text = array();
  128. foreach ($headers as $name => $value) {
  129. $header_text[] .= $name . ': ' . $value;
  130. }
  131. return implode("\n", $header_text);
  132. }
  133. /**
  134. * Make any final alterations to the rendered xhtml.
  135. */
  136. function drupal_final_markup($content) {
  137. // Make sure that the charset is always specified as the first element of the
  138. // head region to prevent encoding-based attacks.
  139. return preg_replace('/<head[^>]*>/i', "\$0\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />", $content, 1);
  140. }
  141. /**
  142. * Add a feed URL for the current page.
  143. *
  144. * @param $url
  145. * A url for the feed.
  146. * @param $title
  147. * The title of the feed.
  148. */
  149. function drupal_add_feed($url = NULL, $title = '') {
  150. static $stored_feed_links = array();
  151. if (!is_null($url) && !isset($stored_feed_links[$url])) {
  152. $stored_feed_links[$url] = theme('feed_icon', $url, $title);
  153. drupal_add_link(array('rel' => 'alternate',
  154. 'type' => 'application/rss+xml',
  155. 'title' => $title,
  156. 'href' => $url));
  157. }
  158. return $stored_feed_links;
  159. }
  160. /**
  161. * Get the feed URLs for the current page.
  162. *
  163. * @param $delimiter
  164. * A delimiter to split feeds by.
  165. */
  166. function drupal_get_feeds($delimiter = "\n") {
  167. $feeds = drupal_add_feed();
  168. return implode($feeds, $delimiter);
  169. }
  170. /**
  171. * @defgroup http_handling HTTP handling
  172. * @{
  173. * Functions to properly handle HTTP responses.
  174. */
  175. /**
  176. * Parse an array into a valid urlencoded query string.
  177. *
  178. * @param $query
  179. * The array to be processed e.g. $_GET.
  180. * @param $exclude
  181. * The array filled with keys to be excluded. Use parent[child] to exclude
  182. * nested items.
  183. * @param $parent
  184. * Should not be passed, only used in recursive calls.
  185. * @return
  186. * An 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 = rawurlencode($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 .'='. rawurlencode($value);
  203. }
  204. }
  205. return implode('&', $params);
  206. }
  207. /**
  208. * Prepare a destination query string for use in combination with drupal_goto().
  209. *
  210. * Used to direct the user back to the referring page after completing a form.
  211. * By default the current URL is returned. If a destination exists in the
  212. * previous request, that destination is returned. As such, a destination can
  213. * persist across multiple 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. * destination 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. * A query string component, if any.
  257. * @param $fragment
  258. * A 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 (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, array('query' => $query, 'fragment' => $fragment, 'absolute' => TRUE));
  289. // Remove newlines from the URL to avoid header injection attacks.
  290. $url = str_replace(array("\n", "\r"), '', $url);
  291. // Allow modules to react to the end of the page request before redirecting.
  292. // We do not want this while running update.php.
  293. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
  294. module_invoke_all('exit', $url);
  295. }
  296. // Even though session_write_close() is registered as a shutdown function,
  297. // we need all session data written to the database before redirecting.
  298. drupal_session_commit();
  299. header('Location: '. $url, TRUE, $http_response_code);
  300. // The "Location" header sends a redirect status code to the HTTP daemon. In
  301. // some cases this can be wrong, so we make sure none of the code below the
  302. // drupal_goto() call gets executed upon redirection.
  303. exit();
  304. }
  305. /**
  306. * Generates a site off-line message.
  307. */
  308. function drupal_site_offline() {
  309. drupal_maintenance_theme();
  310. drupal_set_header('HTTP/1.1 503 Service unavailable');
  311. drupal_set_title(t('Site off-line'));
  312. print theme('maintenance_page', filter_xss_admin(variable_get('site_offline_message',
  313. t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Pressflow'))))));
  314. }
  315. /**
  316. * Generates a 404 error if the request can not be handled.
  317. */
  318. function drupal_not_found() {
  319. drupal_set_header('HTTP/1.1 404 Not Found');
  320. watchdog('page not found', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
  321. // Keep old path for reference, and to allow forms to redirect to it.
  322. if (!isset($_REQUEST['destination'])) {
  323. $_REQUEST['destination'] = $_GET['q'];
  324. }
  325. $path = drupal_get_normal_path(variable_get('site_404', ''));
  326. if ($path && $path != $_GET['q']) {
  327. // Set the active item in case there are tabs to display, or other
  328. // dependencies on the path.
  329. menu_set_active_item($path);
  330. $return = menu_execute_active_handler($path);
  331. }
  332. if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
  333. drupal_set_title(t('Page not found'));
  334. $return = t('The requested page could not be found.');
  335. }
  336. // To conserve CPU and bandwidth, omit the blocks.
  337. print theme('page', $return, FALSE);
  338. }
  339. /**
  340. * Generates a 403 error if the request is not allowed.
  341. */
  342. function drupal_access_denied() {
  343. drupal_set_header('HTTP/1.1 403 Forbidden');
  344. watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
  345. // Keep old path for reference, and to allow forms to redirect to it.
  346. if (!isset($_REQUEST['destination'])) {
  347. $_REQUEST['destination'] = $_GET['q'];
  348. }
  349. $path = drupal_get_normal_path(variable_get('site_403', ''));
  350. if ($path && $path != $_GET['q']) {
  351. // Set the active item in case there are tabs to display or other
  352. // dependencies on the path.
  353. menu_set_active_item($path);
  354. $return = menu_execute_active_handler($path);
  355. }
  356. if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
  357. drupal_set_title(t('Access denied'));
  358. $return = t('You are not authorized to access this page.');
  359. }
  360. print theme('page', $return);
  361. }
  362. /**
  363. * Perform an HTTP request.
  364. *
  365. * This is a flexible and powerful HTTP client implementation. Correctly handles
  366. * GET, POST, PUT or any other HTTP requests. Handles redirects.
  367. *
  368. * @param $url
  369. * A string containing a fully qualified URI.
  370. * @param $headers
  371. * An array containing an HTTP header => value pair.
  372. * @param $method
  373. * A string defining the HTTP request to use.
  374. * @param $data
  375. * A string containing data to include in the request.
  376. * @param $retry
  377. * An integer representing how many times to retry the request in case of a
  378. * redirect.
  379. * @return
  380. * An object containing the HTTP request headers, response code, protocol,
  381. * status message, headers, data and redirect status.
  382. */
  383. function drupal_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) {
  384. global $db_prefix;
  385. $result = new stdClass();
  386. // Parse the URL and make sure we can handle the schema.
  387. $uri = parse_url($url);
  388. if ($uri == FALSE) {
  389. $result->error = 'unable to parse URL';
  390. $result->code = -1001;
  391. return $result;
  392. }
  393. if (!isset($uri['scheme'])) {
  394. $result->error = 'missing schema';
  395. $result->code = -1002;
  396. return $result;
  397. }
  398. switch ($uri['scheme']) {
  399. case 'http':
  400. case 'feed':
  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. // When a network error occurs, we use a negative number so it does not
  419. // clash with the HTTP status codes.
  420. $result->code = -$errno;
  421. $result->error = trim($errstr);
  422. // Mark that this request failed. This will trigger a check of the web
  423. // server's ability to make outgoing HTTP requests the next time that
  424. // requirements checking is performed.
  425. // @see system_requirements()
  426. variable_set('drupal_http_request_fails', TRUE);
  427. return $result;
  428. }
  429. // Construct the path to act on.
  430. $path = isset($uri['path']) ? $uri['path'] : '/';
  431. if (isset($uri['query'])) {
  432. $path .= '?'. $uri['query'];
  433. }
  434. // Create HTTP request.
  435. $defaults = array(
  436. // RFC 2616: "non-standard ports MUST, default ports MAY be included".
  437. // We don't add the port to prevent from breaking rewrite rules checking the
  438. // host that do not take into account the port number.
  439. 'Host' => "Host: $host",
  440. 'User-Agent' => 'User-Agent: Drupal (+http://drupal.org/)',
  441. );
  442. // Only add Content-Length if we actually have any content or if it is a POST
  443. // or PUT request. Some non-standard servers get confused by Content-Length in
  444. // at least HEAD/GET requests, and Squid always requires Content-Length in
  445. // POST/PUT requests.
  446. $content_length = strlen($data);
  447. if ($content_length > 0 || $method == 'POST' || $method == 'PUT') {
  448. $defaults['Content-Length'] = 'Content-Length: '. $content_length;
  449. }
  450. // If the server url has a user then attempt to use basic authentication
  451. if (isset($uri['user'])) {
  452. $defaults['Authorization'] = 'Authorization: Basic '. base64_encode($uri['user'] . (!empty($uri['pass']) ? ":". $uri['pass'] : ''));
  453. }
  454. // If the database prefix is being used by SimpleTest to run the tests in a copied
  455. // database then set the user-agent header to the database prefix so that any
  456. // calls to other Drupal pages will run the SimpleTest prefixed database. The
  457. // user-agent is used to ensure that multiple testing sessions running at the
  458. // same time won't interfere with each other as they would if the database
  459. // prefix were stored statically in a file or database variable.
  460. if (is_string($db_prefix) && preg_match("/^simpletest\d+$/", $db_prefix, $matches)) {
  461. $defaults['User-Agent'] = 'User-Agent: ' . drupal_generate_test_ua($matches[0]);
  462. }
  463. foreach ($headers as $header => $value) {
  464. $defaults[$header] = $header .': '. $value;
  465. }
  466. $request = $method .' '. $path ." HTTP/1.0\r\n";
  467. $request .= implode("\r\n", $defaults);
  468. $request .= "\r\n\r\n";
  469. $request .= $data;
  470. $result->request = $request;
  471. fwrite($fp, $request);
  472. // Fetch response.
  473. $response = '';
  474. while (!feof($fp) && $chunk = fread($fp, 1024)) {
  475. $response .= $chunk;
  476. }
  477. fclose($fp);
  478. // Parse response.
  479. list($split, $result->data) = explode("\r\n\r\n", $response, 2);
  480. $split = preg_split("/\r\n|\n|\r/", $split);
  481. list($protocol, $code, $status_message) = explode(' ', trim(array_shift($split)), 3);
  482. $result->protocol = $protocol;
  483. $result->status_message = $status_message;
  484. $result->headers = array();
  485. // Parse headers.
  486. while ($line = trim(array_shift($split))) {
  487. list($header, $value) = explode(':', $line, 2);
  488. if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
  489. // RFC 2109: the Set-Cookie response header comprises the token Set-
  490. // Cookie:, followed by a comma-separated list of one or more cookies.
  491. $result->headers[$header] .= ','. trim($value);
  492. }
  493. else {
  494. $result->headers[$header] = trim($value);
  495. }
  496. }
  497. $responses = array(
  498. 100 => 'Continue', 101 => 'Switching Protocols',
  499. 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
  500. 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
  501. 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',
  502. 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'
  503. );
  504. // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  505. // base code in their class.
  506. if (!isset($responses[$code])) {
  507. $code = floor($code / 100) * 100;
  508. }
  509. switch ($code) {
  510. case 200: // OK
  511. case 304: // Not modified
  512. break;
  513. case 301: // Moved permanently
  514. case 302: // Moved temporarily
  515. case 307: // Moved temporarily
  516. $location = $result->headers['Location'];
  517. if ($retry) {
  518. $result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
  519. $result->redirect_code = $result->code;
  520. }
  521. $result->redirect_url = $location;
  522. break;
  523. default:
  524. $result->error = $status_message;
  525. }
  526. $result->code = $code;
  527. return $result;
  528. }
  529. /**
  530. * @} End of "HTTP handling".
  531. */
  532. /**
  533. * Log errors as defined by administrator.
  534. *
  535. * Error levels:
  536. * - 0 = Log errors to database.
  537. * - 1 = Log errors to database and to screen.
  538. */
  539. function drupal_error_handler($errno, $message, $filename, $line, $context) {
  540. // If the @ error suppression operator was used, error_reporting will have
  541. // been temporarily set to 0.
  542. if (error_reporting() == 0) {
  543. return;
  544. }
  545. if ($errno & (E_ALL ^ E_DEPRECATED ^ E_NOTICE)) {
  546. $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');
  547. // For database errors, we want the line number/file name of the place that
  548. // the query was originally called, not _db_query().
  549. if (isset($context[DB_ERROR])) {
  550. $backtrace = array_reverse(debug_backtrace());
  551. // List of functions where SQL queries can originate.
  552. $query_functions = array('db_query', 'pager_query', 'db_query_range', 'db_query_temporary', 'update_sql');
  553. // Determine where query function was called, and adjust line/file
  554. // accordingly.
  555. foreach ($backtrace as $index => $function) {
  556. if (in_array($function['function'], $query_functions)) {
  557. $line = $backtrace[$index]['line'];
  558. $filename = $backtrace[$index]['file'];
  559. break;
  560. }
  561. }
  562. }
  563. $entry = check_plain($types[$errno]) .': '. filter_xss($message) .' in '. check_plain($filename) .' on line '. check_plain($line) .'.';
  564. // Force display of error messages in update.php.
  565. if (variable_get('error_level', 1) == 1 || strstr($_SERVER['SCRIPT_NAME'], 'update.php')) {
  566. drupal_set_message($entry, 'error');
  567. }
  568. watchdog('php', '%message in %file on line %line.', array('%error' => $types[$errno], '%message' => $message, '%file' => $filename, '%line' => $line), WATCHDOG_ERROR);
  569. }
  570. }
  571. function _fix_gpc_magic(&$item) {
  572. if (is_array($item)) {
  573. array_walk($item, '_fix_gpc_magic');
  574. }
  575. else {
  576. $item = stripslashes($item);
  577. }
  578. }
  579. /**
  580. * Helper function to strip slashes from $_FILES skipping over the tmp_name keys
  581. * since PHP generates single backslashes for file paths on Windows systems.
  582. *
  583. * tmp_name does not have backslashes added see
  584. * http://php.net/manual/en/features.file-upload.php#42280
  585. */
  586. function _fix_gpc_magic_files(&$item, $key) {
  587. if ($key != 'tmp_name') {
  588. if (is_array($item)) {
  589. array_walk($item, '_fix_gpc_magic_files');
  590. }
  591. else {
  592. $item = stripslashes($item);
  593. }
  594. }
  595. }
  596. /**
  597. * Fix double-escaping problems caused by "magic quotes" in some PHP installations.
  598. */
  599. function fix_gpc_magic() {
  600. static $fixed = FALSE;
  601. if (!$fixed && ini_get('magic_quotes_gpc')) {
  602. array_walk($_GET, '_fix_gpc_magic');
  603. array_walk($_POST, '_fix_gpc_magic');
  604. array_walk($_COOKIE, '_fix_gpc_magic');
  605. array_walk($_REQUEST, '_fix_gpc_magic');
  606. array_walk($_FILES, '_fix_gpc_magic_files');
  607. $fixed = TRUE;
  608. }
  609. }
  610. /**
  611. * Translate strings to the page language or a given language.
  612. *
  613. * Human-readable text that will be displayed somewhere within a page should
  614. * be run through the t() function.
  615. *
  616. * Examples:
  617. * @code
  618. * if (!$info || !$info['extension']) {
  619. * form_set_error('picture_upload', t('The uploaded file was not an image.'));
  620. * }
  621. *
  622. * $form['submit'] = array(
  623. * '#type' => 'submit',
  624. * '#value' => t('Log in'),
  625. * );
  626. * @endcode
  627. *
  628. * Any text within t() can be extracted by translators and changed into
  629. * the equivalent text in their native language.
  630. *
  631. * Special variables called "placeholders" are used to signal dynamic
  632. * information in a string which should not be translated. Placeholders
  633. * can also be used for text that may change from time to time (such as
  634. * link paths) to be changed without requiring updates to translations.
  635. *
  636. * For example:
  637. * @code
  638. * $output = t('There are currently %members and %visitors online.', array(
  639. * '%members' => format_plural($total_users, '1 user', '@count users'),
  640. * '%visitors' => format_plural($guests->count, '1 guest', '@count guests')));
  641. * @endcode
  642. *
  643. * There are three styles of placeholders:
  644. * - !variable, which indicates that the text should be inserted as-is. This is
  645. * useful for inserting variables into things like e-mail.
  646. * @code
  647. * $message[] = t("If you don't want to receive such e-mails, you can change your settings at !url.", array('!url' => url("user/$account->uid", array('absolute' => TRUE))));
  648. * @endcode
  649. *
  650. * - @variable, which indicates that the text should be run through
  651. * check_plain, to escape HTML characters. Use this for any output that's
  652. * displayed within a Drupal page.
  653. * @code
  654. * drupal_set_title($title = t("@name's blog", array('@name' => $account->name)));
  655. * @endcode
  656. *
  657. * - %variable, which indicates that the string should be HTML escaped and
  658. * highlighted with theme_placeholder() which shows up by default as
  659. * <em>emphasized</em>.
  660. * @code
  661. * $message = t('%name-from sent %name-to an e-mail.', array('%name-from' => $user->name, '%name-to' => $account->name));
  662. * @endcode
  663. *
  664. * When using t(), try to put entire sentences and strings in one t() call.
  665. * This makes it easier for translators, as it provides context as to what
  666. * each word refers to. HTML markup within translation strings is allowed, but
  667. * should be avoided if possible. The exception are embedded links; link
  668. * titles add a context for translators, so should be kept in the main string.
  669. *
  670. * Here is an example of incorrect usage of t():
  671. * @code
  672. * $output .= t('<p>Go to the @contact-page.</p>', array('@contact-page' => l(t('contact page'), 'contact')));
  673. * @endcode
  674. *
  675. * Here is an example of t() used correctly:
  676. * @code
  677. * $output .= '<p>'. t('Go to the <a href="@contact-page">contact page</a>.', array('@contact-page' => url('contact'))) .'</p>';
  678. * @endcode
  679. *
  680. * Avoid escaping quotation marks wherever possible.
  681. *
  682. * Incorrect:
  683. * @code
  684. * $output .= t('Don\'t click me.');
  685. * @endcode
  686. *
  687. * Correct:
  688. * @code
  689. * $output .= t("Don't click me.");
  690. * @endcode
  691. *
  692. * Because t() is designed for handling code-based strings, in almost all
  693. * cases, the actual string and not a variable must be passed through t().
  694. *
  695. * Extraction of translations is done based on the strings contained in t()
  696. * calls. If a variable is passed through t(), the content of the variable
  697. * cannot be extracted from the file for translation.
  698. *
  699. * Incorrect:
  700. * @code
  701. * $message = 'An error occurred.';
  702. * drupal_set_message(t($message), 'error');
  703. * $output .= t($message);
  704. * @endcode
  705. *
  706. * Correct:
  707. * @code
  708. * $message = t('An error occurred.');
  709. * drupal_set_message($message, 'error');
  710. * $output .= $message;
  711. * @endcode
  712. *
  713. * The only case in which variables can be passed safely through t() is when
  714. * code-based versions of the same strings will be passed through t() (or
  715. * otherwise extracted) elsewhere.
  716. *
  717. * In some cases, modules may include strings in code that can't use t()
  718. * calls. For example, a module may use an external PHP application that
  719. * produces strings that are loaded into variables in Drupal for output.
  720. * In these cases, module authors may include a dummy file that passes the
  721. * relevant strings through t(). This approach will allow the strings to be
  722. * extracted.
  723. *
  724. * Sample external (non-Drupal) code:
  725. * @code
  726. * class Time {
  727. * public $yesterday = 'Yesterday';
  728. * public $today = 'Today';
  729. * public $tomorrow = 'Tomorrow';
  730. * }
  731. * @endcode
  732. *
  733. * Sample dummy file.
  734. * @code
  735. * // Dummy function included in example.potx.inc.
  736. * function example_potx() {
  737. * $strings = array(
  738. * t('Yesterday'),
  739. * t('Today'),
  740. * t('Tomorrow'),
  741. * );
  742. * // No return value needed, since this is a dummy function.
  743. * }
  744. * @endcode
  745. *
  746. * Having passed strings through t() in a dummy function, it is then
  747. * okay to pass variables through t().
  748. *
  749. * Correct (if a dummy file was used):
  750. * @code
  751. * $time = new Time();
  752. * $output .= t($time->today);
  753. * @endcode
  754. *
  755. * However tempting it is, custom data from user input or other non-code
  756. * sources should not be passed through t(). Doing so leads to the following
  757. * problems and errors:
  758. * - The t() system doesn't support updates to existing strings. When user
  759. * data is updated, the next time it's passed through t() a new record is
  760. * created instead of an update. The database bloats over time and any
  761. * existing translations are orphaned with each update.
  762. * - The t() system assumes any data it receives is in English. User data may
  763. * be in another language, producing translation errors.
  764. * - The "Built-in interface" text group in the locale system is used to
  765. * produce translations for storage in .po files. When non-code strings are
  766. * passed through t(), they are added to this text group, which is rendered
  767. * inaccurate since it is a mix of actual interface strings and various user
  768. * input strings of uncertain origin.
  769. *
  770. * Incorrect:
  771. * @code
  772. * $item = item_load();
  773. * $output .= check_plain(t($item['title']));
  774. * @endcode
  775. *
  776. * Instead, translation of these data can be done through the locale system,
  777. * either directly or through helper functions provided by contributed
  778. * modules.
  779. * @see hook_locale()
  780. *
  781. * During installation, st() is used in place of t(). Code that may be called
  782. * during installation or during normal operation should use the get_t()
  783. * helper function.
  784. * @see st()
  785. * @see get_t()
  786. *
  787. * @param $string
  788. * A string containing the English string to translate.
  789. * @param $args
  790. * An associative array of replacements to make after translation. Incidences
  791. * of any key in this array are replaced with the corresponding value. Based
  792. * on the first character of the key, the value is escaped and/or themed:
  793. * - !variable: inserted as is
  794. * - @variable: escape plain text to HTML (check_plain)
  795. * - %variable: escape text and theme as a placeholder for user-submitted
  796. * content (check_plain + theme_placeholder)
  797. * @param $langcode
  798. * Optional language code to translate to a language other than what is used
  799. * to display the page.
  800. * @return
  801. * The translated string.
  802. */
  803. function t($string, $args = array(), $langcode = NULL) {
  804. global $language;
  805. static $custom_strings;
  806. $langcode = isset($langcode) ? $langcode : $language->language;
  807. // First, check for an array of customized strings. If present, use the array
  808. // *instead of* database lookups. This is a high performance way to provide a
  809. // handful of string replacements. See settings.php for examples.
  810. // Cache the $custom_strings variable to improve performance.
  811. if (!isset($custom_strings[$langcode])) {
  812. $custom_strings[$langcode] = variable_get('locale_custom_strings_'. $langcode, array());
  813. }
  814. // Custom strings work for English too, even if locale module is disabled.
  815. if (isset($custom_strings[$langcode][$string])) {
  816. $string = $custom_strings[$langcode][$string];
  817. }
  818. // Translate with locale module if enabled.
  819. elseif (function_exists('locale') && $langcode != 'en') {
  820. $string = locale($string, $langcode);
  821. }
  822. if (empty($args)) {
  823. return $string;
  824. }
  825. else {
  826. // Transform arguments before inserting them.
  827. foreach ($args as $key => $value) {
  828. switch ($key[0]) {
  829. case '@':
  830. // Escaped only.
  831. $args[$key] = check_plain($value);
  832. break;
  833. case '%':
  834. default:
  835. // Escaped and placeholder.
  836. $args[$key] = theme('placeholder', $value);
  837. break;
  838. case '!':
  839. // Pass-through.
  840. }
  841. }
  842. return strtr($string, $args);
  843. }
  844. }
  845. /**
  846. * @defgroup validation Input validation
  847. * @{
  848. * Functions to validate user input.
  849. */
  850. /**
  851. * Verifies the syntax of the given e-mail address.
  852. *
  853. * See RFC 2822 for details.
  854. *
  855. * @param $mail
  856. * A string containing an e-mail address.
  857. * @return
  858. * 1 if the email address is valid, 0 if it is invalid or empty, and FALSE if
  859. * there is an input error (such as passing in an array instead of a string).
  860. */
  861. function valid_email_address($mail) {
  862. $user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
  863. $domain = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+';
  864. $ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
  865. $ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';
  866. return preg_match("/^$user@($domain|(\[($ipv4|$ipv6)\]))$/", $mail);
  867. }
  868. /**
  869. * Verify the syntax of the given URL.
  870. *
  871. * This function should only be used on actual URLs. It should not be used for
  872. * Drupal menu paths, which can contain arbitrary characters.
  873. * Valid values per RFC 3986.
  874. *
  875. * @param $url
  876. * The URL to verify.
  877. * @param $absolute
  878. * Whether the URL is absolute (beginning with a scheme such as "http:").
  879. * @return
  880. * TRUE if the URL is in a valid format.
  881. */
  882. function valid_url($url, $absolute = FALSE) {
  883. if ($absolute) {
  884. return (bool)preg_match("
  885. /^ # Start at the beginning of the text
  886. (?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
  887. (?: # Userinfo (optional) which is typically
  888. (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
  889. (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
  890. )?
  891. (?:
  892. (?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
  893. |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
  894. )
  895. (?::[0-9]+)? # Server port number (optional)
  896. (?:[\/|\?]
  897. (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
  898. *)?
  899. $/xi", $url);
  900. }
  901. else {
  902. return (bool)preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url);
  903. }
  904. }
  905. /**
  906. * @} End of "defgroup validation".
  907. */
  908. /**
  909. * Register an event for the current visitor (hostname/IP) to the flood control mechanism.
  910. *
  911. * @param $name
  912. * The name of an event.
  913. */
  914. function flood_register_event($name) {
  915. db_query("INSERT INTO {flood} (event, hostname, timestamp) VALUES ('%s', '%s', %d)", $name, ip_address(), time());
  916. }
  917. /**
  918. * Check if the current visitor (hostname/IP) is allowed to proceed with the specified event.
  919. *
  920. * The user is allowed to proceed if he did not trigger the specified event more
  921. * than $threshold times per hour.
  922. *
  923. * @param $name
  924. * The name of the event.
  925. * @param $threshold
  926. * The maximum number of the specified event per hour (per visitor).
  927. * @return
  928. * True if the user did not exceed the hourly threshold. False otherwise.
  929. */
  930. function flood_is_allowed($name, $threshold) {
  931. $number = db_result(db_query("SELECT COUNT(*) FROM {flood} WHERE event = '%s' AND hostname = '%s' AND timestamp > %d", $name, ip_address(), time() - 3600));
  932. return ($number < $threshold ? TRUE : FALSE);
  933. }
  934. function check_file($filename) {
  935. return is_uploaded_file($filename);
  936. }
  937. /**
  938. * Prepare a URL for use in an HTML attribute. Strips harmful protocols.
  939. */
  940. function check_url($uri) {
  941. return filter_xss_bad_protocol($uri, FALSE);
  942. }
  943. /**
  944. * @defgroup format Formatting
  945. * @{
  946. * Functions to format numbers, strings, dates, etc.
  947. */
  948. /**
  949. * Formats an RSS channel.
  950. *
  951. * Arbitrary elements may be added using the $args associative array.
  952. */
  953. function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
  954. global $language;
  955. $langcode = $langcode ? $langcode : $language->language;
  956. $output = "<channel>\n";
  957. $output .= ' <title>'. check_plain($title) ."</title>\n";
  958. $output .= ' <link>'. check_url($link) ."</link>\n";
  959. // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
  960. // We strip all HTML tags, but need to prevent double encoding from properly
  961. // escaped source data (such as &amp becoming &amp;amp;).
  962. $output .= ' <description>'. check_plain(decode_entities(strip_tags($description))) ."</description>\n";
  963. $output .= ' <language>'. check_plain($langcode) ."</language>\n";
  964. $output .= format_xml_elements($args);
  965. $output .= $items;
  966. $output .= "</channel>\n";
  967. return $output;
  968. }
  969. /**
  970. * Format a single RSS item.
  971. *
  972. * Arbitrary elements may be added using the $args associative array.
  973. */
  974. function format_rss_item($title, $link, $description, $args = array()) {
  975. $output = "<item>\n";
  976. $output .= ' <title>'. check_plain($title) ."</title>\n";
  977. $output .= ' <link>'. check_url($link) ."</link>\n";
  978. $output .= ' <description>'. check_plain($description) ."</description>\n";
  979. $output .= format_xml_elements($args);
  980. $output .= "</item>\n";
  981. return $output;
  982. }
  983. /**
  984. * Format XML elements.
  985. *
  986. * @param $array
  987. * An array where each item represent an element and is either a:
  988. * - (key => value) pair (<key>value</key>)
  989. * - Associative array with fields:
  990. * - 'key': element name
  991. * - 'value': element contents
  992. * - 'attributes': associative array of element attributes
  993. *
  994. * In both cases, 'value' can be a simple string, or it can be another array
  995. * with the same format as $array itself for nesting.
  996. */
  997. function format_xml_elements($array) {
  998. $output = '';
  999. foreach ($array as $key => $value) {
  1000. if (is_numeric($key)) {
  1001. if ($value['key']) {
  1002. $output .= ' <'. $value['key'];
  1003. if (isset($value['attributes']) && is_array($value['attributes'])) {
  1004. $output .= drupal_attributes($value['attributes']);
  1005. }
  1006. if (isset($value['value']) && $value['value'] != '') {
  1007. $output .= '>'. (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) .'</'. $value['key'] .">\n";
  1008. }
  1009. else {
  1010. $output .= " />\n";
  1011. }
  1012. }
  1013. }
  1014. else {
  1015. $output .= ' <'. $key .'>'. (is_array($value) ? format_xml_elements($value) : check_plain($value)) ."</$key>\n";
  1016. }
  1017. }
  1018. return $output;
  1019. }
  1020. /**
  1021. * Format a string containing a count of items.
  1022. *
  1023. * This function ensures that the string is pluralized correctly. Since t() is
  1024. * called by this function, make sure not to pass already-localized strings to
  1025. * it.
  1026. *
  1027. * For example:
  1028. * @code
  1029. * $output = format_plural($node->comment_count, '1 comment', '@count comments');
  1030. * @endcode
  1031. *
  1032. * Example with additional replacements:
  1033. * @code
  1034. * $output = format_plural($update_count,
  1035. * 'Changed the content type of 1 post from %old-type to %new-type.',
  1036. * 'Changed the content type of @count posts from %old-type to %new-type.',
  1037. * array('%old-type' => $info->old_type, '%new-type' => $info->new_type)));
  1038. * @endcode
  1039. *
  1040. * @param $count
  1041. * The item count to display.
  1042. * @param $singular
  1043. * The string for the singular case. Please make sure it is clear this is
  1044. * singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
  1045. * Do not use @count in the singular string.
  1046. * @param $plural
  1047. * The string for the plural case. Please make sure it is clear this is plural,
  1048. * to ease translation. Use @count in place of the item count, as in "@count
  1049. * new comments".
  1050. * @param $args
  1051. * An associative array of replacements to make after translation. Incidences
  1052. * of any key in this array are replaced with the corresponding value.
  1053. * Based on the first character of the key, the value is escaped and/or themed:
  1054. * - !variable: inserted as is
  1055. * - @variable: escape plain text to HTML (check_plain)
  1056. * - %variable: escape text and theme as a placeholder for user-submitted
  1057. * content (check_plain + theme_placeholder)
  1058. * Note that you do not need to include @count in this array.
  1059. * This replacement is done automatically for the plural case.
  1060. * @param $langcode
  1061. * Optional language code to translate to a language other than
  1062. * what is used to display the page.
  1063. * @return
  1064. * A translated string.
  1065. */
  1066. function format_plural($count, $singular, $plural, $args = array(), $langcode = NULL) {
  1067. $args['@count'] = $count;
  1068. if ($count == 1) {
  1069. return t($singular, $args, $langcode);
  1070. }
  1071. // Get the plural index through the gettext formula.
  1072. $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, $langcode) : -1;
  1073. // Backwards compatibility.
  1074. if ($index < 0) {
  1075. return t($plural, $args, $langcode);
  1076. }
  1077. else {
  1078. switch ($index) {
  1079. case "0":
  1080. return t($singular, $args, $langcode);
  1081. case "1":
  1082. return t($plural, $args, $langcode);
  1083. default:
  1084. unset($args['@count']);
  1085. $args['@count['. $index .']'] = $count;
  1086. return t(strtr($plural, array('@count' => '@count['. $index .']')), $args, $langcode);
  1087. }
  1088. }
  1089. }
  1090. /**
  1091. * Parse a given byte count.
  1092. *
  1093. * @param $size
  1094. * A size expressed as a number of bytes with optional SI size and unit
  1095. * suffix (e.g. 2, 3K, 5MB, 10G).
  1096. * @return
  1097. * An integer representation of the size.
  1098. */
  1099. function parse_size($size) {
  1100. $suffixes = array(
  1101. '' => 1,
  1102. 'k' => 1024,
  1103. 'm' => 1048576, // 1024 * 1024
  1104. 'g' => 1073741824, // 1024 * 1024 * 1024
  1105. );
  1106. if (preg_match('/([0-9]+)\s*(k|m|g)?(b?(ytes?)?)/i', $size, $match)) {
  1107. return $match[1] * $suffixes[drupal_strtolower($match[2])];
  1108. }
  1109. }
  1110. /**
  1111. * Generate a string representation for the given byte count.
  1112. *
  1113. * @param $size
  1114. * A size in bytes.
  1115. * @param $langcode
  1116. * Optional language code to translate to a language other than what is used
  1117. * to display the page.
  1118. * @return
  1119. * A translated string representation of the size.
  1120. */
  1121. function format_size($size, $langcode = NULL) {
  1122. if ($size < 1024) {
  1123. return format_plural($size, '1 byte', '@count bytes', array(), $langcode);
  1124. }
  1125. else {
  1126. $size = round($size / 1024, 2);
  1127. $suffix = t('KB', array(), $langcode);
  1128. if ($size >= 1024) {
  1129. $size = round($size / 1024, 2);
  1130. $suffix = t('MB', array(), $langcode);
  1131. }
  1132. return t('@size @suffix', array('@size' => $size, '@suffix' => $suffix), $langcode);
  1133. }
  1134. }
  1135. /**
  1136. * Format a time interval with the requested granularity.
  1137. *
  1138. * @param $timestamp
  1139. * The length of the interval in seconds.
  1140. * @param $granularity
  1141. * How many different units to display in the string.
  1142. * @param $langcode
  1143. * Optional language code to translate to a language other than
  1144. * what is used to display the page.
  1145. * @return
  1146. * A translated string representation of the interval.
  1147. */
  1148. function format_interval($timestamp, $granularity = 2, $langcode = NULL) {
  1149. $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);
  1150. $output = '';
  1151. foreach ($units as $key => $value) {
  1152. $key = explode('|', $key);
  1153. if ($timestamp >= $value) {
  1154. $output .= ($output ? ' ' : '') . format_plural(floor($timestamp / $value), $key[0], $key[1], array(), $langcode);
  1155. $timestamp %= $value;
  1156. $granularity--;
  1157. }
  1158. if ($granularity == 0) {
  1159. break;
  1160. }
  1161. }
  1162. return $output ? $output : t('0 sec', array(), $langcode);
  1163. }
  1164. /**
  1165. * Format a date with the given configured format or a custom format string.
  1166. *
  1167. * Drupal allows administrators to select formatting strings for 'small',
  1168. * 'medium' and 'large' date formats. This function can handle these formats,
  1169. * as well as any custom format.
  1170. *
  1171. * @param $timestamp
  1172. * The exact date to format, as a UNIX timestamp.
  1173. * @param $type
  1174. * The format to use. Can be "small", "medium" or "large" for the preconfigured
  1175. * date formats. If "custom" is specified, then $format is required as well.
  1176. * @param $format
  1177. * A PHP date format string as required by date(). A backslash should be used
  1178. * before a character to avoid interpreting the character as part of a date
  1179. * format.
  1180. * @param $timezone
  1181. * Time zone offset in seconds; if omitted, the user's time zone is used.
  1182. * @param $langcode
  1183. * Optional language code to translate to a language other than what is used
  1184. * to display the page.
  1185. * @return
  1186. * A translated date string in the requested format.
  1187. */
  1188. function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
  1189. if (!isset($timezone)) {
  1190. global $user;
  1191. if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
  1192. $timezone = $user->timezone;
  1193. }
  1194. else {
  1195. $timezone = variable_get('date_default_timezone', 0);
  1196. }
  1197. }
  1198. $timestamp += $timezone;
  1199. switch ($type) {
  1200. case 'small':
  1201. $format = variable_get('date_format_short', 'm/d/Y - H:i');
  1202. break;
  1203. case 'large':
  1204. $format = variable_get('date_format_long', 'l, F j, Y - H:i');
  1205. break;
  1206. case 'custom':
  1207. // No change to format.
  1208. break;
  1209. case 'medium':
  1210. default:
  1211. $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
  1212. }
  1213. $max = strlen($format);
  1214. $date = '';
  1215. for ($i = 0; $i < $max; $i++) {
  1216. $c = $format[$i];
  1217. if (strpos('AaDlM', $c) !== FALSE) {
  1218. $date .= t(gmdate($c, $timestamp), array(), $langcode);
  1219. }
  1220. else if ($c == 'F') {
  1221. // Special treatment for long month names: May is both an abbreviation
  1222. // and a full month name in English, but other languages have
  1223. // different abbreviations.
  1224. $date .= trim(t('!long-month-name '. gmdate($c, $timestamp), array('!long-month-name' => ''), $langcode));
  1225. }
  1226. else if (strpos('BdgGhHiIjLmnsStTUwWYyz', $c) !== FALSE) {
  1227. $date .= gmdate($c, $timestamp);
  1228. }
  1229. else if ($c == 'r') {
  1230. $date .= format_date($timestamp - $timezone, 'custom', 'D, d M Y H:i:s O', $timezone, $langcode);
  1231. }
  1232. else if ($c == 'O') {
  1233. $date .= sprintf('%s%02d%02d', ($timezone < 0 ? '-' : '+'), abs($timezone / 3600), abs($timezone % 3600) / 60);
  1234. }
  1235. else if ($c == 'Z') {
  1236. $date .= $timezone;
  1237. }
  1238. else if ($c == '\\') {
  1239. $date .= $format[++$i];
  1240. }
  1241. else {
  1242. $date .= $c;
  1243. }
  1244. }
  1245. return $date;
  1246. }
  1247. /**
  1248. * @} End of "defgroup format".
  1249. */
  1250. /**
  1251. * Generates an internal or external URL.
  1252. *
  1253. * When creating links in modules, consider whether l() could be a better
  1254. * alternative than url().
  1255. *
  1256. * @param $path
  1257. * The internal path or external URL being linked to, such as "node/34" or
  1258. * "http://example.com/foo". A few notes:
  1259. * - If you provide a full URL, it will be considered an external URL.
  1260. * - If you provide only the path (e.g. "node/34"), it will be
  1261. * considered an internal link. In this case, it should be a system URL,
  1262. * and it will be replaced with the alias, if one exists. Additional query
  1263. * arguments for internal paths must be supplied in $options['query'], not
  1264. * included in $path.
  1265. * - If you provide an internal path and $options['alias'] is set to TRUE, the
  1266. * path is assumed already to be the correct path alias, and the alias is
  1267. * not looked up.
  1268. * - The special string '<front>' generates a link to the site's base URL.
  1269. * - If your external URL contains a query (e.g. http://example.com/foo?a=b),
  1270. * then you can either URL encode the query keys and values yourself and
  1271. * include them in $path, or use $options['query'] to let this function
  1272. * URL encode them.
  1273. * @param $options
  1274. * An associative array of additional options, with the following elements:
  1275. * - 'query': A URL-encoded query string to append to the link, or an array of
  1276. * query key/value-pairs without any URL-encoding.
  1277. * - 'fragment': A fragment identifier (named anchor) to append to the URL.
  1278. * Do not include the leading '#' character.
  1279. * - 'absolute' (default FALSE): Whether to force the output to be an absolute
  1280. * link (beginning with http:). Useful for links that will be displayed
  1281. * outside the site, such as in an RSS feed.
  1282. * - 'alias' (default FALSE): Whether the given path is a URL alias already.
  1283. * - 'external': Whether the given path is an external URL.
  1284. * - 'language': An optional language object. Used to build the URL to link
  1285. * to and look up the proper alias for the link.
  1286. * - 'base_url': Only used internally, to modify the base URL when a language
  1287. * dependent URL requires so.
  1288. * - 'prefix': Only used internally, to modify the path when a language
  1289. * dependent URL requires so.
  1290. *
  1291. * @return
  1292. * A string containing a URL to the given path.
  1293. */
  1294. function url($path = NULL, $options = array()) {
  1295. // Merge in defaults.
  1296. $options += array(
  1297. 'fragment' => '',
  1298. 'query' => '',
  1299. 'absolute' => FALSE,
  1300. 'alias' => FALSE,
  1301. 'prefix' => ''
  1302. );
  1303. if (!isset($options['external'])) {
  1304. // Return an external link if $path contains an allowed absolute URL.
  1305. // Only call the slow filter_xss_bad_protocol if $path contains a ':' before
  1306. // any / ? or #.
  1307. $colonpos = strpos($path, ':');
  1308. $options['external'] = ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && filter_xss_bad_protocol($path, FALSE) == check_plain($path));
  1309. }
  1310. // May need language dependent rewriting if language.inc is present.
  1311. if (function_exists('language_url_rewrite')) {
  1312. language_url_rewrite($path, $options);
  1313. }
  1314. if ($options['fragment']) {
  1315. $options['fragment'] = '#'. $options['fragment'];
  1316. }
  1317. if (is_array($options['query'])) {
  1318. $options['query'] = drupal_query_string_encode($options['query']);
  1319. }
  1320. if ($options['external']) {
  1321. // Split off the fragment.
  1322. if (strpos($path, '#') !== FALSE) {
  1323. list($path, $old_fragment) = explode('#', $path, 2);
  1324. if (isset($old_fragment) && !$options['fragment']) {
  1325. $options['fragment'] = '#'. $old_fragment;
  1326. }
  1327. }
  1328. // Append the query.
  1329. if ($options['query']) {
  1330. $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . $options['query'];
  1331. }
  1332. // Reassemble.
  1333. return $path . $options['fragment'];
  1334. }
  1335. global $base_url;
  1336. static $script;
  1337. if (!isset($script)) {
  1338. // On some web servers, such as IIS, we can't omit "index.php". So, we
  1339. // generate "index.php?q=foo" instead of "?q=foo" on anything that is not
  1340. // Apache.
  1341. $script = (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') === FALSE) ? 'index.php'

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