PageRenderTime 73ms CodeModel.GetById 21ms 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
  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' : '';
  1342. }
  1343. if (!isset($options['base_url'])) {
  1344. // The base_url might be rewritten from the language rewrite in domain mode.
  1345. $options['base_url'] = $base_url;
  1346. }
  1347. // Preserve the original path before aliasing.
  1348. $original_path = $path;
  1349. // The special path '<front>' links to the default front page.
  1350. if ($path == '<front>') {
  1351. $path = '';
  1352. }
  1353. elseif (!empty($path) && !$options['alias']) {
  1354. $path = drupal_get_path_alias($path, isset($options['language']) ? $options['language']->language : '');
  1355. }
  1356. if (function_exists('custom_url_rewrite_outbound')) {
  1357. // Modules may alter outbound links by reference.
  1358. custom_url_rewrite_outbound($path, $options, $original_path);
  1359. }
  1360. $base = $options['absolute'] ? $options['base_url'] .'/' : base_path();
  1361. $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
  1362. $path = drupal_urlencode($prefix . $path);
  1363. if (variable_get('clean_url', '0')) {
  1364. // With Clean URLs.
  1365. if ($options['query']) {
  1366. return $base . $path .'?'. $options['query'] . $options['fragment'];
  1367. }
  1368. else {
  1369. return $base . $path . $options['fragment'];
  1370. }
  1371. }
  1372. else {
  1373. // Without Clean URLs.
  1374. $variables = array();
  1375. if (!empty($path)) {
  1376. $variables[] = 'q='. $path;
  1377. }
  1378. if (!empty($options['query'])) {
  1379. $variables[] = $options['query'];
  1380. }
  1381. if ($query = join('&', $variables)) {
  1382. return $base . $script .'?'. $query . $options['fragment'];
  1383. }
  1384. else {
  1385. return $base . $options['fragment'];
  1386. }
  1387. }
  1388. }
  1389. /**
  1390. * Format an attribute string to insert in a tag.
  1391. *
  1392. * @param $attributes
  1393. * An associative array of HTML attributes.
  1394. * @return
  1395. * An HTML string ready for insertion in a tag.
  1396. */
  1397. function drupal_attributes($attributes = array()) {
  1398. if (is_array($attributes)) {
  1399. $t = '';
  1400. foreach ($attributes as $key => $value) {
  1401. $t .= " $key=".'"'. check_plain($value) .'"';
  1402. }
  1403. return $t;
  1404. }
  1405. }
  1406. /**
  1407. * Formats an internal or external URL link as an HTML anchor tag.
  1408. *
  1409. * This function correctly handles aliased paths, and adds an 'active' class
  1410. * attribute to links that point to the current page (for theming), so all
  1411. * internal links output by modules should be generated by this function if
  1412. * possible.
  1413. *
  1414. * @param $text
  1415. * The link text for the anchor tag.
  1416. * @param $path
  1417. * The internal path or external URL being linked to, such as "node/34" or
  1418. * "http://example.com/foo". After the url() function is called to construct
  1419. * the URL from $path and $options, the resulting URL is passed through
  1420. * check_url() before it is inserted into the HTML anchor tag, to ensure
  1421. * well-formed HTML. See url() for more information and notes.
  1422. * @param $options
  1423. * An associative array of additional options, with the following elements:
  1424. * - 'attributes': An associative array of HTML attributes to apply to the
  1425. * anchor tag.
  1426. * - 'html' (default FALSE): Whether $text is HTML or just plain-text. For
  1427. * example, to make an image tag into a link, this must be set to TRUE, or
  1428. * you will see the escaped HTML image tag.
  1429. * - 'language': An optional language object. If the path being linked to is
  1430. * internal to the site, $options['language'] is used to look up the alias
  1431. * for the URL, and to determine whether the link is "active", or pointing
  1432. * to the current page (the language as well as the path must match).This
  1433. * element is also used by url().
  1434. * - Additional $options elements used by the url() function.
  1435. *
  1436. * @return
  1437. * An HTML string containing a link to the given path.
  1438. */
  1439. function l($text, $path, $options = array()) {
  1440. global $language;
  1441. // Merge in defaults.
  1442. $options += array(
  1443. 'attributes' => array(),
  1444. 'html' => FALSE,
  1445. );
  1446. // Append active class.
  1447. if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
  1448. (empty($options['language']) || $options['language']->language == $language->language)) {
  1449. if (isset($options['attributes']['class'])) {
  1450. $options['attributes']['class'] .= ' active';
  1451. }
  1452. else {
  1453. $options['attributes']['class'] = 'active';
  1454. }
  1455. }
  1456. // Remove all HTML and PHP tags from a tooltip. For best performance, we act only
  1457. // if a quick strpos() pre-check gave a suspicion (because strip_tags() is expensive).
  1458. if (isset($options['attributes']['title']) && strpos($options['attributes']['title'], '<') !== FALSE) {
  1459. $options['attributes']['title'] = strip_tags($options['attributes']['title']);
  1460. }
  1461. return '<a href="'. check_url(url($path, $options)) .'"'. drupal_attributes($options['attributes']) .'>'. ($options['html'] ? $text : check_plain($text)) .'</a>';
  1462. }
  1463. /**
  1464. * Perform end-of-request tasks.
  1465. *
  1466. * This function sets the page cache if appropriate, and allows modules to
  1467. * react to the closing of the page by calling hook_exit().
  1468. */
  1469. function drupal_page_footer() {
  1470. // Write the session, and open one if needed.
  1471. drupal_session_commit();
  1472. // Do not cache if cache is disabled or external.
  1473. $cache = variable_get('cache', CACHE_DISABLED);
  1474. if ($cache != CACHE_DISABLED && $cache != CACHE_EXTERNAL) {
  1475. page_set_cache();
  1476. }
  1477. module_invoke_all('exit');
  1478. }
  1479. /**
  1480. * Form an associative array from a linear array.
  1481. *
  1482. * This function walks through the provided array and constructs an associative
  1483. * array out of it. The keys of the resulting array will be the values of the
  1484. * input array. The values will be the same as the keys unless a function is
  1485. * specified, in which case the output of the function is used for the values
  1486. * instead.
  1487. *
  1488. * @param $array
  1489. * A linear array.
  1490. * @param $function
  1491. * A name of a function to apply to all values before output.
  1492. *
  1493. * @return
  1494. * An associative array.
  1495. */
  1496. function drupal_map_assoc($array, $function = NULL) {
  1497. if (!isset($function)) {
  1498. $result = array();
  1499. foreach ($array as $value) {
  1500. $result[$value] = $value;
  1501. }
  1502. return $result;
  1503. }
  1504. elseif (function_exists($function)) {
  1505. $result = array();
  1506. foreach ($array as $value) {
  1507. $result[$value] = $function($value);
  1508. }
  1509. return $result;
  1510. }
  1511. }
  1512. /**
  1513. * Evaluate a string of PHP code.
  1514. *
  1515. * This is a wrapper around PHP's eval(). It uses output buffering to capture both
  1516. * returned and printed text. Unlike eval(), we require code to be surrounded by
  1517. * <?php ?> tags; in other words, we evaluate the code as if it were a stand-alone
  1518. * PHP file.
  1519. *
  1520. * Using this wrapper also ensures that the PHP code which is evaluated can not
  1521. * overwrite any variables in the calling code, unlike a regular eval() call.
  1522. *
  1523. * @param $code
  1524. * The code to evaluate.
  1525. * @return
  1526. * A string containing the printed output of the code, followed by the returned
  1527. * output of the code.
  1528. */
  1529. function drupal_eval($code) {
  1530. global $theme_path, $theme_info, $conf;
  1531. // Store current theme path.
  1532. $old_theme_path = $theme_path;
  1533. // Restore theme_path to the theme, as long as drupal_eval() executes,
  1534. // so code evaluted will not see the caller module as the current theme.
  1535. // If theme info is not initialized get the path from theme_default.
  1536. if (!isset($theme_info)) {
  1537. $theme_path = drupal_get_path('theme', $conf['theme_default']);
  1538. }
  1539. else {
  1540. $theme_path = dirname($theme_info->filename);
  1541. }
  1542. ob_start();
  1543. print eval('?>'. $code);
  1544. $output = ob_get_contents();
  1545. ob_end_clean();
  1546. // Recover original theme path.
  1547. $theme_path = $old_theme_path;
  1548. return $output;
  1549. }
  1550. /**
  1551. * Returns the path to a system item (module, theme, etc.).
  1552. *
  1553. * @param $type
  1554. * The type of the item (i.e. theme, theme_engine, module, profile).
  1555. * @param $name
  1556. * The name of the item for which the path is requested.
  1557. *
  1558. * @return
  1559. * The path to the requested item.
  1560. */
  1561. function drupal_get_path($type, $name) {
  1562. return dirname(drupal_get_filename($type, $name));
  1563. }
  1564. /**
  1565. * Returns the base URL path of the Drupal installation.
  1566. * At the very least, this will always default to /.
  1567. */
  1568. function base_path() {
  1569. return $GLOBALS['base_path'];
  1570. }
  1571. /**
  1572. * Provide a substitute clone() function for PHP4.
  1573. */
  1574. function drupal_clone($object) {
  1575. return version_compare(phpversion(), '5.0') < 0 ? $object : clone($object);
  1576. }
  1577. /**
  1578. * Add a <link> tag to the page's HEAD.
  1579. */
  1580. function drupal_add_link($attributes) {
  1581. drupal_set_html_head('<link'. drupal_attributes($attributes) .' />');
  1582. }
  1583. /**
  1584. * Adds a CSS file to the stylesheet queue.
  1585. *
  1586. * @param $path
  1587. * (optional) The path to the CSS file relative to the base_path(), e.g.,
  1588. * modules/devel/devel.css.
  1589. *
  1590. * Modules should always prefix the names of their CSS files with the module
  1591. * name, for example: system-menus.css rather than simply menus.css. Themes
  1592. * can override module-supplied CSS files based on their filenames, and this
  1593. * prefixing helps prevent confusing name collisions for theme developers.
  1594. * See drupal_get_css where the overrides are performed.
  1595. *
  1596. * If the direction of the current language is right-to-left (Hebrew,
  1597. * Arabic, etc.), the function will also look for an RTL CSS file and append
  1598. * it to the list. The name of this file should have an '-rtl.css' suffix.
  1599. * For example a CSS file called 'name.css' will have a 'name-rtl.css'
  1600. * file added to the list, if exists in the same directory. This CSS file
  1601. * should contain overrides for properties which should be reversed or
  1602. * otherwise different in a right-to-left display.
  1603. * @param $type
  1604. * (optional) The type of stylesheet that is being added. Types are: module
  1605. * or theme.
  1606. * @param $media
  1607. * (optional) The media type for the stylesheet, e.g., all, print, screen.
  1608. * @param $preprocess
  1609. * (optional) Should this CSS file be aggregated and compressed if this
  1610. * feature has been turned on under the performance section?
  1611. *
  1612. * What does this actually mean?
  1613. * CSS preprocessing is the process of aggregating a bunch of separate CSS
  1614. * files into one file that is then compressed by removing all extraneous
  1615. * white space.
  1616. *
  1617. * The reason for merging the CSS files is outlined quite thoroughly here:
  1618. * http://www.die.net/musings/page_load_time/
  1619. * "Load fewer external objects. Due to request overhead, one bigger file
  1620. * just loads faster than two smaller ones half its size."
  1621. *
  1622. * However, you should *not* preprocess every file as this can lead to
  1623. * redundant caches. You should set $preprocess = FALSE when:
  1624. *
  1625. * - Your styles are only used rarely on the site. This could be a special
  1626. * admin page, the homepage, or a handful of pages that does not represent
  1627. * the majority of the pages on your site.
  1628. *
  1629. * Typical candidates for caching are for example styles for nodes across
  1630. * the site, or used in the theme.
  1631. * @return
  1632. * An array of CSS files.
  1633. */
  1634. function drupal_add_css($path = NULL, $type = 'module', $media = 'all', $preprocess = TRUE) {
  1635. static $css = array();
  1636. global $language;
  1637. // Create an array of CSS files for each media type first, since each type needs to be served
  1638. // to the browser differently.
  1639. if (isset($path)) {
  1640. // This check is necessary to ensure proper cascading of styles and is faster than an asort().
  1641. if (!isset($css[$media])) {
  1642. $css[$media] = array('module' => array(), 'theme' => array());
  1643. }
  1644. $css[$media][$type][$path] = $preprocess;
  1645. // If the current language is RTL, add the CSS file with RTL overrides.
  1646. if ($language->direction == LANGUAGE_RTL) {
  1647. $rtl_path = str_replace('.css', '-rtl.css', $path);
  1648. if (file_exists($rtl_path)) {
  1649. $css[$media][$type][$rtl_path] = $preprocess;
  1650. }
  1651. }
  1652. }
  1653. return $css;
  1654. }
  1655. /**
  1656. * Returns a themed representation of all stylesheets that should be attached to the page.
  1657. *
  1658. * It loads the CSS in order, with 'module' first, then 'theme' afterwards.
  1659. * This ensures proper cascading of styles so themes can easily override
  1660. * module styles through CSS selectors.
  1661. *
  1662. * Themes may replace module-defined CSS files by adding a stylesheet with the
  1663. * same filename. For example, themes/garland/system-menus.css would replace
  1664. * modules/system/system-menus.css. This allows themes to override complete
  1665. * CSS files, rather than specific selectors, when necessary.
  1666. *
  1667. * If the original CSS file is being overridden by a theme, the theme is
  1668. * responsible for supplying an accompanying RTL CSS file to replace the
  1669. * module's.
  1670. *
  1671. * @param $css
  1672. * (optional) An array of CSS files. If no array is provided, the default
  1673. * stylesheets array is used instead.
  1674. * @return
  1675. * A string of XHTML CSS tags.
  1676. */
  1677. function drupal_get_css($css = NULL) {
  1678. $output = '';
  1679. if (!isset($css)) {
  1680. $css = drupal_add_css();
  1681. }
  1682. $no_module_preprocess = '';
  1683. $no_theme_preprocess = '';
  1684. $preprocess_css = (variable_get('preprocess_css', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
  1685. $directory = file_directory_path();
  1686. $is_writable = is_dir($directory) && is_writable($directory) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC);
  1687. // A dummy query-string is added to filenames, to gain control over
  1688. // browser-caching. The string changes on every update or full cache
  1689. // flush, forcing browsers to load a new copy of the files, as the
  1690. // URL changed.
  1691. $query_string = '?'. substr(variable_get('css_js_query_string', '0'), 0, 1);
  1692. foreach ($css as $media => $types) {
  1693. // If CSS preprocessing is off, we still need to output the styles.
  1694. // Additionally, go through any remaining styles if CSS preprocessing is on and output the non-cached ones.
  1695. foreach ($types as $type => $files) {
  1696. if ($type == 'module') {
  1697. // Setup theme overrides for module styles.
  1698. $theme_styles = array();
  1699. foreach (array_keys($css[$media]['theme']) as $theme_style) {
  1700. $theme_styles[] = basename($theme_style);
  1701. }
  1702. }
  1703. foreach ($types[$type] as $file => $preprocess) {
  1704. // If the theme supplies its own style using the name of the module style, skip its inclusion.
  1705. // This includes any RTL styles associated with its main LTR counterpart.
  1706. if ($type == 'module' && in_array(str_replace('-rtl.css', '.css', basename($file)), $theme_styles)) {
  1707. // Unset the file to prevent its inclusion when CSS aggregation is enabled.
  1708. unset($types[$type][$file]);
  1709. continue;
  1710. }
  1711. // Only include the stylesheet if it exists.
  1712. if (file_exists($file)) {
  1713. if (!$preprocess || !($is_writable && $preprocess_css)) {
  1714. // If a CSS file is not to be preprocessed and it's a module CSS file, it needs to *always* appear at the *top*,
  1715. // regardless of whether preprocessing is on or off.
  1716. if (!$preprocess && $type == 'module') {
  1717. $no_module_preprocess .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. file_create_url($file) . $query_string .'" />'."\n";
  1718. }
  1719. // If a CSS file is not to be preprocessed and it's a theme CSS file, it needs to *always* appear at the *bottom*,
  1720. // regardless of whether preprocessing is on or off.
  1721. else if (!$preprocess && $type == 'theme') {
  1722. $no_theme_preprocess .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. file_create_url($file) . $query_string .'" />'."\n";
  1723. }
  1724. else {
  1725. $output .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. file_create_url($file) . $query_string .'" />'."\n";
  1726. }
  1727. }
  1728. }
  1729. }
  1730. }
  1731. if ($is_writable && $preprocess_css) {
  1732. // Prefix filename to prevent blocking by firewalls which reject files
  1733. // starting with "ad*".
  1734. $filename = 'css_'. md5(serialize($types) . $query_string) .'.css';
  1735. $preprocess_file = drupal_build_css_cache($types, $filename);
  1736. $output .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. file_create_url($preprocess_file) .'" />'."\n";
  1737. }
  1738. }
  1739. return $no_module_preprocess . $output . $no_theme_preprocess;
  1740. }
  1741. /**
  1742. * Aggregate and optimize CSS files, putting them in the files directory.
  1743. *
  1744. * @param $types
  1745. * An array of types of CSS files (e.g., screen, print) to aggregate and
  1746. * compress into one file.
  1747. * @param $filename
  1748. * The name of the aggregate CSS file.
  1749. * @return
  1750. * The name of the CSS file.
  1751. */
  1752. function drupal_build_css_cache($types, $filename) {
  1753. $data = '';
  1754. // Create the css/ within the files folder.
  1755. $csspath = file_create_path('css');
  1756. file_check_directory($csspath, FILE_CREATE_DIRECTORY);
  1757. if (!file_exists($csspath .'/'. $filename)) {
  1758. // Build aggregate CSS file.
  1759. foreach ($types as $type) {
  1760. foreach ($type as $file => $cache) {
  1761. if ($cache) {
  1762. $contents = drupal_load_stylesheet($file, TRUE);
  1763. // Return the path to where this CSS file originated from.
  1764. $base = base_path() . dirname($file) .'/';
  1765. _drupal_build_css_path(NULL, $base);
  1766. // Prefix all paths within this CSS file, ignoring external and absolute paths.
  1767. $data .= preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', '_drupal_build_css_path', $contents);
  1768. }
  1769. }
  1770. }
  1771. // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
  1772. // @import rules must proceed any other style, so we move those to the top.
  1773. $regexp = '/@import[^;]+;/i';
  1774. preg_match_all($regexp, $data, $matches);
  1775. $data = preg_replace($regexp, '', $data);
  1776. $data = implode('', $matches[0]) . $data;
  1777. // Create the CSS file.
  1778. file_save_data($data, $csspath .'/'. $filename, FILE_EXISTS_REPLACE);
  1779. }
  1780. return $csspath .'/'. $filename;
  1781. }
  1782. /**
  1783. * Helper function for drupal_build_css_cache().
  1784. *
  1785. * This function will prefix all paths within a CSS file.
  1786. */
  1787. function _drupal_build_css_path($matches, $base = NULL) {
  1788. static $_base;
  1789. // Store base path for preg_replace_callback.
  1790. if (isset($base)) {
  1791. $_base = $base;
  1792. }
  1793. // Prefix with base and remove '../' segments where possible.
  1794. $path = $_base . $matches[1];
  1795. $last = '';
  1796. while ($path != $last) {
  1797. $last = $path;
  1798. $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
  1799. }
  1800. return 'url('. $path .')';
  1801. }
  1802. /**
  1803. * Loads the stylesheet and resolves all @import commands.
  1804. *
  1805. * Loads a stylesheet and replaces @import commands with the contents of the
  1806. * imported file. Use this instead of file_get_contents when processing
  1807. * stylesheets.
  1808. *
  1809. * The returned contents are compressed removing white space and comments only
  1810. * when CSS aggregation is enabled. This optimization will not apply for
  1811. * color.module enabled themes with CSS aggregation turned off.
  1812. *
  1813. * @param $file
  1814. * Name of the stylesheet to be processed.
  1815. * @param $optimize
  1816. * Defines if CSS contents should be compressed or not.
  1817. * @return
  1818. * Contents of the stylesheet including the imported stylesheets.
  1819. */
  1820. function drupal_load_stylesheet($file, $optimize = NULL) {
  1821. static $_optimize;
  1822. // Store optimization parameter for preg_replace_callback with nested @import loops.
  1823. if (isset($optimize)) {
  1824. $_optimize = $optimize;
  1825. }
  1826. $contents = '';
  1827. if (file_exists($file)) {
  1828. // Load the local CSS stylesheet.
  1829. $contents = file_get_contents($file);
  1830. // Change to the current stylesheet's directory.
  1831. $cwd = getcwd();
  1832. chdir(dirname($file));
  1833. // Replaces @import commands with the actual stylesheet content.
  1834. // This happens recursively but omits external files.
  1835. $contents = preg_replace_callback('/@import\s*(?:url\()?[\'"]?(?![a-z]+:)([^\'"\()]+)[\'"]?\)?;/', '_drupal_load_stylesheet', $contents);
  1836. // Remove multiple charset declarations for standards compliance (and fixing Safari problems).
  1837. $contents = preg_replace('/^@charset\s+[\'"](\S*)\b[\'"];/i', '', $contents);
  1838. if ($_optimize) {
  1839. // Perform some safe CSS optimizations.
  1840. // Regexp to match comment blocks.
  1841. $comment = '/\*[^*]*\*+(?:[^/*][^*]*\*+)*/';
  1842. // Regexp to match double quoted strings.
  1843. $double_quot = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
  1844. // Regexp to match single quoted strings.
  1845. $single_quot = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'";
  1846. $contents = preg_replace_callback(
  1847. "<$double_quot|$single_quot|$comment>Ss", // Match all comment blocks along
  1848. "_process_comment", // with double/single quoted strings
  1849. $contents); // and feed them to _process_comment().
  1850. $contents = preg_replace(
  1851. '<\s*([@{}:;,]|\)\s|\s\()\s*>S', // Remove whitespace around separators,
  1852. '\1', $contents); // but keep space around parentheses.
  1853. // End the file with a new line.
  1854. $contents .= "\n";
  1855. }
  1856. // Change back directory.
  1857. chdir($cwd);
  1858. }
  1859. return $contents;
  1860. }
  1861. /**
  1862. * Process comment blocks.
  1863. *
  1864. * This is the callback function for the preg_replace_callback()
  1865. * used in drupal_load_stylesheet_content(). Support for comment
  1866. * hacks is implemented here.
  1867. */
  1868. function _process_comment($matches) {
  1869. static $keep_nextone = FALSE;
  1870. // Quoted string, keep it.
  1871. if ($matches[0][0] == "'" || $matches[0][0] == '"') {
  1872. return $matches[0];
  1873. }
  1874. // End of IE-Mac hack, keep it.
  1875. if ($keep_nextone) {
  1876. $keep_nextone = FALSE;
  1877. return $matches[0];
  1878. }
  1879. switch (strrpos($matches[0], '\\')) {
  1880. case FALSE :
  1881. // No backslash, strip it.
  1882. return '';
  1883. case drupal_strlen($matches[0])-3 :
  1884. // Ends with \*/ so is a multi line IE-Mac hack, keep the next one also.
  1885. $keep_nextone = TRUE;
  1886. return '/*_\*/';
  1887. default :
  1888. // Single line IE-Mac hack.
  1889. return '/*\_*/';
  1890. }
  1891. }
  1892. /**
  1893. * Loads stylesheets recursively and returns contents with corrected paths.
  1894. *
  1895. * This function is used for recursive loading of stylesheets and
  1896. * returns the stylesheet content with all url() paths corrected.
  1897. */
  1898. function _drupal_load_stylesheet($matches) {
  1899. $filename = $matches[1];
  1900. // Load the imported stylesheet and replace @import commands in there as well.
  1901. $file = drupal_load_stylesheet($filename);
  1902. // Determine the file's directory.
  1903. $directory = dirname($filename);
  1904. // If the file is in the current directory, make sure '.' doesn't appear in
  1905. // the url() path.
  1906. $directory = $directory == '.' ? '' : $directory .'/';
  1907. // Alter all internal url() paths. Leave external paths alone. We don't need
  1908. // to normalize absolute paths here (i.e. remove folder/... segments) because
  1909. // that will be done later.
  1910. return preg_replace('/url\s*\(([\'"]?)(?![a-z]+:|\/+)/i', 'url(\1'. $directory, $file);
  1911. }
  1912. /**
  1913. * Delete all cached CSS files.
  1914. */
  1915. function drupal_clear_css_cache() {
  1916. file_scan_directory(file_create_path('css'), '.*', array('.', '..', 'CVS'), 'file_delete', TRUE);
  1917. }
  1918. /**
  1919. * Add a JavaScript file, setting or inline code to the page.
  1920. *
  1921. * The behavior of this function depends on the parameters it is called with.
  1922. * Generally, it handles the addition of JavaScript to the page, either as
  1923. * reference to an existing file or as inline code. The following actions can be
  1924. * performed using this function:
  1925. *
  1926. * - Add a file ('core', 'module' and 'theme'):
  1927. * Adds a reference to a JavaScript file to the page. JavaScript files
  1928. * are placed in a certain order, from 'core' first, to 'module' and finally
  1929. * 'theme' so that files, that are added later, can override previously added
  1930. * files with ease.
  1931. *
  1932. * - Add inline JavaScript code ('inline'):
  1933. * Executes a piece of JavaScript code on the current page by placing the code
  1934. * directly in the page. This can, for example, be useful to tell the user that
  1935. * a new message arrived, by opening a pop up, alert box etc.
  1936. *
  1937. * - Add settings ('setting'):
  1938. * Adds a setting to Drupal's global storage of JavaScript settings. Per-page
  1939. * settings are required by some modules to function properly. The settings
  1940. * will be accessible at Drupal.settings.
  1941. *
  1942. * @param $data
  1943. * (optional) If given, the value depends on the $type parameter:
  1944. * - 'core', 'module' or 'theme': Path to the file relative to base_path().
  1945. * - 'inline': The JavaScript code that should be placed in the given scope.
  1946. * - 'setting': An array with configuration options as associative array. The
  1947. * array is directly placed in Drupal.settings. You might want to wrap your
  1948. * actual configuration settings in another variable to prevent the pollution
  1949. * of the Drupal.settings namespace.
  1950. * @param $type
  1951. * (optional) The type of JavaScript that should be added to the page. Allowed
  1952. * values are 'core', 'module', 'theme', 'inline' and 'setting'. You
  1953. * can, however, specify any value. It is treated as a reference to a JavaScript
  1954. * file. Defaults to 'module'.
  1955. * @param $scope
  1956. * (optional) The location in which you want to place the script. Possible
  1957. * values are 'header' and 'footer' by default. If your theme implements
  1958. * different locations, however, you can also use these.
  1959. * @param $defer
  1960. * (optional) If set to TRUE, the defer attribute is set on the <script> tag.
  1961. * Defaults to FALSE. This parameter is not used with $type == 'setting'.
  1962. * @param $cache
  1963. * (optional) If set to FALSE, the JavaScript file is loaded anew on every page
  1964. * call, that means, it is not cached. Defaults to TRUE. Used only when $type
  1965. * references a JavaScript file.
  1966. * @param $preprocess
  1967. * (optional) Should this JS file be aggregated if this
  1968. * feature has been turned on under the performance section?
  1969. * @return
  1970. * If the first parameter is NULL, the JavaScript array that has been built so
  1971. * far for $scope is returned. If the first three parameters are NULL,
  1972. * an array with all scopes is returned.
  1973. */
  1974. function drupal_add_js($data = NULL, $type = 'module', $scope = 'header', $defer = FALSE, $cache = TRUE, $preprocess = TRUE) {
  1975. static $javascript = array();
  1976. if (isset($data)) {
  1977. // Add jquery.js and drupal.js, as well as the basePath setting, the
  1978. // first time a Javascript file is added.
  1979. if (empty($javascript)) {
  1980. $javascript['header'] = array(
  1981. 'core' => array(
  1982. 'misc/jquery.js' => array('cache' => TRUE, 'defer' => FALSE, 'preprocess' => TRUE),
  1983. 'misc/drupal.js' => array('cache' => TRUE, 'defer' => FALSE, 'preprocess' => TRUE),
  1984. ),
  1985. 'module' => array(),
  1986. 'theme' => array(),
  1987. 'setting' => array(
  1988. array('basePath' => base_path()),
  1989. ),
  1990. 'inline' => array(),
  1991. );
  1992. }
  1993. if (isset($scope) && !isset($javascript[$scope])) {
  1994. $javascript[$scope] = array('core' => array(), 'module' => array(), 'theme' => array(), 'setting' => array(), 'inline' => array());
  1995. }
  1996. if (isset($type) && isset($scope) && !isset($javascript[$scope][$type])) {
  1997. $javascript[$scope][$type] = array();
  1998. }
  1999. switch ($type) {
  2000. case 'setting':
  2001. $javascript[$scope][$type][] = $data;
  2002. break;
  2003. case 'inline':
  2004. $javascript[$scope][$type][] = array('code' => $data, 'defer' => $defer);
  2005. break;
  2006. default:
  2007. // If cache is FALSE, don't preprocess the JS file.
  2008. $javascript[$scope][$type][$data] = array('cache' => $cache, 'defer' => $defer, 'preprocess' => (!$cache ? FALSE : $preprocess));
  2009. }
  2010. }
  2011. if (isset($scope)) {
  2012. if (isset($javascript[$scope])) {
  2013. return $javascript[$scope];
  2014. }
  2015. else {
  2016. return array();
  2017. }
  2018. }
  2019. else {
  2020. return $javascript;
  2021. }
  2022. }
  2023. /**
  2024. * Returns a themed presentation of all JavaScript code for the current page.
  2025. *
  2026. * References to JavaScript files are placed in a certain order: first, all
  2027. * 'core' files, then all 'module' and finally all 'theme' JavaScript files
  2028. * are added to the page. Then, all settings are output, followed by 'inline'
  2029. * JavaScript code. If running update.php, all preprocessing is disabled.
  2030. *
  2031. * @param $scope
  2032. * (optional) The scope for which the JavaScript rules should be returned.
  2033. * Defaults to 'header'.
  2034. * @param $javascript
  2035. * (optional) An array with all JavaScript code. Defaults to the default
  2036. * JavaScript array for the given scope.
  2037. * @return
  2038. * All JavaScript code segments and includes for the scope as HTML tags.
  2039. */
  2040. function drupal_get_js($scope = 'header', $javascript = NULL) {
  2041. if ((!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') && function_exists('locale_update_js_files')) {
  2042. locale_update_js_files();
  2043. }
  2044. if (!isset($javascript)) {
  2045. $javascript = drupal_add_js(NULL, NULL, $scope);
  2046. }
  2047. if (empty($javascript)) {
  2048. return '';
  2049. }
  2050. $output = '';
  2051. $preprocessed = '';
  2052. $no_preprocess = array('core' => '', 'module' => '', 'theme' => '');
  2053. $files = array();
  2054. $preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
  2055. $directory = file_directory_path();
  2056. $is_writable = is_dir($directory) && is_writable($directory) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC);
  2057. // A dummy query-string is added to filenames, to gain control over
  2058. // browser-caching. The string changes on every update or full cache
  2059. // flush, forcing browsers to load a new copy of the files, as the
  2060. // URL changed. Files that should not be cached (see drupal_add_js())
  2061. // get time() as query-string instead, to enforce reload on every
  2062. // page request.
  2063. $query_string = '?'. substr(variable_get('css_js_query_string', '0'), 0, 1);
  2064. // For inline Javascript to validate as XHTML, all Javascript containing
  2065. // XHTML needs to be wrapped in CDATA. To make that backwards compatible
  2066. // with HTML 4, we need to comment out the CDATA-tag.
  2067. $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
  2068. $embed_suffix = "\n//--><!]]>\n";
  2069. foreach ($javascript as $type => $data) {
  2070. if (!$data) continue;
  2071. switch ($type) {
  2072. case 'setting':
  2073. $output .= '<script type="text/javascript">' . $embed_prefix . 'jQuery.extend(Drupal.settings, ' . drupal_to_js(call_user_func_array('array_merge_recursive', $data)) . ");" . $embed_suffix . "</script>\n";
  2074. break;
  2075. case 'inline':
  2076. foreach ($data as $info) {
  2077. $output .= '<script type="text/javascript"' . ($info['defer'] ? ' defer="defer"' : '') . '>' . $embed_prefix . $info['code'] . $embed_suffix . "</script>\n";
  2078. }
  2079. break;
  2080. default:
  2081. // If JS preprocessing is off, we still need to output the scripts.
  2082. // Additionally, go through any remaining scripts if JS preprocessing is on and output the non-cached ones.
  2083. foreach ($data as $path => $info) {
  2084. if (!$info['preprocess'] || !$is_writable || !$preprocess_js) {
  2085. $no_preprocess[$type] .= '<script type="text/javascript"'. ($info['defer'] ? ' defer="defer"' : '') .' src="'. file_create_url($path) . ($info['cache'] ? $query_string : '?'. time()) ."\"></script>\n";
  2086. }
  2087. else {
  2088. $files[$path] = $info;
  2089. }
  2090. }
  2091. }
  2092. }
  2093. // Aggregate any remaining JS files that haven't already been output.
  2094. if ($is_writable && $preprocess_js && count($files) > 0) {
  2095. // Prefix filename to prevent blocking by firewalls which reject files
  2096. // starting with "ad*".
  2097. $filename = 'js_'. md5(serialize($files) . $query_string) .'.js';
  2098. $preprocess_file = drupal_build_js_cache($files, $filename);
  2099. $preprocessed .= '<script type="text/javascript" src="'. file_create_url($preprocess_file) .'"></script>'."\n";
  2100. }
  2101. // Keep the order of JS files consistent as some are preprocessed and others are not.
  2102. // Make sure any inline or JS setting variables appear last after libraries have loaded.
  2103. $output = $preprocessed . implode('', $no_preprocess) . $output;
  2104. return $output;
  2105. }
  2106. /**
  2107. * Assist in adding the tableDrag JavaScript behavior to a themed table.
  2108. *
  2109. * Draggable tables should be used wherever an outline or list of sortable items
  2110. * needs to be arranged by an end-user. Draggable tables are very flexible and
  2111. * can manipulate the value of form elements placed within individual columns.
  2112. *
  2113. * To set up a table to use drag and drop in place of weight select-lists or
  2114. * in place of a form that contains parent relationships, the form must be
  2115. * themed into a table. The table must have an id attribute set. If using
  2116. * theme_table(), the id may be set as such:
  2117. * @code
  2118. * $output = theme('table', $header, $rows, array('id' => 'my-module-table'));
  2119. * return $output;
  2120. * @endcode
  2121. *
  2122. * In the theme function for the form, a special class must be added to each
  2123. * form element within the same column, "grouping" them together.
  2124. *
  2125. * In a situation where a single weight column is being sorted in the table, the
  2126. * classes could be added like this (in the theme function):
  2127. * @code
  2128. * $form['my_elements'][$delta]['weight']['#attributes']['class'] = "my-elements-weight";
  2129. * @endcode
  2130. *
  2131. * Each row of the table must also have a class of "draggable" in order to enable the
  2132. * drag handles:
  2133. * @code
  2134. * $row = array(...);
  2135. * $rows[] = array(
  2136. * 'data' => $row,
  2137. * 'class' => 'draggable',
  2138. * );
  2139. * @endcode
  2140. *
  2141. * When tree relationships are present, the two additional classes
  2142. * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
  2143. * - Rows with the 'tabledrag-leaf' class cannot have child rows.
  2144. * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
  2145. *
  2146. * Calling drupal_add_tabledrag() would then be written as such:
  2147. * @code
  2148. * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
  2149. * @endcode
  2150. *
  2151. * In a more complex case where there are several groups in one column (such as
  2152. * the block regions on the admin/build/block page), a separate subgroup class
  2153. * must also be added to differentiate the groups.
  2154. * @code
  2155. * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = "my-elements-weight my-elements-weight-". $region;
  2156. * @endcode
  2157. *
  2158. * $group is still 'my-element-weight', and the additional $subgroup variable
  2159. * will be passed in as 'my-elements-weight-'. $region. This also means that
  2160. * you'll need to call drupal_add_tabledrag() once for every region added.
  2161. *
  2162. * @code
  2163. * foreach ($regions as $region) {
  2164. * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight', 'my-elements-weight-'. $region);
  2165. * }
  2166. * @endcode
  2167. *
  2168. * In a situation where tree relationships are present, adding multiple
  2169. * subgroups is not necessary, because the table will contain indentations that
  2170. * provide enough information about the sibling and parent relationships.
  2171. * See theme_menu_overview_form() for an example creating a table containing
  2172. * parent relationships.
  2173. *
  2174. * Please note that this function should be called from the theme layer, such as
  2175. * in a .tpl.php file, theme_ function, or in a template_preprocess function,
  2176. * not in a form declartion. Though the same JavaScript could be added to the
  2177. * page using drupal_add_js() directly, this function helps keep template files
  2178. * clean and readable. It also prevents tabledrag.js from being added twice
  2179. * accidentally.
  2180. *
  2181. * @param $table_id
  2182. * String containing the target table's id attribute. If the table does not
  2183. * have an id, one will need to be set, such as <table id="my-module-table">.
  2184. * @param $action
  2185. * String describing the action to be done on the form item. Either 'match'
  2186. * 'depth', or 'order'. Match is typically used for parent relationships.
  2187. * Order is typically used to set weights on other form elements with the same
  2188. * group. Depth updates the target element with the current indentation.
  2189. * @param $relationship
  2190. * String describing where the $action variable should be performed. Either
  2191. * 'parent', 'sibling', 'group', or 'self'. Parent will only look for fields
  2192. * up the tree. Sibling will look for fields in the same group in rows above
  2193. * and below it. Self affects the dragged row itself. Group affects the
  2194. * dragged row, plus any children below it (the entire dragged group).
  2195. * @param $group
  2196. * A class name applied on all related form elements for this action.
  2197. * @param $subgroup
  2198. * (optional) If the group has several subgroups within it, this string should
  2199. * contain the class name identifying fields in the same subgroup.
  2200. * @param $source
  2201. * (optional) If the $action is 'match', this string should contain the class
  2202. * name identifying what field will be used as the source value when matching
  2203. * the value in $subgroup.
  2204. * @param $hidden
  2205. * (optional) The column containing the field elements may be entirely hidden
  2206. * from view dynamically when the JavaScript is loaded. Set to FALSE if the
  2207. * column should not be hidden.
  2208. * @param $limit
  2209. * (optional) Limit the maximum amount of parenting in this table.
  2210. * @see block-admin-display-form.tpl.php
  2211. * @see theme_menu_overview_form()
  2212. */
  2213. function drupal_add_tabledrag($table_id, $action, $relationship, $group, $subgroup = NULL, $source = NULL, $hidden = TRUE, $limit = 0) {
  2214. static $js_added = FALSE;
  2215. if (!$js_added) {
  2216. drupal_add_js('misc/tabledrag.js', 'core');
  2217. $js_added = TRUE;
  2218. }
  2219. // If a subgroup or source isn't set, assume it is the same as the group.
  2220. $target = isset($subgroup) ? $subgroup : $group;
  2221. $source = isset($source) ? $source : $target;
  2222. $settings['tableDrag'][$table_id][$group][] = array(
  2223. 'target' => $target,
  2224. 'source' => $source,
  2225. 'relationship' => $relationship,
  2226. 'action' => $action,
  2227. 'hidden' => $hidden,
  2228. 'limit' => $limit,
  2229. );
  2230. drupal_add_js($settings, 'setting');
  2231. }
  2232. /**
  2233. * Aggregate JS files, putting them in the files directory.
  2234. *
  2235. * @param $files
  2236. * An array of JS files to aggregate and compress into one file.
  2237. * @param $filename
  2238. * The name of the aggregate JS file.
  2239. * @return
  2240. * The name of the JS file.
  2241. */
  2242. function drupal_build_js_cache($files, $filename) {
  2243. $contents = '';
  2244. // Create the js/ within the files folder.
  2245. $jspath = file_create_path('js');
  2246. file_check_directory($jspath, FILE_CREATE_DIRECTORY);
  2247. if (!file_exists($jspath .'/'. $filename)) {
  2248. // Build aggregate JS file.
  2249. foreach ($files as $path => $info) {
  2250. if ($info['preprocess']) {
  2251. // Append a ';' and a newline after each JS file to prevent them from running together.
  2252. $contents .= file_get_contents($path) .";\n";
  2253. }
  2254. }
  2255. // Create the JS file.
  2256. file_save_data($contents, $jspath .'/'. $filename, FILE_EXISTS_REPLACE);
  2257. }
  2258. return $jspath .'/'. $filename;
  2259. }
  2260. /**
  2261. * Delete all cached JS files.
  2262. */
  2263. function drupal_clear_js_cache() {
  2264. file_scan_directory(file_create_path('js'), '.*', array('.', '..', 'CVS'), 'file_delete', TRUE);
  2265. variable_set('javascript_parsed', array());
  2266. }
  2267. /**
  2268. * Converts a PHP variable into its Javascript equivalent.
  2269. *
  2270. * We use HTML-safe strings, i.e. with <, > and & escaped.
  2271. */
  2272. function drupal_to_js($var) {
  2273. // json_encode() does not escape <, > and &, so we do it with str_replace()
  2274. return str_replace(array("<", ">", "&"), array('\u003c', '\u003e', '\u0026'), json_encode($var));
  2275. }
  2276. /**
  2277. * Return data in JSON format.
  2278. *
  2279. * This function should be used for JavaScript callback functions returning
  2280. * data in JSON format. It sets the header for JavaScript output.
  2281. *
  2282. * @param $var
  2283. * (optional) If set, the variable will be converted to JSON and output.
  2284. */
  2285. function drupal_json($var = NULL) {
  2286. // We are returning JavaScript, so tell the browser.
  2287. drupal_set_header('Content-Type: text/javascript; charset=utf-8');
  2288. if (isset($var)) {
  2289. echo drupal_to_js($var);
  2290. }
  2291. }
  2292. /**
  2293. * Wrapper around urlencode() which avoids Apache quirks.
  2294. *
  2295. * Should be used when placing arbitrary data in an URL. Note that Drupal paths
  2296. * are urlencoded() when passed through url() and do not require urlencoding()
  2297. * of individual components.
  2298. *
  2299. * Notes:
  2300. * - For esthetic reasons, we do not escape slashes. This also avoids a 'feature'
  2301. * in Apache where it 404s on any path containing '%2F'.
  2302. * - mod_rewrite unescapes %-encoded ampersands, hashes, and slashes when clean
  2303. * URLs are used, which are interpreted as delimiters by PHP. These
  2304. * characters are double escaped so PHP will still see the encoded version.
  2305. * - With clean URLs, Apache changes '//' to '/', so every second slash is
  2306. * double escaped.
  2307. * - This function should only be used on paths, not on query string arguments,
  2308. * otherwise unwanted double encoding will occur.
  2309. *
  2310. * @param $text
  2311. * String to encode
  2312. */
  2313. function drupal_urlencode($text) {
  2314. if (variable_get('clean_url', '0')) {
  2315. return str_replace(array('%2F', '%26', '%23', '//'),
  2316. array('/', '%2526', '%2523', '/%252F'),
  2317. rawurlencode($text));
  2318. }
  2319. else {
  2320. return str_replace('%2F', '/', rawurlencode($text));
  2321. }
  2322. }
  2323. /**
  2324. * Ensure the private key variable used to generate tokens is set.
  2325. *
  2326. * @return
  2327. * The private key.
  2328. */
  2329. function drupal_get_private_key() {
  2330. if (!($key = variable_get('drupal_private_key', 0))) {
  2331. $key = md5(uniqid(mt_rand(), true)) . md5(uniqid(mt_rand(), true));
  2332. variable_set('drupal_private_key', $key);
  2333. }
  2334. return $key;
  2335. }
  2336. /**
  2337. * Generate a token based on $value, the current user session and private key.
  2338. *
  2339. * @param $value
  2340. * An additional value to base the token on.
  2341. */
  2342. function drupal_get_token($value = '') {
  2343. $private_key = drupal_get_private_key();
  2344. return md5(session_id() . $value . $private_key);
  2345. }
  2346. /**
  2347. * Validate a token based on $value, the current user session and private key.
  2348. *
  2349. * @param $token
  2350. * The token to be validated.
  2351. * @param $value
  2352. * An additional value to base the token on.
  2353. * @param $skip_anonymous
  2354. * Set to true to skip token validation for anonymous users.
  2355. * @return
  2356. * True for a valid token, false for an invalid token. When $skip_anonymous
  2357. * is true, the return value will always be true for anonymous users.
  2358. */
  2359. function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
  2360. global $user;
  2361. return (($skip_anonymous && $user->uid == 0) || ($token == md5(session_id() . $value . variable_get('drupal_private_key', ''))));
  2362. }
  2363. /**
  2364. * Performs one or more XML-RPC request(s).
  2365. *
  2366. * @param $url
  2367. * An absolute URL of the XML-RPC endpoint.
  2368. * Example:
  2369. * http://www.example.com/xmlrpc.php
  2370. * @param ...
  2371. * For one request:
  2372. * The method name followed by a variable number of arguments to the method.
  2373. * For multiple requests (system.multicall):
  2374. * An array of call arrays. Each call array follows the pattern of the single
  2375. * request: method name followed by the arguments to the method.
  2376. * @return
  2377. * For one request:
  2378. * Either the return value of the method on success, or FALSE.
  2379. * If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
  2380. * For multiple requests:
  2381. * An array of results. Each result will either be the result
  2382. * returned by the method called, or an xmlrpc_error object if the call
  2383. * failed. See xmlrpc_error().
  2384. */
  2385. function xmlrpc($url) {
  2386. require_once './includes/xmlrpc.inc';
  2387. $args = func_get_args();
  2388. return call_user_func_array('_xmlrpc', $args);
  2389. }
  2390. function _drupal_bootstrap_full() {
  2391. static $called;
  2392. if ($called) {
  2393. return;
  2394. }
  2395. $called = 1;
  2396. require_once './includes/theme.inc';
  2397. require_once './includes/pager.inc';
  2398. require_once './includes/menu.inc';
  2399. require_once './includes/tablesort.inc';
  2400. require_once './includes/file.inc';
  2401. require_once './includes/unicode.inc';
  2402. require_once './includes/image.inc';
  2403. require_once './includes/form.inc';
  2404. require_once './includes/mail.inc';
  2405. require_once './includes/actions.inc';
  2406. // Set the Drupal custom error handler.
  2407. set_error_handler('_drupal_error_handler');
  2408. set_exception_handler('_drupal_exception_handler');
  2409. // Emit the correct charset HTTP header.
  2410. drupal_set_header('Content-Type: text/html; charset=utf-8');
  2411. // Detect string handling method
  2412. unicode_check();
  2413. // Undo magic quotes
  2414. fix_gpc_magic();
  2415. if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'simpletest') !== FALSE) {
  2416. // Valid SimpleTest user-agent, log fatal errors to test specific file
  2417. // directory. The user-agent is validated in DRUPAL_BOOTSTRAP_DATABASE
  2418. // phase so as long as it is a SimpleTest user-agent it is valid.
  2419. ini_set('log_errors', 1);
  2420. ini_set('error_log', file_directory_path() . '/error.log');
  2421. }
  2422. // Load all enabled modules
  2423. module_load_all();
  2424. // Let all modules take action before menu system handles the request
  2425. // We do not want this while running update.php.
  2426. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
  2427. module_invoke_all('init');
  2428. }
  2429. }
  2430. /**
  2431. * Store the current page in the cache.
  2432. *
  2433. * If page_compression is enabled, a gzipped version of the page is stored in
  2434. * the cache to avoid compressing the output on each request. The cache entry
  2435. * is unzipped in the relatively rare event that the page is requested by a
  2436. * client without gzip support.
  2437. *
  2438. * Page compression requires the PHP zlib extension
  2439. * (http://php.net/manual/en/ref.zlib.php).
  2440. *
  2441. * @see drupal_page_header
  2442. */
  2443. function page_set_cache() {
  2444. global $base_root;
  2445. if (drupal_page_is_cacheable()) {
  2446. // This will fail in some cases, see page_get_cache() for the explanation.
  2447. if ($data = ob_get_contents()) {
  2448. ob_end_clean();
  2449. $cache_lifetime = variable_get('page_cache_lifetime', 0);
  2450. if (variable_get('page_compression', TRUE) && extension_loaded('zlib')) {
  2451. $data = gzencode($data, 9, FORCE_GZIP);
  2452. }
  2453. $cache = (object) array(
  2454. 'cid' => $base_root . request_uri(),
  2455. 'data' => $data,
  2456. 'expire' => $cache_lifetime > 0 ? $cache_lifetime : CACHE_TEMPORARY,
  2457. 'created' => $_SERVER['REQUEST_TIME'],
  2458. 'headers' => array(),
  2459. );
  2460. // Restore preferred header names based on the lower-case names returned
  2461. // by drupal_get_header().
  2462. $header_names = _drupal_set_preferred_header_name();
  2463. foreach (drupal_get_header() as $name_lower => $value) {
  2464. $cache->headers[$header_names[$name_lower]] = $value;
  2465. }
  2466. cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire, serialize($cache->headers));
  2467. drupal_page_cache_header($cache);
  2468. }
  2469. }
  2470. }
  2471. /**
  2472. * Executes a cron run when called
  2473. * @return
  2474. * Returns TRUE if ran successfully
  2475. */
  2476. function drupal_cron_run() {
  2477. // Try to allocate enough time to run all the hook_cron implementations.
  2478. if (function_exists('set_time_limit')) {
  2479. @set_time_limit(240);
  2480. }
  2481. // Fetch the cron semaphore
  2482. $semaphore = variable_get('cron_semaphore', FALSE);
  2483. if ($semaphore) {
  2484. if (time() - $semaphore > 3600) {
  2485. // Either cron has been running for more than an hour or the semaphore
  2486. // was not reset due to a database error.
  2487. watchdog('cron', 'Cron has been running for more than an hour and is most likely stuck.', array(), WATCHDOG_ERROR);
  2488. // Release cron semaphore
  2489. variable_del('cron_semaphore');
  2490. }
  2491. else {
  2492. // Cron is still running normally.
  2493. watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
  2494. }
  2495. }
  2496. else {
  2497. // Register shutdown callback
  2498. register_shutdown_function('drupal_cron_cleanup');
  2499. // Lock cron semaphore
  2500. variable_set('cron_semaphore', time());
  2501. // Iterate through the modules calling their cron handlers (if any):
  2502. module_invoke_all('cron');
  2503. // Record cron time
  2504. variable_set('cron_last', time());
  2505. watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
  2506. // Release cron semaphore
  2507. variable_del('cron_semaphore');
  2508. // Return TRUE so other functions can check if it did run successfully
  2509. return TRUE;
  2510. }
  2511. }
  2512. /**
  2513. * Shutdown function for cron cleanup.
  2514. */
  2515. function drupal_cron_cleanup() {
  2516. // See if the semaphore is still locked.
  2517. if (variable_get('cron_semaphore', FALSE)) {
  2518. watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);
  2519. // Release cron semaphore
  2520. variable_del('cron_semaphore');
  2521. }
  2522. }
  2523. /**
  2524. * Return an array of system file objects.
  2525. *
  2526. * Returns an array of file objects of the given type from the site-wide
  2527. * directory (i.e. modules/), the all-sites directory (i.e.
  2528. * sites/all/modules/), the profiles directory, and site-specific directory
  2529. * (i.e. sites/somesite/modules/). The returned array will be keyed using the
  2530. * key specified (name, basename, filename). Using name or basename will cause
  2531. * site-specific files to be prioritized over similar files in the default
  2532. * directories. That is, if a file with the same name appears in both the
  2533. * site-wide directory and site-specific directory, only the site-specific
  2534. * version will be included.
  2535. *
  2536. * @param $mask
  2537. * The regular expression of the files to find.
  2538. * @param $directory
  2539. * The subdirectory name in which the files are found. For example,
  2540. * 'modules' will search in both modules/ and
  2541. * sites/somesite/modules/.
  2542. * @param $key
  2543. * The key to be passed to file_scan_directory().
  2544. * @param $min_depth
  2545. * Minimum depth of directories to return files from.
  2546. *
  2547. * @return
  2548. * An array of file objects of the specified type.
  2549. */
  2550. function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
  2551. global $profile;
  2552. $config = conf_path();
  2553. // When this function is called during Drupal's initial installation process,
  2554. // the name of the profile that's about to be installed is stored in the global
  2555. // $profile variable. At all other times, the standard Drupal systems variable
  2556. // table contains the name of the current profile, and we can call variable_get()
  2557. // to determine what one is active.
  2558. if (!isset($profile)) {
  2559. $profile = variable_get('install_profile', 'default');
  2560. }
  2561. $searchdir = array($directory);
  2562. $files = array();
  2563. // The 'profiles' directory contains pristine collections of modules and
  2564. // themes as organized by a distribution. It is pristine in the same way
  2565. // that /modules is pristine for core; users should avoid changing anything
  2566. // there in favor of sites/all or sites/<domain> directories.
  2567. if (file_exists("profiles/$profile/$directory")) {
  2568. $searchdir[] = "profiles/$profile/$directory";
  2569. }
  2570. // Always search sites/all/* as well as the global directories
  2571. $searchdir[] = 'sites/all/'. $directory;
  2572. if (file_exists("$config/$directory")) {
  2573. $searchdir[] = "$config/$directory";
  2574. }
  2575. // Get current list of items
  2576. foreach ($searchdir as $dir) {
  2577. $files = array_merge($files, file_scan_directory($dir, $mask, array('.', '..', 'CVS'), 0, TRUE, $key, $min_depth));
  2578. }
  2579. return $files;
  2580. }
  2581. /**
  2582. * Hands off alterable variables to type-specific *_alter implementations.
  2583. *
  2584. * This dispatch function hands off the passed in variables to type-specific
  2585. * hook_TYPE_alter() implementations in modules. It ensures a consistent
  2586. * interface for all altering operations.
  2587. *
  2588. * @param $type
  2589. * A string describing the type of the alterable $data (e.g. 'form',
  2590. * 'profile').
  2591. * @param $data
  2592. * The variable that will be passed to hook_TYPE_alter() implementations to
  2593. * be altered. The type of this variable depends on $type. For example, when
  2594. * altering a 'form', $data will be a structured array. When altering a
  2595. * 'profile', $data will be an object. If you need to pass additional
  2596. * parameters by reference to the hook_TYPE_alter() functions, include them
  2597. * as an array in $data['__drupal_alter_by_ref']. They will be unpacked and
  2598. * passed to the hook_TYPE_alter() functions, before the additional
  2599. * ... parameters (see below).
  2600. * @param ...
  2601. * Any additional parameters will be passed on to the hook_TYPE_alter()
  2602. * functions (not by reference), after any by-reference parameters included
  2603. * in $data (see above)
  2604. */
  2605. function drupal_alter($type, &$data) {
  2606. // PHP's func_get_args() always returns copies of params, not references, so
  2607. // drupal_alter() can only manipulate data that comes in via the required first
  2608. // param. For the edge case functions that must pass in an arbitrary number of
  2609. // alterable parameters (hook_form_alter() being the best example), an array of
  2610. // those params can be placed in the __drupal_alter_by_ref key of the $data
  2611. // array. This is somewhat ugly, but is an unavoidable consequence of a flexible
  2612. // drupal_alter() function, and the limitations of func_get_args().
  2613. // @todo: Remove this in Drupal 7.
  2614. if (is_array($data) && isset($data['__drupal_alter_by_ref'])) {
  2615. $by_ref_parameters = $data['__drupal_alter_by_ref'];
  2616. unset($data['__drupal_alter_by_ref']);
  2617. }
  2618. // Hang onto a reference to the data array so that it isn't blown away later.
  2619. // Also, merge in any parameters that need to be passed by reference.
  2620. $args = array(&$data);
  2621. if (isset($by_ref_parameters)) {
  2622. $args = array_merge($args, $by_ref_parameters);
  2623. }
  2624. // Now, use func_get_args() to pull in any additional parameters passed into
  2625. // the drupal_alter() call.
  2626. $additional_args = func_get_args();
  2627. array_shift($additional_args);
  2628. array_shift($additional_args);
  2629. $args = array_merge($args, $additional_args);
  2630. foreach (module_implements($type .'_alter') as $module) {
  2631. $function = $module .'_'. $type .'_alter';
  2632. call_user_func_array($function, $args);
  2633. }
  2634. }
  2635. /**
  2636. * Renders HTML given a structured array tree.
  2637. *
  2638. * Recursively iterates over each of the array elements, generating HTML code.
  2639. * This function is usually called from within another function, like
  2640. * drupal_get_form() or node_view().
  2641. *
  2642. * drupal_render() flags each element with a '#printed' status to indicate that
  2643. * the element has been rendered, which allows individual elements of a given
  2644. * array to be rendered independently. This prevents elements from being
  2645. * rendered more than once on subsequent calls to drupal_render() if, for example,
  2646. * they are part of a larger array. If the same array or array element is passed
  2647. * more than once to drupal_render(), it simply returns a NULL value.
  2648. *
  2649. * @param $elements
  2650. * The structured array describing the data to be rendered.
  2651. * @return
  2652. * The rendered HTML.
  2653. */
  2654. function drupal_render(&$elements) {
  2655. if (!isset($elements) || (isset($elements['#access']) && !$elements['#access'])) {
  2656. return NULL;
  2657. }
  2658. // If the default values for this element haven't been loaded yet, populate
  2659. // them.
  2660. if (!isset($elements['#defaults_loaded']) || !$elements['#defaults_loaded']) {
  2661. if ((!empty($elements['#type'])) && ($info = _element_info($elements['#type']))) {
  2662. $elements += $info;
  2663. }
  2664. }
  2665. // Make any final changes to the element before it is rendered. This means
  2666. // that the $element or the children can be altered or corrected before the
  2667. // element is rendered into the final text.
  2668. if (isset($elements['#pre_render'])) {
  2669. foreach ($elements['#pre_render'] as $function) {
  2670. if (function_exists($function)) {
  2671. $elements = $function($elements);
  2672. }
  2673. }
  2674. }
  2675. $content = '';
  2676. // Either the elements did not go through form_builder or one of the children
  2677. // has a #weight.
  2678. if (!isset($elements['#sorted'])) {
  2679. uasort($elements, "element_sort");
  2680. }
  2681. $elements += array('#title' => NULL, '#description' => NULL);
  2682. if (!isset($elements['#children'])) {
  2683. $children = element_children($elements);
  2684. // Render all the children that use a theme function.
  2685. if (isset($elements['#theme']) && empty($elements['#theme_used'])) {
  2686. $elements['#theme_used'] = TRUE;
  2687. $previous = array();
  2688. foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
  2689. $previous[$key] = isset($elements[$key]) ? $elements[$key] : NULL;
  2690. }
  2691. // If we rendered a single element, then we will skip the renderer.
  2692. if (empty($children)) {
  2693. $elements['#printed'] = TRUE;
  2694. }
  2695. else {
  2696. $elements['#value'] = '';
  2697. }
  2698. $elements['#type'] = 'markup';
  2699. unset($elements['#prefix'], $elements['#suffix']);
  2700. $content = theme($elements['#theme'], $elements);
  2701. foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
  2702. $elements[$key] = isset($previous[$key]) ? $previous[$key] : NULL;
  2703. }
  2704. }
  2705. // Render each of the children using drupal_render and concatenate them.
  2706. if (!isset($content) || $content === '') {
  2707. foreach ($children as $key) {
  2708. $content .= drupal_render($elements[$key]);
  2709. }
  2710. }
  2711. }
  2712. if (isset($content) && $content !== '') {
  2713. $elements['#children'] = $content;
  2714. }
  2715. // Until now, we rendered the children, here we render the element itself
  2716. if (!isset($elements['#printed'])) {
  2717. $content = theme(!empty($elements['#type']) ? $elements['#type'] : 'markup', $elements);
  2718. $elements['#printed'] = TRUE;
  2719. }
  2720. if (isset($content) && $content !== '') {
  2721. // Filter the outputted content and make any last changes before the
  2722. // content is sent to the browser. The changes are made on $content
  2723. // which allows the output'ed text to be filtered.
  2724. if (isset($elements['#post_render'])) {
  2725. foreach ($elements['#post_render'] as $function) {
  2726. if (function_exists($function)) {
  2727. $content = $function($content, $elements);
  2728. }
  2729. }
  2730. }
  2731. $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
  2732. $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
  2733. return $prefix . $content . $suffix;
  2734. }
  2735. }
  2736. /**
  2737. * Function used by uasort to sort structured arrays by weight.
  2738. */
  2739. function element_sort($a, $b) {
  2740. $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
  2741. $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
  2742. if ($a_weight == $b_weight) {
  2743. return 0;
  2744. }
  2745. return ($a_weight < $b_weight) ? -1 : 1;
  2746. }
  2747. /**
  2748. * Check if the key is a property.
  2749. */
  2750. function element_property($key) {
  2751. return $key[0] == '#';
  2752. }
  2753. /**
  2754. * Get properties of a structured array element. Properties begin with '#'.
  2755. */
  2756. function element_properties($element) {
  2757. return array_filter(array_keys((array) $element), 'element_property');
  2758. }
  2759. /**
  2760. * Check if the key is a child.
  2761. */
  2762. function element_child($key) {
  2763. return !isset($key[0]) || $key[0] != '#';
  2764. }
  2765. /**
  2766. * Get keys of a structured array tree element that are not properties (i.e., do not begin with '#').
  2767. */
  2768. function element_children($element) {
  2769. return array_filter(array_keys((array) $element), 'element_child');
  2770. }
  2771. /**
  2772. * Provide theme registration for themes across .inc files.
  2773. */
  2774. function drupal_common_theme() {
  2775. return array(
  2776. // theme.inc
  2777. 'placeholder' => array(
  2778. 'arguments' => array('text' => NULL)
  2779. ),
  2780. 'page' => array(
  2781. 'arguments' => array('content' => NULL, 'show_blocks' => TRUE, 'show_messages' => TRUE),
  2782. 'template' => 'page',
  2783. ),
  2784. 'maintenance_page' => array(
  2785. 'arguments' => array('content' => NULL, 'show_blocks' => TRUE, 'show_messages' => TRUE),
  2786. 'template' => 'maintenance-page',
  2787. ),
  2788. 'update_page' => array(
  2789. 'arguments' => array('content' => NULL, 'show_messages' => TRUE),
  2790. ),
  2791. 'install_page' => array(
  2792. 'arguments' => array('content' => NULL),
  2793. ),
  2794. 'task_list' => array(
  2795. 'arguments' => array('items' => NULL, 'active' => NULL),
  2796. ),
  2797. 'status_messages' => array(
  2798. 'arguments' => array('display' => NULL),
  2799. ),
  2800. 'links' => array(
  2801. 'arguments' => array('links' => NULL, 'attributes' => array('class' => 'links')),
  2802. ),
  2803. 'image' => array(
  2804. 'arguments' => array('path' => NULL, 'alt' => '', 'title' => '', 'attributes' => NULL, 'getsize' => TRUE),
  2805. ),
  2806. 'breadcrumb' => array(
  2807. 'arguments' => array('breadcrumb' => NULL),
  2808. ),
  2809. 'help' => array(
  2810. 'arguments' => array(),
  2811. ),
  2812. 'submenu' => array(
  2813. 'arguments' => array('links' => NULL),
  2814. ),
  2815. 'table' => array(
  2816. 'arguments' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL),
  2817. ),
  2818. 'table_select_header_cell' => array(
  2819. 'arguments' => array(),
  2820. ),
  2821. 'tablesort_indicator' => array(
  2822. 'arguments' => array('style' => NULL),
  2823. ),
  2824. 'box' => array(
  2825. 'arguments' => array('title' => NULL, 'content' => NULL, 'region' => 'main'),
  2826. 'template' => 'box',
  2827. ),
  2828. 'block' => array(
  2829. 'arguments' => array('block' => NULL),
  2830. 'template' => 'block',
  2831. ),
  2832. 'mark' => array(
  2833. 'arguments' => array('type' => MARK_NEW),
  2834. ),
  2835. 'item_list' => array(
  2836. 'arguments' => array('items' => array(), 'title' => NULL, 'type' => 'ul', 'attributes' => NULL),
  2837. ),
  2838. 'more_help_link' => array(
  2839. 'arguments' => array('url' => NULL),
  2840. ),
  2841. 'xml_icon' => array(
  2842. 'arguments' => array('url' => NULL),
  2843. ),
  2844. 'feed_icon' => array(
  2845. 'arguments' => array('url' => NULL, 'title' => NULL),
  2846. ),
  2847. 'more_link' => array(
  2848. 'arguments' => array('url' => NULL, 'title' => NULL)
  2849. ),
  2850. 'closure' => array(
  2851. 'arguments' => array('main' => 0),
  2852. ),
  2853. 'blocks' => array(
  2854. 'arguments' => array('region' => NULL),
  2855. ),
  2856. 'username' => array(
  2857. 'arguments' => array('object' => NULL),
  2858. ),
  2859. 'progress_bar' => array(
  2860. 'arguments' => array('percent' => NULL, 'message' => NULL),
  2861. ),
  2862. 'indentation' => array(
  2863. 'arguments' => array('size' => 1),
  2864. ),
  2865. // from pager.inc
  2866. 'pager' => array(
  2867. 'arguments' => array('tags' => array(), 'limit' => 10, 'element' => 0, 'parameters' => array()),
  2868. ),
  2869. 'pager_first' => array(
  2870. 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'parameters' => array()),
  2871. ),
  2872. 'pager_previous' => array(
  2873. 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
  2874. ),
  2875. 'pager_next' => array(
  2876. 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
  2877. ),
  2878. 'pager_last' => array(
  2879. 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'parameters' => array()),
  2880. ),
  2881. 'pager_link' => array(
  2882. 'arguments' => array('text' => NULL, 'page_new' => NULL, 'element' => NULL, 'parameters' => array(), 'attributes' => array()),
  2883. ),
  2884. // from menu.inc
  2885. 'menu_item_link' => array(
  2886. 'arguments' => array('item' => NULL),
  2887. ),
  2888. 'menu_tree' => array(
  2889. 'arguments' => array('tree' => NULL),
  2890. ),
  2891. 'menu_item' => array(
  2892. 'arguments' => array('link' => NULL, 'has_children' => NULL, 'menu' => ''),
  2893. ),
  2894. 'menu_local_task' => array(
  2895. 'arguments' => array('link' => NULL, 'active' => FALSE),
  2896. ),
  2897. 'menu_local_tasks' => array(
  2898. 'arguments' => array(),
  2899. ),
  2900. // from form.inc
  2901. 'select' => array(
  2902. 'arguments' => array('element' => NULL),
  2903. ),
  2904. 'fieldset' => array(
  2905. 'arguments' => array('element' => NULL),
  2906. ),
  2907. 'radio' => array(
  2908. 'arguments' => array('element' => NULL),
  2909. ),
  2910. 'radios' => array(
  2911. 'arguments' => array('element' => NULL),
  2912. ),
  2913. 'password_confirm' => array(
  2914. 'arguments' => array('element' => NULL),
  2915. ),
  2916. 'date' => array(
  2917. 'arguments' => array('element' => NULL),
  2918. ),
  2919. 'item' => array(
  2920. 'arguments' => array('element' => NULL),
  2921. ),
  2922. 'checkbox' => array(
  2923. 'arguments' => array('element' => NULL),
  2924. ),
  2925. 'checkboxes' => array(
  2926. 'arguments' => array('element' => NULL),
  2927. ),
  2928. 'submit' => array(
  2929. 'arguments' => array('element' => NULL),
  2930. ),
  2931. 'button' => array(
  2932. 'arguments' => array('element' => NULL),
  2933. ),
  2934. 'image_button' => array(
  2935. 'arguments' => array('element' => NULL),
  2936. ),
  2937. 'hidden' => array(
  2938. 'arguments' => array('element' => NULL),
  2939. ),
  2940. 'token' => array(
  2941. 'arguments' => array('element' => NULL),
  2942. ),
  2943. 'textfield' => array(
  2944. 'arguments' => array('element' => NULL),
  2945. ),
  2946. 'form' => array(
  2947. 'arguments' => array('element' => NULL),
  2948. ),
  2949. 'textarea' => array(
  2950. 'arguments' => array('element' => NULL),
  2951. ),
  2952. 'markup' => array(
  2953. 'arguments' => array('element' => NULL),
  2954. ),
  2955. 'password' => array(
  2956. 'arguments' => array('element' => NULL),
  2957. ),
  2958. 'file' => array(
  2959. 'arguments' => array('element' => NULL),
  2960. ),
  2961. 'form_element' => array(
  2962. 'arguments' => array('element' => NULL, 'value' => NULL),
  2963. ),
  2964. );
  2965. }
  2966. /**
  2967. * @ingroup schemaapi
  2968. * @{
  2969. */
  2970. /**
  2971. * Get the schema definition of a table, or the whole database schema.
  2972. *
  2973. * The returned schema will include any modifications made by any
  2974. * module that implements hook_schema_alter().
  2975. *
  2976. * @param $table
  2977. * The name of the table. If not given, the schema of all tables is returned.
  2978. * @param $rebuild
  2979. * If true, the schema will be rebuilt instead of retrieved from the cache.
  2980. */
  2981. function drupal_get_schema($table = NULL, $rebuild = FALSE) {
  2982. static $schema = array();
  2983. if (empty($schema) || $rebuild) {
  2984. // Try to load the schema from cache.
  2985. if (!$rebuild && $cached = cache_get('schema')) {
  2986. $schema = $cached->data;
  2987. }
  2988. // Otherwise, rebuild the schema cache.
  2989. else {
  2990. $schema = array();
  2991. // Load the .install files to get hook_schema.
  2992. module_load_all_includes('install');
  2993. // Invoke hook_schema for all modules.
  2994. foreach (module_implements('schema') as $module) {
  2995. // Cast the result of hook_schema() to an array, as a NULL return value
  2996. // would cause array_merge() to set the $schema variable to NULL as well.
  2997. // That would break modules which use $schema further down the line.
  2998. $current = (array) module_invoke($module, 'schema');
  2999. _drupal_initialize_schema($module, $current);
  3000. $schema = array_merge($schema, $current);
  3001. }
  3002. drupal_alter('schema', $schema);
  3003. cache_set('schema', $schema);
  3004. }
  3005. }
  3006. if (!isset($table)) {
  3007. return $schema;
  3008. }
  3009. elseif (isset($schema[$table])) {
  3010. return $schema[$table];
  3011. }
  3012. else {
  3013. return FALSE;
  3014. }
  3015. }
  3016. /**
  3017. * Create all tables that a module defines in its hook_schema().
  3018. *
  3019. * Note: This function does not pass the module's schema through
  3020. * hook_schema_alter(). The module's tables will be created exactly as the
  3021. * module defines them.
  3022. *
  3023. * @param $module
  3024. * The module for which the tables will be created.
  3025. * @return
  3026. * An array of arrays with the following key/value pairs:
  3027. * - success: a boolean indicating whether the query succeeded.
  3028. * - query: the SQL query(s) executed, passed through check_plain().
  3029. */
  3030. function drupal_install_schema($module) {
  3031. $schema = drupal_get_schema_unprocessed($module);
  3032. _drupal_initialize_schema($module, $schema);
  3033. $ret = array();
  3034. foreach ($schema as $name => $table) {
  3035. db_create_table($ret, $name, $table);
  3036. }
  3037. return $ret;
  3038. }
  3039. /**
  3040. * Remove all tables that a module defines in its hook_schema().
  3041. *
  3042. * Note: This function does not pass the module's schema through
  3043. * hook_schema_alter(). The module's tables will be created exactly as the
  3044. * module defines them.
  3045. *
  3046. * @param $module
  3047. * The module for which the tables will be removed.
  3048. * @return
  3049. * An array of arrays with the following key/value pairs:
  3050. * - success: a boolean indicating whether the query succeeded.
  3051. * - query: the SQL query(s) executed, passed through check_plain().
  3052. */
  3053. function drupal_uninstall_schema($module) {
  3054. $schema = drupal_get_schema_unprocessed($module);
  3055. _drupal_initialize_schema($module, $schema);
  3056. $ret = array();
  3057. foreach ($schema as $table) {
  3058. db_drop_table($ret, $table['name']);
  3059. }
  3060. return $ret;
  3061. }
  3062. /**
  3063. * Returns the unprocessed and unaltered version of a module's schema.
  3064. *
  3065. * Use this function only if you explicitly need the original
  3066. * specification of a schema, as it was defined in a module's
  3067. * hook_schema(). No additional default values will be set,
  3068. * hook_schema_alter() is not invoked and these unprocessed
  3069. * definitions won't be cached.
  3070. *
  3071. * This function can be used to retrieve a schema specification in
  3072. * hook_schema(), so it allows you to derive your tables from existing
  3073. * specifications.
  3074. *
  3075. * It is also used by drupal_install_schema() and
  3076. * drupal_uninstall_schema() to ensure that a module's tables are
  3077. * created exactly as specified without any changes introduced by a
  3078. * module that implements hook_schema_alter().
  3079. *
  3080. * @param $module
  3081. * The module to which the table belongs.
  3082. * @param $table
  3083. * The name of the table. If not given, the module's complete schema
  3084. * is returned.
  3085. */
  3086. function drupal_get_schema_unprocessed($module, $table = NULL) {
  3087. // Load the .install file to get hook_schema.
  3088. module_load_install($module);
  3089. $schema = module_invoke($module, 'schema');
  3090. if (!is_null($table) && isset($schema[$table])) {
  3091. return $schema[$table];
  3092. }
  3093. elseif (!empty($schema)) {
  3094. return $schema;
  3095. }
  3096. return array();
  3097. }
  3098. /**
  3099. * Fill in required default values for table definitions returned by hook_schema().
  3100. *
  3101. * @param $module
  3102. * The module for which hook_schema() was invoked.
  3103. * @param $schema
  3104. * The schema definition array as it was returned by the module's
  3105. * hook_schema().
  3106. */
  3107. function _drupal_initialize_schema($module, &$schema) {
  3108. // Set the name and module key for all tables.
  3109. foreach ($schema as $name => $table) {
  3110. if (empty($table['module'])) {
  3111. $schema[$name]['module'] = $module;
  3112. }
  3113. if (!isset($table['name'])) {
  3114. $schema[$name]['name'] = $name;
  3115. }
  3116. }
  3117. }
  3118. /**
  3119. * Retrieve a list of fields from a table schema. The list is suitable for use in a SQL query.
  3120. *
  3121. * @param $table
  3122. * The name of the table from which to retrieve fields.
  3123. * @param
  3124. * An optional prefix to to all fields.
  3125. *
  3126. * @return An array of fields.
  3127. **/
  3128. function drupal_schema_fields_sql($table, $prefix = NULL) {
  3129. $schema = drupal_get_schema($table);
  3130. $fields = array_keys($schema['fields']);
  3131. if ($prefix) {
  3132. $columns = array();
  3133. foreach ($fields as $field) {
  3134. $columns[] = "$prefix.$field";
  3135. }
  3136. return $columns;
  3137. }
  3138. else {
  3139. return $fields;
  3140. }
  3141. }
  3142. /**
  3143. * Save a record to the database based upon the schema.
  3144. *
  3145. * Default values are filled in for missing items, and 'serial' (auto increment)
  3146. * types are filled in with IDs.
  3147. *
  3148. * @param $table
  3149. * The name of the table; this must exist in schema API.
  3150. * @param $object
  3151. * The object to write. This is a reference, as defaults according to
  3152. * the schema may be filled in on the object, as well as ID on the serial
  3153. * type(s). Both array an object types may be passed.
  3154. * @param $update
  3155. * If this is an update, specify the primary keys' field names. It is the
  3156. * caller's responsibility to know if a record for this object already
  3157. * exists in the database. If there is only 1 key, you may pass a simple string.
  3158. * @return
  3159. * Failure to write a record will return FALSE. Otherwise SAVED_NEW or
  3160. * SAVED_UPDATED is returned depending on the operation performed. The
  3161. * $object parameter contains values for any serial fields defined by
  3162. * the $table. For example, $object->nid will be populated after inserting
  3163. * a new node.
  3164. */
  3165. function drupal_write_record($table, &$object, $update = array()) {
  3166. // Standardize $update to an array.
  3167. if (is_string($update)) {
  3168. $update = array($update);
  3169. }
  3170. $schema = drupal_get_schema($table);
  3171. if (empty($schema)) {
  3172. return FALSE;
  3173. }
  3174. // Convert to an object if needed.
  3175. if (is_array($object)) {
  3176. $object = (object) $object;
  3177. $array = TRUE;
  3178. }
  3179. else {
  3180. $array = FALSE;
  3181. }
  3182. $fields = $defs = $values = $serials = $placeholders = array();
  3183. // Go through our schema, build SQL, and when inserting, fill in defaults for
  3184. // fields that are not set.
  3185. foreach ($schema['fields'] as $field => $info) {
  3186. // Special case -- skip serial types if we are updating.
  3187. if ($info['type'] == 'serial' && count($update)) {
  3188. continue;
  3189. }
  3190. // For inserts, populate defaults from Schema if not already provided
  3191. if (!isset($object->$field) && !count($update) && isset($info['default'])) {
  3192. $object->$field = $info['default'];
  3193. }
  3194. // Track serial fields so we can helpfully populate them after the query.
  3195. if ($info['type'] == 'serial') {
  3196. $serials[] = $field;
  3197. // Ignore values for serials when inserting data. Unsupported.
  3198. unset($object->$field);
  3199. }
  3200. // Build arrays for the fields, placeholders, and values in our query.
  3201. if (isset($object->$field)) {
  3202. $fields[] = $field;
  3203. $placeholders[] = db_type_placeholder($info['type']);
  3204. if (empty($info['serialize'])) {
  3205. $values[] = $object->$field;
  3206. }
  3207. else {
  3208. $values[] = serialize($object->$field);
  3209. }
  3210. }
  3211. }
  3212. // Build the SQL.
  3213. $query = '';
  3214. if (!count($update)) {
  3215. $query = "INSERT INTO {". $table ."} (". implode(', ', $fields) .') VALUES ('. implode(', ', $placeholders) .')';
  3216. $return = SAVED_NEW;
  3217. }
  3218. else {
  3219. $query = '';
  3220. foreach ($fields as $id => $field) {
  3221. if ($query) {
  3222. $query .= ', ';
  3223. }
  3224. $query .= $field .' = '. $placeholders[$id];
  3225. }
  3226. foreach ($update as $key){
  3227. $conditions[] = "$key = ". db_type_placeholder($schema['fields'][$key]['type']);
  3228. $values[] = $object->$key;
  3229. }
  3230. $query = "UPDATE {". $table ."} SET $query WHERE ". implode(' AND ', $conditions);
  3231. $return = SAVED_UPDATED;
  3232. }
  3233. // Execute the SQL.
  3234. if (db_query($query, $values)) {
  3235. if ($serials) {
  3236. // Get last insert ids and fill them in.
  3237. foreach ($serials as $field) {
  3238. $object->$field = db_last_insert_id($table, $field);
  3239. }
  3240. }
  3241. }
  3242. else {
  3243. $return = FALSE;
  3244. }
  3245. // If we began with an array, convert back so we don't surprise the caller.
  3246. if ($array) {
  3247. $object = (array) $object;
  3248. }
  3249. return $return;
  3250. }
  3251. /**
  3252. * @} End of "ingroup schemaapi".
  3253. */
  3254. /**
  3255. * Parse Drupal info file format.
  3256. *
  3257. * Files should use an ini-like format to specify values.
  3258. * White-space generally doesn't matter, except inside values.
  3259. * e.g.
  3260. *
  3261. * @code
  3262. * key = value
  3263. * key = "value"
  3264. * key = 'value'
  3265. * key = "multi-line
  3266. *
  3267. * value"
  3268. * key = 'multi-line
  3269. *
  3270. * value'
  3271. * key
  3272. * =
  3273. * 'value'
  3274. * @endcode
  3275. *
  3276. * Arrays are created using a GET-like syntax:
  3277. *
  3278. * @code
  3279. * key[] = "numeric array"
  3280. * key[index] = "associative array"
  3281. * key[index][] = "nested numeric array"
  3282. * key[index][index] = "nested associative array"
  3283. * @endcode
  3284. *
  3285. * PHP constants are substituted in, but only when used as the entire value:
  3286. *
  3287. * Comments should start with a semi-colon at the beginning of a line.
  3288. *
  3289. * This function is NOT for placing arbitrary module-specific settings. Use
  3290. * variable_get() and variable_set() for that.
  3291. *
  3292. * Information stored in the module.info file:
  3293. * - name: The real name of the module for display purposes.
  3294. * - description: A brief description of the module.
  3295. * - dependencies: An array of shortnames of other modules this module depends on.
  3296. * - package: The name of the package of modules this module belongs to.
  3297. *
  3298. * Example of .info file:
  3299. * @code
  3300. * name = Forum
  3301. * description = Enables threaded discussions about general topics.
  3302. * dependencies[] = taxonomy
  3303. * dependencies[] = comment
  3304. * package = Core - optional
  3305. * version = VERSION
  3306. * @endcode
  3307. *
  3308. * @param $filename
  3309. * The file we are parsing. Accepts file with relative or absolute path.
  3310. * @return
  3311. * The info array.
  3312. */
  3313. function drupal_parse_info_file($filename) {
  3314. $info = array();
  3315. $constants = get_defined_constants();
  3316. if (!file_exists($filename)) {
  3317. return $info;
  3318. }
  3319. $data = file_get_contents($filename);
  3320. if (preg_match_all('
  3321. @^\s* # Start at the beginning of a line, ignoring leading whitespace
  3322. ((?:
  3323. [^=;\[\]]| # Key names cannot contain equal signs, semi-colons or square brackets,
  3324. \[[^\[\]]*\] # unless they are balanced and not nested
  3325. )+?)
  3326. \s*=\s* # Key/value pairs are separated by equal signs (ignoring white-space)
  3327. (?:
  3328. ("(?:[^"]|(?<=\\\\)")*")| # Double-quoted string, which may contain slash-escaped quotes/slashes
  3329. (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
  3330. ([^\r\n]*?) # Non-quoted string
  3331. )\s*$ # Stop at the next end of a line, ignoring trailing whitespace
  3332. @msx', $data, $matches, PREG_SET_ORDER)) {
  3333. foreach ($matches as $match) {
  3334. // Fetch the key and value string
  3335. $i = 0;
  3336. foreach (array('key', 'value1', 'value2', 'value3') as $var) {
  3337. $$var = isset($match[++$i]) ? $match[$i] : '';
  3338. }
  3339. $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
  3340. // Parse array syntax
  3341. $keys = preg_split('/\]?\[/', rtrim($key, ']'));
  3342. $last = array_pop($keys);
  3343. $parent = &$info;
  3344. // Create nested arrays
  3345. foreach ($keys as $key) {
  3346. if ($key == '') {
  3347. $key = count($parent);
  3348. }
  3349. if (!isset($parent[$key]) || !is_array($parent[$key])) {
  3350. $parent[$key] = array();
  3351. }
  3352. $parent = &$parent[$key];
  3353. }
  3354. // Handle PHP constants.
  3355. if (isset($constants[$value])) {
  3356. $value = $constants[$value];
  3357. }
  3358. // Insert actual value
  3359. if ($last == '') {
  3360. $last = count($parent);
  3361. }
  3362. $parent[$last] = $value;
  3363. }
  3364. }
  3365. return $info;
  3366. }
  3367. /**
  3368. * @return
  3369. * Array of the possible severity levels for log messages.
  3370. *
  3371. * @see watchdog
  3372. */
  3373. function watchdog_severity_levels() {
  3374. return array(
  3375. WATCHDOG_EMERG => t('emergency'),
  3376. WATCHDOG_ALERT => t('alert'),
  3377. WATCHDOG_CRITICAL => t('critical'),
  3378. WATCHDOG_ERROR => t('error'),
  3379. WATCHDOG_WARNING => t('warning'),
  3380. WATCHDOG_NOTICE => t('notice'),
  3381. WATCHDOG_INFO => t('info'),
  3382. WATCHDOG_DEBUG => t('debug'),
  3383. );
  3384. }
  3385. /**
  3386. * Explode a string of given tags into an array.
  3387. *
  3388. * @see drupal_implode_tags()
  3389. */
  3390. function drupal_explode_tags($tags) {
  3391. // This regexp allows the following types of user input:
  3392. // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
  3393. $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
  3394. preg_match_all($regexp, $tags, $matches);
  3395. $typed_tags = array_unique($matches[1]);
  3396. $tags = array();
  3397. foreach ($typed_tags as $tag) {
  3398. // If a user has escaped a term (to demonstrate that it is a group,
  3399. // or includes a comma or quote character), we remove the escape
  3400. // formatting so to save the term into the database as the user intends.
  3401. $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
  3402. if ($tag != "") {
  3403. $tags[] = $tag;
  3404. }
  3405. }
  3406. return $tags;
  3407. }
  3408. /**
  3409. * Implode an array of tags into a string.
  3410. *
  3411. * @see drupal_explode_tags()
  3412. */
  3413. function drupal_implode_tags($tags) {
  3414. $encoded_tags = array();
  3415. foreach ($tags as $tag) {
  3416. // Commas and quotes in tag names are special cases, so encode them.
  3417. if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
  3418. $tag = '"'. str_replace('"', '""', $tag) .'"';
  3419. }
  3420. $encoded_tags[] = $tag;
  3421. }
  3422. return implode(', ', $encoded_tags);
  3423. }
  3424. /**
  3425. * Flush all cached data on the site.
  3426. *
  3427. * Empties cache tables, rebuilds the menu cache and theme registries, and
  3428. * invokes a hook so that other modules' cache data can be cleared as well.
  3429. */
  3430. function drupal_flush_all_caches() {
  3431. // Change query-strings on css/js files to enforce reload for all users.
  3432. _drupal_flush_css_js();
  3433. drupal_clear_css_cache();
  3434. drupal_clear_js_cache();
  3435. // If invoked from update.php, we must not update the theme information in the
  3436. // database, or this will result in all themes being disabled.
  3437. if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
  3438. _system_theme_data();
  3439. }
  3440. else {
  3441. system_theme_data();
  3442. }
  3443. drupal_rebuild_theme_registry();
  3444. menu_rebuild();
  3445. node_types_rebuild();
  3446. // Don't clear cache_form - in-progress form submissions may break.
  3447. // Ordered so clearing the page cache will always be the last action.
  3448. $core = array('cache', 'cache_block', 'cache_filter', 'cache_page');
  3449. $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
  3450. foreach ($cache_tables as $table) {
  3451. cache_clear_all('*', $table, TRUE);
  3452. }
  3453. }
  3454. /**
  3455. * Helper function to change query-strings on css/js files.
  3456. *
  3457. * Changes the character added to all css/js files as dummy query-string,
  3458. * so that all browsers are forced to reload fresh files. We keep
  3459. * 20 characters history (FIFO) to avoid repeats, but only the first
  3460. * (newest) character is actually used on urls, to keep them short.
  3461. * This is also called from update.php.
  3462. */
  3463. function _drupal_flush_css_js() {
  3464. $string_history = variable_get('css_js_query_string', '00000000000000000000');
  3465. $new_character = $string_history[0];
  3466. // Not including 'q' to allow certain JavaScripts to re-use query string.
  3467. $characters = 'abcdefghijklmnoprstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  3468. while (strpos($string_history, $new_character) !== FALSE) {
  3469. $new_character = $characters[mt_rand(0, strlen($characters) - 1)];
  3470. }
  3471. variable_set('css_js_query_string', $new_character . substr($string_history, 0, 19));
  3472. }
  3473. /**
  3474. * Error reporting level: display no errors.
  3475. */
  3476. define('ERROR_REPORTING_HIDE', 0);
  3477. /**
  3478. * Error reporting level: display errors and warnings.
  3479. */
  3480. define('ERROR_REPORTING_DISPLAY_SOME', 1);
  3481. /**
  3482. * Error reporting level: display all messages.
  3483. */
  3484. define('ERROR_REPORTING_DISPLAY_ALL', 2);
  3485. /**
  3486. * Custom PHP error handler.
  3487. *
  3488. * @param $error_level
  3489. * The level of the error raised.
  3490. * @param $message
  3491. * The error message.
  3492. * @param $filename
  3493. * The filename that the error was raised in.
  3494. * @param $line
  3495. * The line number the error was raised at.
  3496. * @param $context
  3497. * An array that points to the active symbol table at the point the error occurred.
  3498. */
  3499. function _drupal_error_handler($error_level, $message, $filename, $line, $context) {
  3500. if ($error_level & error_reporting()) {
  3501. // All these constants are documented at http://php.net/manual/en/errorfunc.constants.php
  3502. $types = array(
  3503. E_ERROR => 'Error',
  3504. E_WARNING => 'Warning',
  3505. E_PARSE => 'Parse error',
  3506. E_NOTICE => 'Notice',
  3507. E_CORE_ERROR => 'Core error',
  3508. E_CORE_WARNING => 'Core warning',
  3509. E_COMPILE_ERROR => 'Compile error',
  3510. E_COMPILE_WARNING => 'Compile warning',
  3511. E_USER_ERROR => 'User error',
  3512. E_USER_WARNING => 'User warning',
  3513. E_USER_NOTICE => 'User notice',
  3514. E_STRICT => 'Strict warning',
  3515. E_RECOVERABLE_ERROR => 'Recoverable fatal error'
  3516. );
  3517. $caller = _drupal_get_last_caller(debug_backtrace());
  3518. // We treat recoverable errors as fatal.
  3519. _drupal_log_error(array(
  3520. '%type' => isset($types[$error_level]) ? $types[$error_level] : 'Unknown error',
  3521. '%message' => $message,
  3522. '%function' => $caller['function'],
  3523. '%file' => $caller['file'],
  3524. '%line' => $caller['line'],
  3525. ), $error_level == E_RECOVERABLE_ERROR);
  3526. }
  3527. }
  3528. /**
  3529. * Custom PHP exception handler.
  3530. *
  3531. * Uncaught exceptions are those not enclosed in a try/catch block. They are
  3532. * always fatal: the execution of the script will stop as soon as the exception
  3533. * handler exits.
  3534. *
  3535. * @param $exception
  3536. * The exception object that was thrown.
  3537. */
  3538. function _drupal_exception_handler($exception) {
  3539. // Log the message to the watchdog and return an error page to the user.
  3540. _drupal_log_error(_drupal_decode_exception($exception), TRUE);
  3541. }
  3542. /**
  3543. * Decode an exception, especially to retrive the correct caller.
  3544. *
  3545. * @param $exception
  3546. * The exception object that was thrown.
  3547. * @return An error in the format expected by _drupal_log_error().
  3548. */
  3549. function _drupal_decode_exception($exception) {
  3550. $message = $exception->getMessage();
  3551. $backtrace = $exception->getTrace();
  3552. // Add the line throwing the exception to the backtrace.
  3553. array_unshift($backtrace, array('line' => $exception->getLine(), 'file' => $exception->getFile()));
  3554. // For PDOException errors, we try to return the initial caller,
  3555. // skipping internal functions of the database layer.
  3556. if ($exception instanceof PDOException) {
  3557. // The first element in the stack is the call, the second element gives us the caller.
  3558. // We skip calls that occurred in one of the classes of the database layer
  3559. // or in one of its global functions.
  3560. $db_functions = array('db_query', 'pager_query', 'db_query_range', 'db_query_temporary', 'update_sql');
  3561. while (!empty($backtrace[1]) && ($caller = $backtrace[1]) &&
  3562. ((isset($caller['class']) && (strpos($caller['class'], 'Query') !== FALSE || strpos($caller['class'], 'Database') !== FALSE || strpos($caller['class'], 'PDO') !== FALSE)) ||
  3563. in_array($caller['function'], $db_functions))) {
  3564. // We remove that call.
  3565. array_shift($backtrace);
  3566. }
  3567. if (isset($exception->query_string, $exception->args)) {
  3568. $message .= ": " . $exception->query_string . "; " . print_r($exception->args, TRUE);
  3569. }
  3570. }
  3571. $caller = _drupal_get_last_caller($backtrace);
  3572. return array(
  3573. '%type' => get_class($exception),
  3574. '%message' => $message,
  3575. '%function' => $caller['function'],
  3576. '%file' => $caller['file'],
  3577. '%line' => $caller['line'],
  3578. );
  3579. }
  3580. /**
  3581. * Log a PHP error or exception, display an error page in fatal cases.
  3582. *
  3583. * @param $error
  3584. * An array with the following keys: %type, %message, %function, %file, %line.
  3585. * @param $fatal
  3586. * TRUE if the error is fatal.
  3587. */
  3588. function _drupal_log_error($error, $fatal = FALSE) {
  3589. // Initialize a maintenance theme if the boostrap was not complete.
  3590. // Do it early because drupal_set_message() triggers a drupal_theme_initialize().
  3591. if ($fatal && (drupal_get_bootstrap_phase() != DRUPAL_BOOTSTRAP_FULL)) {
  3592. unset($GLOBALS['theme']);
  3593. if (!defined('MAINTENANCE_MODE')) {
  3594. define('MAINTENANCE_MODE', 'error');
  3595. }
  3596. drupal_maintenance_theme();
  3597. }
  3598. // When running inside the testing framework, we relay the errors
  3599. // to the tested site by the way of HTTP headers.
  3600. if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/^simpletest\d+;/", $_SERVER['HTTP_USER_AGENT']) && !headers_sent() && (!defined('SIMPLETEST_COLLECT_ERRORS') || SIMPLETEST_COLLECT_ERRORS)) {
  3601. // $number does not use drupal_static as it should not be reset
  3602. // as it uniquely identifies each PHP error.
  3603. static $number = 0;
  3604. $assertion = array(
  3605. $error['%message'],
  3606. $error['%type'],
  3607. array(
  3608. 'function' => $error['%function'],
  3609. 'file' => $error['%file'],
  3610. 'line' => $error['%line'],
  3611. ),
  3612. );
  3613. header('X-Drupal-Assertion-' . $number . ': ' . rawurlencode(serialize($assertion)));
  3614. $number++;
  3615. }
  3616. try {
  3617. watchdog('php', '%type: %message in %function (line %line of %file).', $error, WATCHDOG_ERROR);
  3618. }
  3619. catch (Exception $e) {
  3620. // Ignore any additional watchdog exception, as that probably means
  3621. // that the database was not initialized correctly.
  3622. }
  3623. if ($fatal) {
  3624. drupal_set_header('500 Service unavailable (with message)');
  3625. }
  3626. if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
  3627. if ($fatal) {
  3628. // When called from JavaScript, simply output the error message.
  3629. print t('%type: %message in %function (line %line of %file).', $error);
  3630. exit;
  3631. }
  3632. }
  3633. else {
  3634. // Display the message if the current error reporting level allows this type
  3635. // of message to be displayed, and unconditionnaly in update.php.
  3636. $error_level = variable_get('error_level', ERROR_REPORTING_DISPLAY_ALL);
  3637. $display_error = $error_level == ERROR_REPORTING_DISPLAY_ALL || ($error_level == ERROR_REPORTING_DISPLAY_SOME && $error['%type'] != 'Notice');
  3638. if ($display_error || (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update')) {
  3639. $class = 'error';
  3640. // If error type is 'User notice' then treat it as debug information
  3641. // instead of an error message, see dd().
  3642. if ($error['%type'] == 'User notice') {
  3643. $error['%type'] = 'Debug';
  3644. $class = 'status';
  3645. }
  3646. drupal_set_message(t('%type: %message in %function (line %line of %file).', $error), $class);
  3647. }
  3648. if ($fatal) {
  3649. drupal_set_title(t('Error'));
  3650. // We fallback to a maintenance page at this point, because the page generation
  3651. // itself can generate errors.
  3652. print theme('maintenance_page', t('The website encountered an unexpected error. Please try again later.'));
  3653. exit;
  3654. }
  3655. }
  3656. }
  3657. /**
  3658. * Gets the last caller from a backtrace.
  3659. *
  3660. * @param $backtrace
  3661. * A standard PHP backtrace.
  3662. * @return
  3663. * An associative array with keys 'file', 'line' and 'function'.
  3664. */
  3665. function _drupal_get_last_caller($backtrace) {
  3666. // Errors that occur inside PHP internal functions do not generate
  3667. // information about file and line. Ignore black listed functions.
  3668. $blacklist = array('debug');
  3669. while (($backtrace && !isset($backtrace[0]['line'])) ||
  3670. (isset($backtrace[1]['function']) && in_array($backtrace[1]['function'], $blacklist))) {
  3671. array_shift($backtrace);
  3672. }
  3673. // The first trace is the call itself.
  3674. // It gives us the line and the file of the last call.
  3675. $call = $backtrace[0];
  3676. // The second call give us the function where the call originated.
  3677. if (isset($backtrace[1])) {
  3678. if (isset($backtrace[1]['class'])) {
  3679. $call['function'] = $backtrace[1]['class'] . $backtrace[1]['type'] . $backtrace[1]['function'] . '()';
  3680. }
  3681. else {
  3682. $call['function'] = $backtrace[1]['function'] . '()';
  3683. }
  3684. }
  3685. else {
  3686. $call['function'] = 'main()';
  3687. }
  3688. return $call;
  3689. }
  3690. /**
  3691. * Debug function used for outputting debug information.
  3692. *
  3693. * The debug information is passed on to trigger_error() after being converted
  3694. * to a string using _drupal_debug_message().
  3695. *
  3696. * @param $data
  3697. * Data to be output.
  3698. * @param $label
  3699. * Label to prefix the data.
  3700. * @param $print_r
  3701. * Flag to switch between print_r() and var_export() for data conversion to
  3702. * string. Set $print_r to TRUE when dealing with a recursive data structure
  3703. * as var_export() will generate an error.
  3704. */
  3705. function debug($data, $label = NULL, $print_r = FALSE) {
  3706. // Print $data contents to string.
  3707. $string = $print_r ? print_r($data, TRUE) : var_export($data, TRUE);
  3708. trigger_error(trim($label ? "$label: $string" : $string));
  3709. }