PageRenderTime 71ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/includes/common.inc

https://bitbucket.org/pentababu/test
PHP | 3799 lines | 2543 code | 202 blank | 1054 comment | 262 complexity | 42d7e06a66928ce521a478824ef07689 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, LGPL-2.1, GPL-2.0

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

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