common.inc

Common functions that many Drupal modules will need to reference.

The functions that are critical and need to be available even when serving a cached page are instead located in bootstrap.inc.

Archivo

drupal-6.x/includes/common.inc
View source
  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. * Error code indicating that the request made by drupal_http_request() exceeded
  29. * the specified timeout.
  30. */
  31. define('HTTP_REQUEST_TIMEOUT', -1);
  32. /**
  33. * Set content for a specified region.
  34. *
  35. * @param $region
  36. * Page region the content is assigned to.
  37. * @param $data
  38. * Content to be set.
  39. */
  40. function drupal_set_content($region = NULL, $data = NULL) {
  41. static $content = array();
  42. if (!is_null($region) && !is_null($data)) {
  43. $content[$region][] = $data;
  44. }
  45. return $content;
  46. }
  47. /**
  48. * Get assigned content.
  49. *
  50. * @param $region
  51. * A specified region to fetch content for. If NULL, all regions will be
  52. * returned.
  53. * @param $delimiter
  54. * Content to be inserted between imploded array elements.
  55. */
  56. function drupal_get_content($region = NULL, $delimiter = ' ') {
  57. $content = drupal_set_content();
  58. if (isset($region)) {
  59. if (isset($content[$region]) && is_array($content[$region])) {
  60. return implode($delimiter, $content[$region]);
  61. }
  62. }
  63. else {
  64. foreach (array_keys($content) as $region) {
  65. if (is_array($content[$region])) {
  66. $content[$region] = implode($delimiter, $content[$region]);
  67. }
  68. }
  69. return $content;
  70. }
  71. }
  72. /**
  73. * Set the breadcrumb trail for the current page.
  74. *
  75. * @param $breadcrumb
  76. * Array of links, starting with "home" and proceeding up to but not including
  77. * the current page.
  78. */
  79. function drupal_set_breadcrumb($breadcrumb = NULL) {
  80. static $stored_breadcrumb;
  81. if (!is_null($breadcrumb)) {
  82. $stored_breadcrumb = $breadcrumb;
  83. }
  84. return $stored_breadcrumb;
  85. }
  86. /**
  87. * Get the breadcrumb trail for the current page.
  88. */
  89. function drupal_get_breadcrumb() {
  90. $breadcrumb = drupal_set_breadcrumb();
  91. if (is_null($breadcrumb)) {
  92. $breadcrumb = menu_get_active_breadcrumb();
  93. }
  94. return $breadcrumb;
  95. }
  96. /**
  97. * Add output to the head tag of the HTML page.
  98. *
  99. * This function can be called as long the headers aren't sent.
  100. */
  101. function drupal_set_html_head($data = NULL) {
  102. static $stored_head = '';
  103. if (!is_null($data)) {
  104. $stored_head .= $data ."\n";
  105. }
  106. return $stored_head;
  107. }
  108. /**
  109. * Retrieve output to be displayed in the head tag of the HTML page.
  110. */
  111. function drupal_get_html_head() {
  112. $output = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
  113. return $output . drupal_set_html_head();
  114. }
  115. /**
  116. * Reset the static variable which holds the aliases mapped for this request.
  117. */
  118. function drupal_clear_path_cache() {
  119. drupal_lookup_path('wipe');
  120. }
  121. /**
  122. * Set an HTTP response header for the current page.
  123. *
  124. * Note: When sending a Content-Type header, always include a 'charset' type,
  125. * too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
  126. */
  127. function drupal_set_header($header = NULL) {
  128. // We use an array to guarantee there are no leading or trailing delimiters.
  129. // Otherwise, header('') could get called when serving the page later, which
  130. // ends HTTP headers prematurely on some PHP versions.
  131. static $stored_headers = array();
  132. if (strlen($header)) {
  133. header($header);
  134. $stored_headers[] = $header;
  135. }
  136. return implode("\n", $stored_headers);
  137. }
  138. /**
  139. * Get the HTTP response headers for the current page.
  140. */
  141. function drupal_get_headers() {
  142. return drupal_set_header();
  143. }
  144. /**
  145. * Make any final alterations to the rendered xhtml.
  146. */
  147. function drupal_final_markup($content) {
  148. // Make sure that the charset is always specified as the first element of the
  149. // head region to prevent encoding-based attacks.
  150. return preg_replace('/<head[^>]*>/i', "\$0\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />", $content, 1);
  151. }
  152. /**
  153. * Add a feed URL for the current page.
  154. *
  155. * @param $url
  156. * A URL for the feed.
  157. * @param $title
  158. * The title of the feed.
  159. */
  160. function drupal_add_feed($url = NULL, $title = '') {
  161. static $stored_feed_links = array();
  162. if (!is_null($url) && !isset($stored_feed_links[$url])) {
  163. $stored_feed_links[$url] = theme('feed_icon', $url, $title);
  164. drupal_add_link(array('rel' => 'alternate',
  165. 'type' => 'application/rss+xml',
  166. 'title' => $title,
  167. 'href' => $url));
  168. }
  169. return $stored_feed_links;
  170. }
  171. /**
  172. * Get the feed URLs for the current page.
  173. *
  174. * @param $delimiter
  175. * A delimiter to split feeds by.
  176. */
  177. function drupal_get_feeds($delimiter = "\n") {
  178. $feeds = drupal_add_feed();
  179. return implode($feeds, $delimiter);
  180. }
  181. /**
  182. * @defgroup http_handling HTTP handling
  183. * @{
  184. * Functions to properly handle HTTP responses.
  185. */
  186. /**
  187. * Parse an array into a valid urlencoded query string.
  188. *
  189. * @param $query
  190. * The array to be processed e.g. $_GET.
  191. * @param $exclude
  192. * The array filled with keys to be excluded. Use parent[child] to exclude
  193. * nested items.
  194. * @param $parent
  195. * Should not be passed, only used in recursive calls.
  196. * @return
  197. * An urlencoded string which can be appended to/as the URL query string.
  198. */
  199. function drupal_query_string_encode($query, $exclude = array(), $parent = '') {
  200. $params = array();
  201. foreach ($query as $key => $value) {
  202. $key = rawurlencode($key);
  203. if ($parent) {
  204. $key = $parent .'['. $key .']';
  205. }
  206. if (in_array($key, $exclude)) {
  207. continue;
  208. }
  209. if (is_array($value)) {
  210. $params[] = drupal_query_string_encode($value, $exclude, $key);
  211. }
  212. else {
  213. $params[] = $key .'='. rawurlencode($value);
  214. }
  215. }
  216. return implode('&', $params);
  217. }
  218. /**
  219. * Prepare a destination query string for use in combination with drupal_goto().
  220. *
  221. * Used to direct the user back to the referring page after completing a form.
  222. * By default the current URL is returned. If a destination exists in the
  223. * previous request, that destination is returned. As such, a destination can
  224. * persist across multiple pages.
  225. *
  226. * @see drupal_goto()
  227. */
  228. function drupal_get_destination() {
  229. if (isset($_REQUEST['destination'])) {
  230. return 'destination='. urlencode($_REQUEST['destination']);
  231. }
  232. else {
  233. // Use $_GET here to retrieve the original path in source form.
  234. $path = isset($_GET['q']) ? $_GET['q'] : '';
  235. $query = drupal_query_string_encode($_GET, array('q'));
  236. if ($query != '') {
  237. $path .= '?'. $query;
  238. }
  239. return 'destination='. urlencode($path);
  240. }
  241. }
  242. /**
  243. * Send the user to a different Drupal page.
  244. *
  245. * This issues an on-site HTTP redirect. The function makes sure the redirected
  246. * URL is formatted correctly.
  247. *
  248. * Usually the redirected URL is constructed from this function's input
  249. * parameters. However you may override that behavior by setting a
  250. * destination in either the $_REQUEST-array (i.e. by using
  251. * the query string of an URI) or the $_REQUEST['edit']-array (i.e. by
  252. * using a hidden form field). This is used to direct the user back to
  253. * the proper page after completing a form. For example, after editing
  254. * a post on the 'admin/content/node'-page or after having logged on using the
  255. * 'user login'-block in a sidebar. The function drupal_get_destination()
  256. * can be used to help set the destination URL.
  257. *
  258. * Drupal will ensure that messages set by drupal_set_message() and other
  259. * session data are written to the database before the user is redirected.
  260. *
  261. * This function ends the request; use it rather than a print theme('page')
  262. * statement in your menu callback.
  263. *
  264. * @param $path
  265. * (optional) A Drupal path or a full URL, which will be passed to url() to
  266. * compute the redirect for the URL.
  267. * @param $query
  268. * (optional) A URL-encoded query string to append to the link, or an array of
  269. * query key/value-pairs without any URL-encoding. Passed to url().
  270. * @param $fragment
  271. * (optional) A destination fragment identifier (named anchor).
  272. * @param $http_response_code
  273. * (optional) The HTTP status code to use for the redirection, defaults to
  274. * 302. Valid values for an actual "goto" as per RFC 2616 section 10.3 are:
  275. * - 301 Moved Permanently (the recommended value for most redirects)
  276. * - 302 Found (default in Drupal and PHP, sometimes used for spamming search
  277. * engines)
  278. * - 303 See Other
  279. * - 304 Not Modified
  280. * - 305 Use Proxy
  281. * - 307 Temporary Redirect (alternative to "503 Site Down for Maintenance")
  282. * Note: Other values are defined by RFC 2616, but are rarely used and poorly
  283. * supported.
  284. * @see drupal_get_destination()
  285. */
  286. function drupal_goto($path = '', $query = NULL, $fragment = NULL, $http_response_code = 302) {
  287. $destination = FALSE;
  288. if (isset($_REQUEST['destination'])) {
  289. $destination = $_REQUEST['destination'];
  290. }
  291. else if (isset($_REQUEST['edit']['destination'])) {
  292. $destination = $_REQUEST['edit']['destination'];
  293. }
  294. if ($destination) {
  295. // Do not redirect to an absolute URL originating from user input.
  296. $colonpos = strpos($destination, ':');
  297. $absolute = ($colonpos !== FALSE && !preg_match('![/?#]!', substr($destination, 0, $colonpos)));
  298. if (!$absolute) {
  299. extract(parse_url(urldecode($destination)));
  300. }
  301. }
  302. $url = url($path, array('query' => $query, 'fragment' => $fragment, 'absolute' => TRUE));
  303. // Remove newlines from the URL to avoid header injection attacks.
  304. $url = str_replace(array("\n", "\r"), '', $url);
  305. // Allow modules to react to the end of the page request before redirecting.
  306. // We do not want this while running update.php.
  307. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
  308. module_invoke_all('exit', $url);
  309. }
  310. // Even though session_write_close() is registered as a shutdown function, we
  311. // need all session data written to the database before redirecting.
  312. session_write_close();
  313. header('Location: '. $url, TRUE, $http_response_code);
  314. // The "Location" header sends a redirect status code to the HTTP daemon. In
  315. // some cases this can be wrong, so we make sure none of the code below the
  316. // drupal_goto() call gets executed upon redirection.
  317. exit();
  318. }
  319. /**
  320. * Generates a site off-line message.
  321. */
  322. function drupal_site_offline() {
  323. drupal_maintenance_theme();
  324. drupal_set_header($_SERVER['SERVER_PROTOCOL'] .' 503 Service unavailable');
  325. drupal_set_title(t('Site off-line'));
  326. print theme('maintenance_page', filter_xss_admin(variable_get('site_offline_message',
  327. t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal'))))));
  328. }
  329. /**
  330. * Generates a 404 error if the request can not be handled.
  331. */
  332. function drupal_not_found() {
  333. drupal_set_header($_SERVER['SERVER_PROTOCOL'] .' 404 Not Found');
  334. watchdog('page not found', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
  335. // Keep old path for reference, and to allow forms to redirect to it.
  336. if (!isset($_REQUEST['destination'])) {
  337. $_REQUEST['destination'] = $_GET['q'];
  338. }
  339. $path = drupal_get_normal_path(variable_get('site_404', ''));
  340. if ($path && $path != $_GET['q']) {
  341. // Set the active item in case there are tabs to display, or other
  342. // dependencies on the path.
  343. menu_set_active_item($path);
  344. $return = menu_execute_active_handler($path);
  345. }
  346. if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
  347. drupal_set_title(t('Page not found'));
  348. $return = t('The requested page could not be found.');
  349. }
  350. // To conserve CPU and bandwidth, omit the blocks.
  351. print theme('page', $return, FALSE);
  352. }
  353. /**
  354. * Generates a 403 error if the request is not allowed.
  355. */
  356. function drupal_access_denied() {
  357. drupal_set_header($_SERVER['SERVER_PROTOCOL'] .' 403 Forbidden');
  358. watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
  359. // Keep old path for reference, and to allow forms to redirect to it.
  360. if (!isset($_REQUEST['destination'])) {
  361. $_REQUEST['destination'] = $_GET['q'];
  362. }
  363. $path = drupal_get_normal_path(variable_get('site_403', ''));
  364. if ($path && $path != $_GET['q']) {
  365. // Set the active item in case there are tabs to display or other
  366. // dependencies on the path.
  367. menu_set_active_item($path);
  368. $return = menu_execute_active_handler($path);
  369. }
  370. if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
  371. drupal_set_title(t('Access denied'));
  372. $return = t('You are not authorized to access this page.');
  373. }
  374. print theme('page', $return);
  375. }
  376. /**
  377. * Perform an HTTP request.
  378. *
  379. * This is a flexible and powerful HTTP client implementation. Correctly handles
  380. * GET, POST, PUT or any other HTTP requests. Handles redirects.
  381. *
  382. * @param $url
  383. * A string containing a fully qualified URI.
  384. * @param $headers
  385. * An array containing an HTTP header => value pair.
  386. * @param $method
  387. * A string defining the HTTP request to use.
  388. * @param $data
  389. * A string containing data to include in the request.
  390. * @param $retry
  391. * An integer representing how many times to retry the request in case of a
  392. * redirect.
  393. * @param $timeout
  394. * A float representing the maximum number of seconds the function call may
  395. * take. The default is 30 seconds. If a timeout occurs, the error code is set
  396. * to the HTTP_REQUEST_TIMEOUT constant.
  397. * @return
  398. * An object containing the HTTP request headers, response code, protocol,
  399. * status message, headers, data and redirect status.
  400. */
  401. function drupal_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3, $timeout = 30.0) {
  402. global $db_prefix;
  403. $result = new stdClass();
  404. // Parse the URL and make sure we can handle the schema.
  405. $uri = parse_url($url);
  406. if ($uri == FALSE) {
  407. $result->error = 'unable to parse URL';
  408. $result->code = -1001;
  409. return $result;
  410. }
  411. if (!isset($uri['scheme'])) {
  412. $result->error = 'missing schema';
  413. $result->code = -1002;
  414. return $result;
  415. }
  416. timer_start(__FUNCTION__);
  417. switch ($uri['scheme']) {
  418. case 'http':
  419. case 'feed':
  420. $port = isset($uri['port']) ? $uri['port'] : 80;
  421. $host = $uri['host'] . ($port != 80 ? ':'. $port : '');
  422. $fp = @fsockopen($uri['host'], $port, $errno, $errstr, $timeout);
  423. break;
  424. case 'https':
  425. // Note: Only works for PHP 4.3 compiled with OpenSSL.
  426. $port = isset($uri['port']) ? $uri['port'] : 443;
  427. $host = $uri['host'] . ($port != 443 ? ':'. $port : '');
  428. $fp = @fsockopen('ssl://'. $uri['host'], $port, $errno, $errstr, $timeout);
  429. break;
  430. default:
  431. $result->error = 'invalid schema '. $uri['scheme'];
  432. $result->code = -1003;
  433. return $result;
  434. }
  435. // Make sure the socket opened properly.
  436. if (!$fp) {
  437. // When a network error occurs, we use a negative number so it does not
  438. // clash with the HTTP status codes.
  439. $result->code = -$errno;
  440. $result->error = trim($errstr);
  441. // Mark that this request failed. This will trigger a check of the web
  442. // server's ability to make outgoing HTTP requests the next time that
  443. // requirements checking is performed.
  444. // @see system_requirements()
  445. variable_set('drupal_http_request_fails', TRUE);
  446. return $result;
  447. }
  448. // Construct the path to act on.
  449. $path = isset($uri['path']) ? $uri['path'] : '/';
  450. if (isset($uri['query'])) {
  451. $path .= '?'. $uri['query'];
  452. }
  453. // Create HTTP request.
  454. $defaults = array(
  455. // RFC 2616: "non-standard ports MUST, default ports MAY be included".
  456. // We don't add the port to prevent from breaking rewrite rules checking the
  457. // host that do not take into account the port number.
  458. 'Host' => "Host: $host",
  459. 'User-Agent' => 'User-Agent: Drupal (+http://drupal.org/)',
  460. );
  461. // Only add Content-Length if we actually have any content or if it is a POST
  462. // or PUT request. Some non-standard servers get confused by Content-Length in
  463. // at least HEAD/GET requests, and Squid always requires Content-Length in
  464. // POST/PUT requests.
  465. $content_length = strlen($data);
  466. if ($content_length > 0 || $method == 'POST' || $method == 'PUT') {
  467. $defaults['Content-Length'] = 'Content-Length: '. $content_length;
  468. }
  469. // If the server URL has a user then attempt to use basic authentication
  470. if (isset($uri['user'])) {
  471. $defaults['Authorization'] = 'Authorization: Basic '. base64_encode($uri['user'] . (!empty($uri['pass']) ? ":". $uri['pass'] : ''));
  472. }
  473. // If the database prefix is being used by SimpleTest to run the tests in a copied
  474. // database then set the user-agent header to the database prefix so that any
  475. // calls to other Drupal pages will run the SimpleTest prefixed database. The
  476. // user-agent is used to ensure that multiple testing sessions running at the
  477. // same time won't interfere with each other as they would if the database
  478. // prefix were stored statically in a file or database variable.
  479. if (is_string($db_prefix) && preg_match("/^simpletest\d+$/", $db_prefix, $matches)) {
  480. $defaults['User-Agent'] = 'User-Agent: ' . $matches[0];
  481. }
  482. foreach ($headers as $header => $value) {
  483. $defaults[$header] = $header .': '. $value;
  484. }
  485. $request = $method .' '. $path ." HTTP/1.0\r\n";
  486. $request .= implode("\r\n", $defaults);
  487. $request .= "\r\n\r\n";
  488. $request .= $data;
  489. $result->request = $request;
  490. // Calculate how much time is left of the original timeout value.
  491. $time_left = $timeout - timer_read(__FUNCTION__) / 1000;
  492. if ($time_left > 0) {
  493. stream_set_timeout($fp, floor($time_left), floor(1000000 * fmod($time_left, 1)));
  494. fwrite($fp, $request);
  495. }
  496. // Fetch response.
  497. $response = '';
  498. while (!feof($fp)) {
  499. // Calculate how much time is left of the original timeout value.
  500. $time_left = $timeout - timer_read(__FUNCTION__) / 1000;
  501. if ($time_left <= 0) {
  502. $result->code = HTTP_REQUEST_TIMEOUT;
  503. $result->error = 'request timed out';
  504. return $result;
  505. }
  506. stream_set_timeout($fp, floor($time_left), floor(1000000 * fmod($time_left, 1)));
  507. $chunk = fread($fp, 1024);
  508. $response .= $chunk;
  509. }
  510. fclose($fp);
  511. // Parse response headers from the response body.
  512. // Be tolerant of malformed HTTP responses that separate header and body with
  513. // \n\n or \r\r instead of \r\n\r\n. See http://drupal.org/node/183435
  514. list($split, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
  515. $split = preg_split("/\r\n|\n|\r/", $split);
  516. list($protocol, $code, $status_message) = explode(' ', trim(array_shift($split)), 3);
  517. $result->protocol = $protocol;
  518. $result->status_message = $status_message;
  519. $result->headers = array();
  520. // Parse headers.
  521. while ($line = trim(array_shift($split))) {
  522. list($header, $value) = explode(':', $line, 2);
  523. if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
  524. // RFC 2109: the Set-Cookie response header comprises the token Set-
  525. // Cookie:, followed by a comma-separated list of one or more cookies.
  526. $result->headers[$header] .= ','. trim($value);
  527. }
  528. else {
  529. $result->headers[$header] = trim($value);
  530. }
  531. }
  532. $responses = array(
  533. 100 => 'Continue', 101 => 'Switching Protocols',
  534. 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
  535. 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
  536. 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',
  537. 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'
  538. );
  539. // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  540. // base code in their class.
  541. if (!isset($responses[$code])) {
  542. $code = floor($code / 100) * 100;
  543. }
  544. switch ($code) {
  545. case 200: // OK
  546. case 304: // Not modified
  547. break;
  548. case 301: // Moved permanently
  549. case 302: // Moved temporarily
  550. case 307: // Moved temporarily
  551. $location = $result->headers['Location'];
  552. $timeout -= timer_read(__FUNCTION__) / 1000;
  553. if ($timeout <= 0) {
  554. $result->code = HTTP_REQUEST_TIMEOUT;
  555. $result->error = 'request timed out';
  556. }
  557. elseif ($retry) {
  558. $result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry, $timeout);
  559. $result->redirect_code = $result->code;
  560. }
  561. $result->redirect_url = $location;
  562. break;
  563. default:
  564. $result->error = $status_message;
  565. }
  566. $result->code = $code;
  567. return $result;
  568. }
  569. /**
  570. * @} End of "HTTP handling".
  571. */
  572. /**
  573. * Log errors as defined by administrator.
  574. *
  575. * Error levels:
  576. * - 0 = Log errors to database.
  577. * - 1 = Log errors to database and to screen.
  578. */
  579. function drupal_error_handler($errno, $message, $filename, $line, $context) {
  580. // If the @ error suppression operator was used, error_reporting will have
  581. // been temporarily set to 0.
  582. if (error_reporting() == 0) {
  583. return;
  584. }
  585. if ($errno & (E_ALL ^ E_DEPRECATED)) {
  586. $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');
  587. // For database errors, we want the line number/file name of the place that
  588. // the query was originally called, not _db_query().
  589. if (isset($context[DB_ERROR])) {
  590. $backtrace = array_reverse(debug_backtrace());
  591. // List of functions where SQL queries can originate.
  592. $query_functions = array('db_query', 'pager_query', 'db_query_range', 'db_query_temporary', 'update_sql');
  593. // Determine where query function was called, and adjust line/file
  594. // accordingly.
  595. foreach ($backtrace as $index => $function) {
  596. if (in_array($function['function'], $query_functions)) {
  597. $line = $backtrace[$index]['line'];
  598. $filename = $backtrace[$index]['file'];
  599. break;
  600. }
  601. }
  602. }
  603. // Try to use filter_xss(). If it's too early in the bootstrap process for
  604. // filter_xss() to be loaded, use check_plain() instead.
  605. $entry = check_plain($types[$errno]) .': '. (function_exists('filter_xss') ? filter_xss($message) : check_plain($message)) .' in '. check_plain($filename) .' on line '. check_plain($line) .'.';
  606. // Force display of error messages in update.php.
  607. if (variable_get('error_level', 1) == 1 || strstr($_SERVER['SCRIPT_NAME'], 'update.php')) {
  608. drupal_set_message($entry, 'error');
  609. }
  610. watchdog('php', '%message in %file on line %line.', array('%error' => $types[$errno], '%message' => $message, '%file' => $filename, '%line' => $line), WATCHDOG_ERROR);
  611. }
  612. }
  613. function _fix_gpc_magic(&$item) {
  614. if (is_array($item)) {
  615. array_walk($item, '_fix_gpc_magic');
  616. }
  617. else {
  618. $item = stripslashes($item);
  619. }
  620. }
  621. /**
  622. * Helper function to strip slashes from $_FILES skipping over the tmp_name keys
  623. * since PHP generates single backslashes for file paths on Windows systems.
  624. *
  625. * tmp_name does not have backslashes added see
  626. * http://php.net/manual/en/features.file-upload.php#42280
  627. */
  628. function _fix_gpc_magic_files(&$item, $key) {
  629. if ($key != 'tmp_name') {
  630. if (is_array($item)) {
  631. array_walk($item, '_fix_gpc_magic_files');
  632. }
  633. else {
  634. $item = stripslashes($item);
  635. }
  636. }
  637. }
  638. /**
  639. * Fix double-escaping problems caused by "magic quotes" in some PHP installations.
  640. */
  641. function fix_gpc_magic() {
  642. static $fixed = FALSE;
  643. if (!$fixed && ini_get('magic_quotes_gpc')) {
  644. array_walk($_GET, '_fix_gpc_magic');
  645. array_walk($_POST, '_fix_gpc_magic');
  646. array_walk($_COOKIE, '_fix_gpc_magic');
  647. array_walk($_REQUEST, '_fix_gpc_magic');
  648. array_walk($_FILES, '_fix_gpc_magic_files');
  649. $fixed = TRUE;
  650. }
  651. }
  652. /**
  653. * Translate strings to the page language or a given language.
  654. *
  655. * Human-readable text that will be displayed somewhere within a page should
  656. * be run through the t() function.
  657. *
  658. * Examples:
  659. * @code
  660. * if (!$info || !$info['extension']) {
  661. * form_set_error('picture_upload', t('The uploaded file was not an image.'));
  662. * }
  663. *
  664. * $form['submit'] = array(
  665. * '#type' => 'submit',
  666. * '#value' => t('Log in'),
  667. * );
  668. * @endcode
  669. *
  670. * Any text within t() can be extracted by translators and changed into
  671. * the equivalent text in their native language.
  672. *
  673. * Special variables called "placeholders" are used to signal dynamic
  674. * information in a string which should not be translated. Placeholders
  675. * can also be used for text that may change from time to time (such as
  676. * link paths) to be changed without requiring updates to translations.
  677. *
  678. * For example:
  679. * @code
  680. * $output = t('There are currently %members and %visitors online.', array(
  681. * '%members' => format_plural($total_users, '1 user', '@count users'),
  682. * '%visitors' => format_plural($guests->count, '1 guest', '@count guests')));
  683. * @endcode
  684. *
  685. * There are three styles of placeholders:
  686. * - !variable, which indicates that the text should be inserted as-is. This is
  687. * useful for inserting variables into things like e-mail.
  688. * @code
  689. * $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))));
  690. * @endcode
  691. *
  692. * - @variable, which indicates that the text should be run through
  693. * check_plain, to escape HTML characters. Use this for any output that's
  694. * displayed within a Drupal page.
  695. * @code
  696. * drupal_set_title($title = t("@name's blog", array('@name' => $account->name)));
  697. * @endcode
  698. *
  699. * - %variable, which indicates that the string should be HTML escaped and
  700. * highlighted with theme_placeholder() which shows up by default as
  701. * <em>emphasized</em>.
  702. * @code
  703. * $message = t('%name-from sent %name-to an e-mail.', array('%name-from' => $user->name, '%name-to' => $account->name));
  704. * @endcode
  705. *
  706. * When using t(), try to put entire sentences and strings in one t() call.
  707. * This makes it easier for translators, as it provides context as to what
  708. * each word refers to. HTML markup within translation strings is allowed, but
  709. * should be avoided if possible. The exception are embedded links; link
  710. * titles add a context for translators, so should be kept in the main string.
  711. *
  712. * Here is an example of incorrect usage of t():
  713. * @code
  714. * $output .= t('<p>Go to the @contact-page.</p>', array('@contact-page' => l(t('contact page'), 'contact')));
  715. * @endcode
  716. *
  717. * Here is an example of t() used correctly:
  718. * @code
  719. * $output .= '<p>'. t('Go to the <a href="@contact-page">contact page</a>.', array('@contact-page' => url('contact'))) .'</p>';
  720. * @endcode
  721. *
  722. * Avoid escaping quotation marks wherever possible.
  723. *
  724. * Incorrect:
  725. * @code
  726. * $output .= t('Don\'t click me.');
  727. * @endcode
  728. *
  729. * Correct:
  730. * @code
  731. * $output .= t("Don't click me.");
  732. * @endcode
  733. *
  734. * Because t() is designed for handling code-based strings, in almost all
  735. * cases, the actual string and not a variable must be passed through t().
  736. *
  737. * Extraction of translations is done based on the strings contained in t()
  738. * calls. If a variable is passed through t(), the content of the variable
  739. * cannot be extracted from the file for translation.
  740. *
  741. * Incorrect:
  742. * @code
  743. * $message = 'An error occurred.';
  744. * drupal_set_message(t($message), 'error');
  745. * $output .= t($message);
  746. * @endcode
  747. *
  748. * Correct:
  749. * @code
  750. * $message = t('An error occurred.');
  751. * drupal_set_message($message, 'error');
  752. * $output .= $message;
  753. * @endcode
  754. *
  755. * The only case in which variables can be passed safely through t() is when
  756. * code-based versions of the same strings will be passed through t() (or
  757. * otherwise extracted) elsewhere.
  758. *
  759. * In some cases, modules may include strings in code that can't use t()
  760. * calls. For example, a module may use an external PHP application that
  761. * produces strings that are loaded into variables in Drupal for output.
  762. * In these cases, module authors may include a dummy file that passes the
  763. * relevant strings through t(). This approach will allow the strings to be
  764. * extracted.
  765. *
  766. * Sample external (non-Drupal) code:
  767. * @code
  768. * class Time {
  769. * public $yesterday = 'Yesterday';
  770. * public $today = 'Today';
  771. * public $tomorrow = 'Tomorrow';
  772. * }
  773. * @endcode
  774. *
  775. * Sample dummy file.
  776. * @code
  777. * // Dummy function included in example.potx.inc.
  778. * function example_potx() {
  779. * $strings = array(
  780. * t('Yesterday'),
  781. * t('Today'),
  782. * t('Tomorrow'),
  783. * );
  784. * // No return value needed, since this is a dummy function.
  785. * }
  786. * @endcode
  787. *
  788. * Having passed strings through t() in a dummy function, it is then
  789. * okay to pass variables through t().
  790. *
  791. * Correct (if a dummy file was used):
  792. * @code
  793. * $time = new Time();
  794. * $output .= t($time->today);
  795. * @endcode
  796. *
  797. * However tempting it is, custom data from user input or other non-code
  798. * sources should not be passed through t(). Doing so leads to the following
  799. * problems and errors:
  800. * - The t() system doesn't support updates to existing strings. When user
  801. * data is updated, the next time it's passed through t() a new record is
  802. * created instead of an update. The database bloats over time and any
  803. * existing translations are orphaned with each update.
  804. * - The t() system assumes any data it receives is in English. User data may
  805. * be in another language, producing translation errors.
  806. * - The "Built-in interface" text group in the locale system is used to
  807. * produce translations for storage in .po files. When non-code strings are
  808. * passed through t(), they are added to this text group, which is rendered
  809. * inaccurate since it is a mix of actual interface strings and various user
  810. * input strings of uncertain origin.
  811. *
  812. * Incorrect:
  813. * @code
  814. * $item = item_load();
  815. * $output .= check_plain(t($item['title']));
  816. * @endcode
  817. *
  818. * Instead, translation of these data can be done through the locale system,
  819. * either directly or through helper functions provided by contributed
  820. * modules.
  821. * @see hook_locale()
  822. *
  823. * During installation, st() is used in place of t(). Code that may be called
  824. * during installation or during normal operation should use the get_t()
  825. * helper function.
  826. * @see st()
  827. * @see get_t()
  828. *
  829. * @param $string
  830. * A string containing the English string to translate.
  831. * @param $args
  832. * An associative array of replacements to make after translation. Incidences
  833. * of any key in this array are replaced with the corresponding value. Based
  834. * on the first character of the key, the value is escaped and/or themed:
  835. * - !variable: inserted as is
  836. * - @variable: escape plain text to HTML (check_plain)
  837. * - %variable: escape text and theme as a placeholder for user-submitted
  838. * content (check_plain + theme_placeholder)
  839. * @param $langcode
  840. * Optional language code to translate to a language other than what is used
  841. * to display the page.
  842. * @return
  843. * The translated string.
  844. */
  845. function t($string, $args = array(), $langcode = NULL) {
  846. global $language;
  847. static $custom_strings;
  848. $langcode = isset($langcode) ? $langcode : $language->language;
  849. // First, check for an array of customized strings. If present, use the array
  850. // *instead of* database lookups. This is a high performance way to provide a
  851. // handful of string replacements. See settings.php for examples.
  852. // Cache the $custom_strings variable to improve performance.
  853. if (!isset($custom_strings[$langcode])) {
  854. $custom_strings[$langcode] = variable_get('locale_custom_strings_'. $langcode, array());
  855. }
  856. // Custom strings work for English too, even if locale module is disabled.
  857. if (isset($custom_strings[$langcode][$string])) {
  858. $string = $custom_strings[$langcode][$string];
  859. }
  860. // Translate with locale module if enabled.
  861. elseif (function_exists('locale') && $langcode != 'en') {
  862. $string = locale($string, $langcode);
  863. }
  864. if (empty($args)) {
  865. return $string;
  866. }
  867. else {
  868. // Transform arguments before inserting them.
  869. foreach ($args as $key => $value) {
  870. switch ($key[0]) {
  871. case '@':
  872. // Escaped only.
  873. $args[$key] = check_plain($value);
  874. break;
  875. case '%':
  876. default:
  877. // Escaped and placeholder.
  878. $args[$key] = theme('placeholder', $value);
  879. break;
  880. case '!':
  881. // Pass-through.
  882. }
  883. }
  884. return strtr($string, $args);
  885. }
  886. }
  887. /**
  888. * @defgroup validation Input validation
  889. * @{
  890. * Functions to validate user input.
  891. */
  892. /**
  893. * Verifies the syntax of the given e-mail address.
  894. *
  895. * See @link http://tools.ietf.org/html/rfc5322 RFC 5322 @endlink for details.
  896. *
  897. * @param $mail
  898. * A string containing an e-mail address.
  899. * @return
  900. * 1 if the email address is valid, 0 if it is invalid or empty, and FALSE if
  901. * there is an input error (such as passing in an array instead of a string).
  902. */
  903. function valid_email_address($mail) {
  904. $user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
  905. $domain = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+';
  906. $ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
  907. $ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';
  908. return preg_match("/^$user@($domain|(\[($ipv4|$ipv6)\]))$/", $mail);
  909. }
  910. /**
  911. * Verify the syntax of the given URL.
  912. *
  913. * This function should only be used on actual URLs. It should not be used for
  914. * Drupal menu paths, which can contain arbitrary characters.
  915. * Valid values per RFC 3986.
  916. *
  917. * @param $url
  918. * The URL to verify.
  919. * @param $absolute
  920. * Whether the URL is absolute (beginning with a scheme such as "http:").
  921. * @return
  922. * TRUE if the URL is in a valid format.
  923. */
  924. function valid_url($url, $absolute = FALSE) {
  925. if ($absolute) {
  926. return (bool)preg_match("
  927. /^ # Start at the beginning of the text
  928. (?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
  929. (?: # Userinfo (optional) which is typically
  930. (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
  931. (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
  932. )?
  933. (?:
  934. (?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
  935. |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
  936. )
  937. (?::[0-9]+)? # Server port number (optional)
  938. (?:[\/|\?]
  939. (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
  940. *)?
  941. $/xi", $url);
  942. }
  943. else {
  944. return (bool)preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url);
  945. }
  946. }
  947. /**
  948. * @} End of "defgroup validation".
  949. */
  950. /**
  951. * Register an event for the current visitor (hostname/IP) to the flood control mechanism.
  952. *
  953. * @param $name
  954. * The name of an event.
  955. */
  956. function flood_register_event($name) {
  957. db_query("INSERT INTO {flood} (event, hostname, timestamp) VALUES ('%s', '%s', %d)", $name, ip_address(), time());
  958. }
  959. /**
  960. * Check if the current visitor (hostname/IP) is allowed to proceed with the specified event.
  961. *
  962. * The user is allowed to proceed if he did not trigger the specified event more
  963. * than $threshold times per hour.
  964. *
  965. * @param $name
  966. * The name of the event.
  967. * @param $threshold
  968. * The maximum number of the specified event per hour (per visitor).
  969. * @return
  970. * True if the user did not exceed the hourly threshold. False otherwise.
  971. */
  972. function flood_is_allowed($name, $threshold) {
  973. $number = db_result(db_query("SELECT COUNT(*) FROM {flood} WHERE event = '%s' AND hostname = '%s' AND timestamp > %d", $name, ip_address(), time() - 3600));
  974. return ($number < $threshold ? TRUE : FALSE);
  975. }
  976. function check_file($filename) {
  977. return is_uploaded_file($filename);
  978. }
  979. /**
  980. * Prepare a URL for use in an HTML attribute. Strips harmful protocols.
  981. */
  982. function check_url($uri) {
  983. return filter_xss_bad_protocol($uri, FALSE);
  984. }
  985. /**
  986. * @defgroup format Formatting
  987. * @{
  988. * Functions to format numbers, strings, dates, etc.
  989. */
  990. /**
  991. * Formats an RSS channel.
  992. *
  993. * Arbitrary elements may be added using the $args associative array.
  994. */
  995. function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
  996. global $language;
  997. $langcode = $langcode ? $langcode : $language->language;
  998. $output = "<channel>\n";
  999. $output .= ' <title>'. check_plain($title) ."</title>\n";
  1000. $output .= ' <link>'. check_url($link) ."</link>\n";
  1001. // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
  1002. // We strip all HTML tags, but need to prevent double encoding from properly
  1003. // escaped source data (such as &amp becoming &amp;amp;).
  1004. $output .= ' <description>'. check_plain(decode_entities(strip_tags($description))) ."</description>\n";
  1005. $output .= ' <language>'. check_plain($langcode) ."</language>\n";
  1006. $output .= format_xml_elements($args);
  1007. $output .= $items;
  1008. $output .= "</channel>\n";
  1009. return $output;
  1010. }
  1011. /**
  1012. * Format a single RSS item.
  1013. *
  1014. * Arbitrary elements may be added using the $args associative array.
  1015. */
  1016. function format_rss_item($title, $link, $description, $args = array()) {
  1017. $output = "<item>\n";
  1018. $output .= ' <title>'. check_plain($title) ."</title>\n";
  1019. $output .= ' <link>'. check_url($link) ."</link>\n";
  1020. $output .= ' <description>'. check_plain($description) ."</description>\n";
  1021. $output .= format_xml_elements($args);
  1022. $output .= "</item>\n";
  1023. return $output;
  1024. }
  1025. /**
  1026. * Format XML elements.
  1027. *
  1028. * @param $array
  1029. * An array where each item represent an element and is either a:
  1030. * - (key => value) pair (<key>value</key>)
  1031. * - Associative array with fields:
  1032. * - 'key': element name
  1033. * - 'value': element contents
  1034. * - 'attributes': associative array of element attributes
  1035. *
  1036. * In both cases, 'value' can be a simple string, or it can be another array
  1037. * with the same format as $array itself for nesting.
  1038. */
  1039. function format_xml_elements($array) {
  1040. $output = '';
  1041. foreach ($array as $key => $value) {
  1042. if (is_numeric($key)) {
  1043. if ($value['key']) {
  1044. $output .= ' <'. $value['key'];
  1045. if (isset($value['attributes']) && is_array($value['attributes'])) {
  1046. $output .= drupal_attributes($value['attributes']);
  1047. }
  1048. if (isset($value['value']) && $value['value'] != '') {
  1049. $output .= '>'. (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) .'</'. $value['key'] .">\n";
  1050. }
  1051. else {
  1052. $output .= " />\n";
  1053. }
  1054. }
  1055. }
  1056. else {
  1057. $output .= ' <'. $key .'>'. (is_array($value) ? format_xml_elements($value) : check_plain($value)) ."</$key>\n";
  1058. }
  1059. }
  1060. return $output;
  1061. }
  1062. /**
  1063. * Format a string containing a count of items.
  1064. *
  1065. * This function ensures that the string is pluralized correctly. Since t() is
  1066. * called by this function, make sure not to pass already-localized strings to
  1067. * it.
  1068. *
  1069. * For example:
  1070. * @code
  1071. * $output = format_plural($node->comment_count, '1 comment', '@count comments');
  1072. * @endcode
  1073. *
  1074. * Example with additional replacements:
  1075. * @code
  1076. * $output = format_plural($update_count,
  1077. * 'Changed the content type of 1 post from %old-type to %new-type.',
  1078. * 'Changed the content type of @count posts from %old-type to %new-type.',
  1079. * array('%old-type' => $info->old_type, '%new-type' => $info->new_type)));
  1080. * @endcode
  1081. *
  1082. * @param $count
  1083. * The item count to display.
  1084. * @param $singular
  1085. * The string for the singular case. Please make sure it is clear this is
  1086. * singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
  1087. * Do not use @count in the singular string.
  1088. * @param $plural
  1089. * The string for the plural case. Please make sure it is clear this is plural,
  1090. * to ease translation. Use @count in place of the item count, as in "@count
  1091. * new comments".
  1092. * @param $args
  1093. * An associative array of replacements to make after translation. Incidences
  1094. * of any key in this array are replaced with the corresponding value.
  1095. * Based on the first character of the key, the value is escaped and/or themed:
  1096. * - !variable: inserted as is
  1097. * - @variable: escape plain text to HTML (check_plain)
  1098. * - %variable: escape text and theme as a placeholder for user-submitted
  1099. * content (check_plain + theme_placeholder)
  1100. * Note that you do not need to include @count in this array.
  1101. * This replacement is done automatically for the plural case.
  1102. * @param $langcode
  1103. * Optional language code to translate to a language other than
  1104. * what is used to display the page.
  1105. * @return
  1106. * A translated string.
  1107. */
  1108. function format_plural($count, $singular, $plural, $args = array(), $langcode = NULL) {
  1109. $args['@count'] = $count;
  1110. if ($count == 1) {
  1111. return t($singular, $args, $langcode);
  1112. }
  1113. // Get the plural index through the gettext formula.
  1114. $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, $langcode) : -1;
  1115. // Backwards compatibility.
  1116. if ($index < 0) {
  1117. return t($plural, $args, $langcode);
  1118. }
  1119. else {
  1120. switch ($index) {
  1121. case "0":
  1122. return t($singular, $args, $langcode);
  1123. case "1":
  1124. return t($plural, $args, $langcode);
  1125. default:
  1126. unset($args['@count']);
  1127. $args['@count['. $index .']'] = $count;
  1128. return t(strtr($plural, array('@count' => '@count['. $index .']')), $args, $langcode);
  1129. }
  1130. }
  1131. }
  1132. /**
  1133. * Parse a given byte count.
  1134. *
  1135. * @param $size
  1136. * A size expressed as a number of bytes with optional SI size and unit
  1137. * suffix (e.g. 2, 3K, 5MB, 10G).
  1138. * @return
  1139. * An integer representation of the size.
  1140. */
  1141. function parse_size($size) {
  1142. $suffixes = array(
  1143. '' => 1,
  1144. 'k' => 1024,
  1145. 'm' => 1048576, // 1024 * 1024
  1146. 'g' => 1073741824, // 1024 * 1024 * 1024
  1147. );
  1148. if (preg_match('/([0-9]+)\s*(k|m|g)?(b?(ytes?)?)/i', $size, $match)) {
  1149. return $match[1] * $suffixes[drupal_strtolower($match[2])];
  1150. }
  1151. }
  1152. /**
  1153. * Generate a string representation for the given byte count.
  1154. *
  1155. * @param $size
  1156. * A size in bytes.
  1157. * @param $langcode
  1158. * Optional language code to translate to a language other than what is used
  1159. * to display the page.
  1160. * @return
  1161. * A translated string representation of the size.
  1162. */
  1163. function format_size($size, $langcode = NULL) {
  1164. if ($size < 1024) {
  1165. return format_plural($size, '1 byte', '@count bytes', array(), $langcode);
  1166. }
  1167. else {
  1168. $size = round($size / 1024, 2);
  1169. $suffix = t('KB', array(), $langcode);
  1170. if ($size >= 1024) {
  1171. $size = round($size / 1024, 2);
  1172. $suffix = t('MB', array(), $langcode);
  1173. }
  1174. return t('@size @suffix', array('@size' => $size, '@suffix' => $suffix), $langcode);
  1175. }
  1176. }
  1177. /**
  1178. * Format a time interval with the requested granularity.
  1179. *
  1180. * @param $timestamp
  1181. * The length of the interval in seconds.
  1182. * @param $granularity
  1183. * How many different units to display in the string.
  1184. * @param $langcode
  1185. * Optional language code to translate to a language other than
  1186. * what is used to display the page.
  1187. * @return
  1188. * A translated string representation of the interval.
  1189. */
  1190. function format_interval($timestamp, $granularity = 2, $langcode = NULL) {
  1191. $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);
  1192. $output = '';
  1193. foreach ($units as $key => $value) {
  1194. $key = explode('|', $key);
  1195. if ($timestamp >= $value) {
  1196. $output .= ($output ? ' ' : '') . format_plural(floor($timestamp / $value), $key[0], $key[1], array(), $langcode);
  1197. $timestamp %= $value;
  1198. $granularity--;
  1199. }
  1200. if ($granularity == 0) {
  1201. break;
  1202. }
  1203. }
  1204. return $output ? $output : t('0 sec', array(), $langcode);
  1205. }
  1206. /**
  1207. * Format a date with the given configured format or a custom format string.
  1208. *
  1209. * Drupal allows administrators to select formatting strings for 'small',
  1210. * 'medium' and 'large' date formats. This function can handle these formats,
  1211. * as well as any custom format.
  1212. *
  1213. * @param $timestamp
  1214. * The exact date to format, as a UNIX timestamp.
  1215. * @param $type
  1216. * The format to use. Can be "small", "medium" or "large" for the preconfigured
  1217. * date formats. If "custom" is specified, then $format is required as well.
  1218. * @param $format
  1219. * A PHP date format string as required by date(). A backslash should be used
  1220. * before a character to avoid interpreting the character as part of a date
  1221. * format.
  1222. * @param $timezone
  1223. * Time zone offset in seconds; if omitted, the user's time zone is used.
  1224. * @param $langcode
  1225. * Optional language code to translate to a language other than what is used
  1226. * to display the page.
  1227. * @return
  1228. * A translated date string in the requested format.
  1229. */
  1230. function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
  1231. if (!isset($timezone)) {
  1232. global $user;
  1233. if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
  1234. $timezone = $user->timezone;
  1235. }
  1236. else {
  1237. $timezone = variable_get('date_default_timezone', 0);
  1238. }
  1239. }
  1240. $timestamp += $timezone;
  1241. switch ($type) {
  1242. case 'small':
  1243. $format = variable_get('date_format_short', 'm/d/Y - H:i');
  1244. break;
  1245. case 'large':
  1246. $format = variable_get('date_format_long', 'l, F j, Y - H:i');
  1247. break;
  1248. case 'custom':
  1249. // No change to format.
  1250. break;
  1251. case 'medium':
  1252. default:
  1253. $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
  1254. }
  1255. $max = strlen($format);
  1256. $date = '';
  1257. for ($i = 0; $i < $max; $i++) {
  1258. $c = $format[$i];
  1259. if (strpos('AaDlM', $c) !== FALSE) {
  1260. $date .= t(gmdate($c, $timestamp), array(), $langcode);
  1261. }
  1262. else if ($c == 'F') {
  1263. // Special treatment for long month names: May is both an abbreviation
  1264. // and a full month name in English, but other languages have
  1265. // different abbreviations.
  1266. $date .= trim(t('!long-month-name '. gmdate($c, $timestamp), array('!long-month-name' => ''), $langcode));
  1267. }
  1268. else if (strpos('BdgGhHiIjLmnsStTUwWYyz', $c) !== FALSE) {
  1269. $date .= gmdate($c, $timestamp);
  1270. }
  1271. else if ($c == 'r') {
  1272. $date .= format_date($timestamp - $timezone, 'custom', 'D, d M Y H:i:s O', $timezone, $langcode);
  1273. }
  1274. else if ($c == 'O') {
  1275. $date .= sprintf('%s%02d%02d', ($timezone < 0 ? '-' : '+'), abs($timezone / 3600), abs($timezone % 3600) / 60);
  1276. }
  1277. else if ($c == 'Z') {
  1278. $date .= $timezone;
  1279. }
  1280. else if ($c == '\\') {
  1281. $date .= $format[++$i];
  1282. }
  1283. else {
  1284. $date .= $c;
  1285. }
  1286. }
  1287. return $date;
  1288. }
  1289. /**
  1290. * @} End of "defgroup format".
  1291. */
  1292. /**
  1293. * Generates an internal or external URL.
  1294. *
  1295. * When creating links in modules, consider whether l() could be a better
  1296. * alternative than url().
  1297. *
  1298. * @param $path
  1299. * (optional) The internal path or external URL being linked to, such as
  1300. * "node/34" or "http://example.com/foo". The default value is equivalent to
  1301. * passing in '<front>'. A few notes:
  1302. * - If you provide a full URL, it will be considered an external URL.
  1303. * - If you provide only the path (e.g. "node/34"), it will be
  1304. * considered an internal link. In this case, it should be a system URL,
  1305. * and it will be replaced with the alias, if one exists. Additional query
  1306. * arguments for internal paths must be supplied in $options['query'], not
  1307. * included in $path.
  1308. * - If you provide an internal path and $options['alias'] is set to TRUE, the
  1309. * path is assumed already to be the correct path alias, and the alias is
  1310. * not looked up.
  1311. * - The special string '<front>' generates a link to the site's base URL.
  1312. * - If your external URL contains a query (e.g. http://example.com/foo?a=b),
  1313. * then you can either URL encode the query keys and values yourself and
  1314. * include them in $path, or use $options['query'] to let this function
  1315. * URL encode them.
  1316. * @param $options
  1317. * (optional) An associative array of additional options, with the following
  1318. * elements:
  1319. * - 'query': A URL-encoded query string to append to the link, or an array of
  1320. * query key/value-pairs without any URL-encoding.
  1321. * - 'fragment': A fragment identifier (named anchor) to append to the URL.
  1322. * Do not include the leading '#' character.
  1323. * - 'absolute' (default FALSE): Whether to force the output to be an absolute
  1324. * link (beginning with http:). Useful for links that will be displayed
  1325. * outside the site, such as in an RSS feed.
  1326. * - 'alias' (default FALSE): Whether the given path is a URL alias already.
  1327. * - 'external': Whether the given path is an external URL.
  1328. * - 'language': An optional language object. Used to build the URL to link
  1329. * to and look up the proper alias for the link.
  1330. * - 'base_url': Only used internally, to modify the base URL when a language
  1331. * dependent URL requires so.
  1332. * - 'prefix': Only used internally, to modify the path when a language
  1333. * dependent URL requires so.
  1334. *
  1335. * @return
  1336. * A string containing a URL to the given path.
  1337. */
  1338. function url($path = NULL, $options = array()) {
  1339. // Merge in defaults.
  1340. $options += array(
  1341. 'fragment' => '',
  1342. 'query' => '',
  1343. 'absolute' => FALSE,
  1344. 'alias' => FALSE,
  1345. 'prefix' => ''
  1346. );
  1347. if (!isset($options['external'])) {
  1348. // Return an external link if $path contains an allowed absolute URL.
  1349. // Only call the slow filter_xss_bad_protocol if $path contains a ':' before
  1350. // any / ? or #.
  1351. $colonpos = strpos($path, ':');
  1352. $options['external'] = ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && filter_xss_bad_protocol($path, FALSE) == check_plain($path));
  1353. }
  1354. // May need language dependent rewriting if language.inc is present.
  1355. if (function_exists('language_url_rewrite')) {
  1356. language_url_rewrite($path, $options);
  1357. }
  1358. if ($options['fragment']) {
  1359. $options['fragment'] = '#'. $options['fragment'];
  1360. }
  1361. if (is_array($options['query'])) {
  1362. $options['query'] = drupal_query_string_encode($options['query']);
  1363. }
  1364. if ($options['external']) {
  1365. // Split off the fragment.
  1366. if (strpos($path, '#') !== FALSE) {
  1367. list($path, $old_fragment) = explode('#', $path, 2);
  1368. if (isset($old_fragment) && !$options['fragment']) {
  1369. $options['fragment'] = '#'. $old_fragment;
  1370. }
  1371. }
  1372. // Append the query.
  1373. if ($options['query']) {
  1374. $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . $options['query'];
  1375. }
  1376. // Reassemble.
  1377. return $path . $options['fragment'];
  1378. }
  1379. global $base_url;
  1380. static $script;
  1381. if (!isset($script)) {
  1382. // On some web servers, such as IIS, we can't omit "index.php". So, we
  1383. // generate "index.php?q=foo" instead of "?q=foo" on anything that is not
  1384. // Apache.
  1385. $script = (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') === FALSE) ? 'index.php' : '';
  1386. }
  1387. if (!isset($options['base_url'])) {
  1388. // The base_url might be rewritten from the language rewrite in domain mode.
  1389. $options['base_url'] = $base_url;
  1390. }
  1391. // Preserve the original path before aliasing.
  1392. $original_path = $path;
  1393. // The special path '<front>' links to the default front page.
  1394. if ($path == '<front>') {
  1395. $path = '';
  1396. }
  1397. elseif (!empty($path) && !$options['alias']) {
  1398. $path = drupal_get_path_alias($path, isset($options['language']) ? $options['language']->language : '');
  1399. }
  1400. if (function_exists('custom_url_rewrite_outbound')) {
  1401. // Modules may alter outbound links by reference.
  1402. custom_url_rewrite_outbound($path, $options, $original_path);
  1403. }
  1404. $base = $options['absolute'] ? $options['base_url'] .'/' : base_path();
  1405. $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
  1406. $path = drupal_urlencode($prefix . $path);
  1407. if (variable_get('clean_url', '0')) {
  1408. // With Clean URLs.
  1409. if ($options['query']) {
  1410. return $base . $path .'?'. $options['query'] . $options['fragment'];
  1411. }
  1412. else {
  1413. return $base . $path . $options['fragment'];
  1414. }
  1415. }
  1416. else {
  1417. // Without Clean URLs.
  1418. $variables = array();
  1419. if (!empty($path)) {
  1420. $variables[] = 'q='. $path;
  1421. }
  1422. if (!empty($options['query'])) {
  1423. $variables[] = $options['query'];
  1424. }
  1425. if ($query = join('&', $variables)) {
  1426. return $base . $script .'?'. $query . $options['fragment'];
  1427. }
  1428. else {
  1429. return $base . $options['fragment'];
  1430. }
  1431. }
  1432. }
  1433. /**
  1434. * Format an attribute string to insert in a tag.
  1435. *
  1436. * @param $attributes
  1437. * An associative array of HTML attributes.
  1438. * @return
  1439. * An HTML string ready for insertion in a tag.
  1440. */
  1441. function drupal_attributes($attributes = array()) {
  1442. if (is_array($attributes)) {
  1443. $t = '';
  1444. foreach ($attributes as $key => $value) {
  1445. $t .= " $key=".'"'. check_plain($value) .'"';
  1446. }
  1447. return $t;
  1448. }
  1449. }
  1450. /**
  1451. * Formats an internal or external URL link as an HTML anchor tag.
  1452. *
  1453. * This function correctly handles aliased paths, and adds an 'active' class
  1454. * attribute to links that point to the current page (for theming), so all
  1455. * internal links output by modules should be generated by this function if
  1456. * possible.
  1457. *
  1458. * However, for links enclosed in translatable text you should use t() and
  1459. * embed the HTML anchor tag directly in the translated string. For example:
  1460. * @code
  1461. * t('Visit the <a href="@url">settings</a> page', array('@url' => url('admin')));
  1462. * @endcode
  1463. * This keeps the context of the link title ('settings' in the example) for
  1464. * translators.
  1465. *
  1466. * @param $text
  1467. * The link text for the anchor tag.
  1468. * @param $path
  1469. * The internal path or external URL being linked to, such as "node/34" or
  1470. * "http://example.com/foo". After the url() function is called to construct
  1471. * the URL from $path and $options, the resulting URL is passed through
  1472. * check_url() before it is inserted into the HTML anchor tag, to ensure
  1473. * well-formed HTML. See url() for more information and notes.
  1474. * @param $options
  1475. * An associative array of additional options, with the following elements:
  1476. * - 'attributes': An associative array of HTML attributes to apply to the
  1477. * anchor tag.
  1478. * - 'html' (default FALSE): Whether $text is HTML or just plain-text. For
  1479. * example, to make an image tag into a link, this must be set to TRUE, or
  1480. * you will see the escaped HTML image tag.
  1481. * - 'language': An optional language object. If the path being linked to is
  1482. * internal to the site, $options['language'] is used to look up the alias
  1483. * for the URL, and to determine whether the link is "active", or pointing
  1484. * to the current page (the language as well as the path must match).This
  1485. * element is also used by url().
  1486. * - Additional $options elements used by the url() function.
  1487. *
  1488. * @return
  1489. * An HTML string containing a link to the given path.
  1490. */
  1491. function l($text, $path, $options = array()) {
  1492. global $language;
  1493. // Merge in defaults.
  1494. $options += array(
  1495. 'attributes' => array(),
  1496. 'html' => FALSE,
  1497. );
  1498. // Append active class.
  1499. if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
  1500. (empty($options['language']) || $options['language']->language == $language->language)) {
  1501. if (isset($options['attributes']['class'])) {
  1502. $options['attributes']['class'] .= ' active';
  1503. }
  1504. else {
  1505. $options['attributes']['class'] = 'active';
  1506. }
  1507. }
  1508. // Remove all HTML and PHP tags from a tooltip. For best performance, we act only
  1509. // if a quick strpos() pre-check gave a suspicion (because strip_tags() is expensive).
  1510. if (isset($options['attributes']['title']) && strpos($options['attributes']['title'], '<') !== FALSE) {
  1511. $options['attributes']['title'] = strip_tags($options['attributes']['title']);
  1512. }
  1513. return '<a href="'. check_url(url($path, $options)) .'"'. drupal_attributes($options['attributes']) .'>'. ($options['html'] ? $text : check_plain($text)) .'</a>';
  1514. }
  1515. /**
  1516. * Perform end-of-request tasks.
  1517. *
  1518. * This function sets the page cache if appropriate, and allows modules to
  1519. * react to the closing of the page by calling hook_exit().
  1520. */
  1521. function drupal_page_footer() {
  1522. if (variable_get('cache', CACHE_DISABLED) != CACHE_DISABLED) {
  1523. page_set_cache();
  1524. }
  1525. module_invoke_all('exit');
  1526. }
  1527. /**
  1528. * Form an associative array from a linear array.
  1529. *
  1530. * This function walks through the provided array and constructs an associative
  1531. * array out of it. The keys of the resulting array will be the values of the
  1532. * input array. The values will be the same as the keys unless a function is
  1533. * specified, in which case the output of the function is used for the values
  1534. * instead.
  1535. *
  1536. * @param $array
  1537. * A linear array.
  1538. * @param $function
  1539. * A name of a function to apply to all values before output.
  1540. *
  1541. * @return
  1542. * An associative array.
  1543. */
  1544. function drupal_map_assoc($array, $function = NULL) {
  1545. if (!isset($function)) {
  1546. $result = array();
  1547. foreach ($array as $value) {
  1548. $result[$value] = $value;
  1549. }
  1550. return $result;
  1551. }
  1552. elseif (function_exists($function)) {
  1553. $result = array();
  1554. foreach ($array as $value) {
  1555. $result[$value] = $function($value);
  1556. }
  1557. return $result;
  1558. }
  1559. }
  1560. /**
  1561. * Evaluate a string of PHP code.
  1562. *
  1563. * This is a wrapper around PHP's eval(). It uses output buffering to capture both
  1564. * returned and printed text. Unlike eval(), we require code to be surrounded by
  1565. * <?php ?> tags; in other words, we evaluate the code as if it were a stand-alone
  1566. * PHP file.
  1567. *
  1568. * Using this wrapper also ensures that the PHP code which is evaluated can not
  1569. * overwrite any variables in the calling code, unlike a regular eval() call.
  1570. *
  1571. * @param $code
  1572. * The code to evaluate.
  1573. * @return
  1574. * A string containing the printed output of the code, followed by the returned
  1575. * output of the code.
  1576. */
  1577. function drupal_eval($code) {
  1578. global $theme_path, $theme_info, $conf;
  1579. // Store current theme path.
  1580. $old_theme_path = $theme_path;
  1581. // Restore theme_path to the theme, as long as drupal_eval() executes,
  1582. // so code evaluted will not see the caller module as the current theme.
  1583. // If theme info is not initialized get the path from theme_default.
  1584. if (!isset($theme_info)) {
  1585. $theme_path = drupal_get_path('theme', $conf['theme_default']);
  1586. }
  1587. else {
  1588. $theme_path = dirname($theme_info->filename);
  1589. }
  1590. ob_start();
  1591. print eval('?>'. $code);
  1592. $output = ob_get_contents();
  1593. ob_end_clean();
  1594. // Recover original theme path.
  1595. $theme_path = $old_theme_path;
  1596. return $output;
  1597. }
  1598. /**
  1599. * Returns the path to a system item (module, theme, etc.).
  1600. *
  1601. * @param $type
  1602. * The type of the item (i.e. theme, theme_engine, module, profile).
  1603. * @param $name
  1604. * The name of the item for which the path is requested.
  1605. *
  1606. * @return
  1607. * The path to the requested item.
  1608. */
  1609. function drupal_get_path($type, $name) {
  1610. return dirname(drupal_get_filename($type, $name));
  1611. }
  1612. /**
  1613. * Returns the base URL path of the Drupal installation.
  1614. * At the very least, this will always default to /.
  1615. */
  1616. function base_path() {
  1617. return $GLOBALS['base_path'];
  1618. }
  1619. /**
  1620. * Provide a substitute clone() function for PHP4.
  1621. */
  1622. function drupal_clone($object) {
  1623. return version_compare(phpversion(), '5.0') < 0 ? $object : clone($object);
  1624. }
  1625. /**
  1626. * Add a <link> tag to the page's HEAD.
  1627. */
  1628. function drupal_add_link($attributes) {
  1629. drupal_set_html_head('<link'. drupal_attributes($attributes) .' />');
  1630. }
  1631. /**
  1632. * Adds a CSS file to the stylesheet queue.
  1633. *
  1634. * @param $path
  1635. * (optional) The path to the CSS file relative to the base_path(), e.g.,
  1636. * modules/devel/devel.css.
  1637. *
  1638. * Modules should always prefix the names of their CSS files with the module
  1639. * name, for example: system-menus.css rather than simply menus.css. Themes
  1640. * can override module-supplied CSS files based on their filenames, and this
  1641. * prefixing helps prevent confusing name collisions for theme developers.
  1642. * See drupal_get_css where the overrides are performed.
  1643. *
  1644. * If the direction of the current language is right-to-left (Hebrew,
  1645. * Arabic, etc.), the function will also look for an RTL CSS file and append
  1646. * it to the list. The name of this file should have an '-rtl.css' suffix.
  1647. * For example a CSS file called 'name.css' will have a 'name-rtl.css'
  1648. * file added to the list, if exists in the same directory. This CSS file
  1649. * should contain overrides for properties which should be reversed or
  1650. * otherwise different in a right-to-left display.
  1651. * @param $type
  1652. * (optional) The type of stylesheet that is being added. Types are: module
  1653. * or theme.
  1654. * @param $media
  1655. * (optional) The media type for the stylesheet, e.g., all, print, screen.
  1656. * @param $preprocess
  1657. * (optional) Should this CSS file be aggregated and compressed if this
  1658. * feature has been turned on under the performance section?
  1659. *
  1660. * What does this actually mean?
  1661. * CSS preprocessing is the process of aggregating a bunch of separate CSS
  1662. * files into one file that is then compressed by removing all extraneous
  1663. * white space.
  1664. *
  1665. * The reason for merging the CSS files is outlined quite thoroughly here:
  1666. * http://www.die.net/musings/page_load_time/
  1667. * "Load fewer external objects. Due to request overhead, one bigger file
  1668. * just loads faster than two smaller ones half its size."
  1669. *
  1670. * However, you should *not* preprocess every file as this can lead to
  1671. * redundant caches. You should set $preprocess = FALSE when:
  1672. *
  1673. * - Your styles are only used rarely on the site. This could be a special
  1674. * admin page, the homepage, or a handful of pages that does not represent
  1675. * the majority of the pages on your site.
  1676. *
  1677. * Typical candidates for caching are for example styles for nodes across
  1678. * the site, or used in the theme.
  1679. *
  1680. * @return
  1681. * An array of CSS files.
  1682. *
  1683. * @see drupal_get_css()
  1684. */
  1685. function drupal_add_css($path = NULL, $type = 'module', $media = 'all', $preprocess = TRUE) {
  1686. static $css = array();
  1687. global $language;
  1688. // Create an array of CSS files for each media type first, since each type needs to be served
  1689. // to the browser differently.
  1690. if (isset($path)) {
  1691. // This check is necessary to ensure proper cascading of styles and is faster than an asort().
  1692. if (!isset($css[$media])) {
  1693. $css[$media] = array('module' => array(), 'theme' => array());
  1694. }
  1695. $css[$media][$type][$path] = $preprocess;
  1696. // If the current language is RTL, add the CSS file with RTL overrides.
  1697. if ($language->direction == LANGUAGE_RTL) {
  1698. $rtl_path = str_replace('.css', '-rtl.css', $path);
  1699. if (file_exists($rtl_path)) {
  1700. $css[$media][$type][$rtl_path] = $preprocess;
  1701. }
  1702. }
  1703. }
  1704. return $css;
  1705. }
  1706. /**
  1707. * Returns a themed representation of all stylesheets that should be attached to the page.
  1708. *
  1709. * It loads the CSS in order, with 'module' first, then 'theme' afterwards.
  1710. * This ensures proper cascading of styles so themes can easily override
  1711. * module styles through CSS selectors.
  1712. *
  1713. * Themes may replace module-defined CSS files by adding a stylesheet with the
  1714. * same filename. For example, themes/garland/system-menus.css would replace
  1715. * modules/system/system-menus.css. This allows themes to override complete
  1716. * CSS files, rather than specific selectors, when necessary.
  1717. *
  1718. * If the original CSS file is being overridden by a theme, the theme is
  1719. * responsible for supplying an accompanying RTL CSS file to replace the
  1720. * module's.
  1721. *
  1722. * @param $css
  1723. * (optional) An array of CSS files. If no array is provided, the default
  1724. * stylesheets array is used instead.
  1725. *
  1726. * @return
  1727. * A string of XHTML CSS tags.
  1728. *
  1729. * @see drupal_add_css()
  1730. */
  1731. function drupal_get_css($css = NULL) {
  1732. $output = '';
  1733. if (!isset($css)) {
  1734. $css = drupal_add_css();
  1735. }
  1736. $no_module_preprocess = '';
  1737. $no_theme_preprocess = '';
  1738. $preprocess_css = (variable_get('preprocess_css', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
  1739. $directory = file_directory_path();
  1740. $is_writable = is_dir($directory) && is_writable($directory) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC);
  1741. // A dummy query-string is added to filenames, to gain control over
  1742. // browser-caching. The string changes on every update or full cache
  1743. // flush, forcing browsers to load a new copy of the files, as the
  1744. // URL changed.
  1745. $query_string = '?'. substr(variable_get('css_js_query_string', '0'), 0, 1);
  1746. foreach ($css as $media => $types) {
  1747. // If CSS preprocessing is off, we still need to output the styles.
  1748. // Additionally, go through any remaining styles if CSS preprocessing is on and output the non-cached ones.
  1749. foreach ($types as $type => $files) {
  1750. if ($type == 'module') {
  1751. // Setup theme overrides for module styles.
  1752. $theme_styles = array();
  1753. foreach (array_keys($css[$media]['theme']) as $theme_style) {
  1754. $theme_styles[] = basename($theme_style);
  1755. }
  1756. }
  1757. foreach ($types[$type] as $file => $preprocess) {
  1758. // If the theme supplies its own style using the name of the module style, skip its inclusion.
  1759. // This includes any RTL styles associated with its main LTR counterpart.
  1760. if ($type == 'module' && in_array(str_replace('-rtl.css', '.css', basename($file)), $theme_styles)) {
  1761. // Unset the file to prevent its inclusion when CSS aggregation is enabled.
  1762. unset($types[$type][$file]);
  1763. continue;
  1764. }
  1765. // Only include the stylesheet if it exists.
  1766. if (file_exists($file)) {
  1767. if (!$preprocess || !($is_writable && $preprocess_css)) {
  1768. // If a CSS file is not to be preprocessed and it's a module CSS file, it needs to *always* appear at the *top*,
  1769. // regardless of whether preprocessing is on or off.
  1770. if (!$preprocess && $type == 'module') {
  1771. $no_module_preprocess .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. base_path() . $file . $query_string .'" />'."\n";
  1772. }
  1773. // If a CSS file is not to be preprocessed and it's a theme CSS file, it needs to *always* appear at the *bottom*,
  1774. // regardless of whether preprocessing is on or off.
  1775. else if (!$preprocess && $type == 'theme') {
  1776. $no_theme_preprocess .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. base_path() . $file . $query_string .'" />'."\n";
  1777. }
  1778. else {
  1779. $output .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. base_path() . $file . $query_string .'" />'."\n";
  1780. }
  1781. }
  1782. }
  1783. }
  1784. }
  1785. if ($is_writable && $preprocess_css) {
  1786. // Prefix filename to prevent blocking by firewalls which reject files
  1787. // starting with "ad*".
  1788. $filename = 'css_'. md5(serialize($types) . $query_string) .'.css';
  1789. $preprocess_file = drupal_build_css_cache($types, $filename);
  1790. $output .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. base_path() . $preprocess_file .'" />'."\n";
  1791. }
  1792. }
  1793. return $no_module_preprocess . $output . $no_theme_preprocess;
  1794. }
  1795. /**
  1796. * Aggregate and optimize CSS files, putting them in the files directory.
  1797. *
  1798. * @param $types
  1799. * An array of types of CSS files (e.g., screen, print) to aggregate and
  1800. * compress into one file.
  1801. * @param $filename
  1802. * The name of the aggregate CSS file.
  1803. * @return
  1804. * The name of the CSS file.
  1805. */
  1806. function drupal_build_css_cache($types, $filename) {
  1807. $data = '';
  1808. // Create the css/ within the files folder.
  1809. $csspath = file_create_path('css');
  1810. file_check_directory($csspath, FILE_CREATE_DIRECTORY);
  1811. if (!file_exists($csspath .'/'. $filename)) {
  1812. // Build aggregate CSS file.
  1813. foreach ($types as $type) {
  1814. foreach ($type as $file => $cache) {
  1815. if ($cache) {
  1816. $contents = drupal_load_stylesheet($file, TRUE);
  1817. // Return the path to where this CSS file originated from.
  1818. $base = base_path() . dirname($file) .'/';
  1819. _drupal_build_css_path(NULL, $base);
  1820. // Prefix all paths within this CSS file, ignoring external and absolute paths.
  1821. $data .= preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', '_drupal_build_css_path', $contents);
  1822. }
  1823. }
  1824. }
  1825. // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
  1826. // @import rules must proceed any other style, so we move those to the top.
  1827. $regexp = '/@import[^;]+;/i';
  1828. preg_match_all($regexp, $data, $matches);
  1829. $data = preg_replace($regexp, '', $data);
  1830. $data = implode('', $matches[0]) . $data;
  1831. // Create the CSS file.
  1832. file_save_data($data, $csspath .'/'. $filename, FILE_EXISTS_REPLACE);
  1833. }
  1834. return $csspath .'/'. $filename;
  1835. }
  1836. /**
  1837. * Helper function for drupal_build_css_cache().
  1838. *
  1839. * This function will prefix all paths within a CSS file.
  1840. */
  1841. function _drupal_build_css_path($matches, $base = NULL) {
  1842. static $_base;
  1843. // Store base path for preg_replace_callback.
  1844. if (isset($base)) {
  1845. $_base = $base;
  1846. }
  1847. // Prefix with base and remove '../' segments where possible.
  1848. $path = $_base . $matches[1];
  1849. $last = '';
  1850. while ($path != $last) {
  1851. $last = $path;
  1852. $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
  1853. }
  1854. return 'url('. $path .')';
  1855. }
  1856. /**
  1857. * Loads the stylesheet and resolves all @import commands.
  1858. *
  1859. * Loads a stylesheet and replaces @import commands with the contents of the
  1860. * imported file. Use this instead of file_get_contents when processing
  1861. * stylesheets.
  1862. *
  1863. * The returned contents are compressed removing white space and comments only
  1864. * when CSS aggregation is enabled. This optimization will not apply for
  1865. * color.module enabled themes with CSS aggregation turned off.
  1866. *
  1867. * @param $file
  1868. * Name of the stylesheet to be processed.
  1869. * @param $optimize
  1870. * Defines if CSS contents should be compressed or not.
  1871. * @return
  1872. * Contents of the stylesheet including the imported stylesheets.
  1873. */
  1874. function drupal_load_stylesheet($file, $optimize = NULL) {
  1875. static $_optimize;
  1876. // Store optimization parameter for preg_replace_callback with nested @import loops.
  1877. if (isset($optimize)) {
  1878. $_optimize = $optimize;
  1879. }
  1880. $contents = '';
  1881. if (file_exists($file)) {
  1882. // Load the local CSS stylesheet.
  1883. $contents = file_get_contents($file);
  1884. // Change to the current stylesheet's directory.
  1885. $cwd = getcwd();
  1886. chdir(dirname($file));
  1887. // Replaces @import commands with the actual stylesheet content.
  1888. // This happens recursively but omits external files.
  1889. $contents = preg_replace_callback('/@import\s*(?:url\()?[\'"]?(?![a-z]+:)([^\'"\()]+)[\'"]?\)?;/', '_drupal_load_stylesheet', $contents);
  1890. // Remove multiple charset declarations for standards compliance (and fixing Safari problems).
  1891. $contents = preg_replace('/^@charset\s+[\'"](\S*)\b[\'"];/i', '', $contents);
  1892. if ($_optimize) {
  1893. // Perform some safe CSS optimizations.
  1894. // Regexp to match comment blocks.
  1895. $comment = '/\*[^*]*\*+(?:[^/*][^*]*\*+)*/';
  1896. // Regexp to match double quoted strings.
  1897. $double_quot = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
  1898. // Regexp to match single quoted strings.
  1899. $single_quot = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'";
  1900. $contents = preg_replace_callback(
  1901. "<$double_quot|$single_quot|$comment>Ss", // Match all comment blocks along
  1902. "_process_comment", // with double/single quoted strings
  1903. $contents); // and feed them to _process_comment().
  1904. $contents = preg_replace(
  1905. '<\s*([@{}:;,]|\)\s|\s\()\s*>S', // Remove whitespace around separators,
  1906. '\1', $contents); // but keep space around parentheses.
  1907. // End the file with a new line.
  1908. $contents .= "\n";
  1909. }
  1910. // Change back directory.
  1911. chdir($cwd);
  1912. }
  1913. return $contents;
  1914. }
  1915. /**
  1916. * Process comment blocks.
  1917. *
  1918. * This is the callback function for the preg_replace_callback()
  1919. * used in drupal_load_stylesheet_content(). Support for comment
  1920. * hacks is implemented here.
  1921. */
  1922. function _process_comment($matches) {
  1923. static $keep_nextone = FALSE;
  1924. // Quoted string, keep it.
  1925. if ($matches[0][0] == "'" || $matches[0][0] == '"') {
  1926. return $matches[0];
  1927. }
  1928. // End of IE-Mac hack, keep it.
  1929. if ($keep_nextone) {
  1930. $keep_nextone = FALSE;
  1931. return $matches[0];
  1932. }
  1933. switch (strrpos($matches[0], '\\')) {
  1934. case FALSE :
  1935. // No backslash, strip it.
  1936. return '';
  1937. case drupal_strlen($matches[0])-3 :
  1938. // Ends with \*/ so is a multi line IE-Mac hack, keep the next one also.
  1939. $keep_nextone = TRUE;
  1940. return '/*_\*/';
  1941. default :
  1942. // Single line IE-Mac hack.
  1943. return '/*\_*/';
  1944. }
  1945. }
  1946. /**
  1947. * Loads stylesheets recursively and returns contents with corrected paths.
  1948. *
  1949. * This function is used for recursive loading of stylesheets and
  1950. * returns the stylesheet content with all url() paths corrected.
  1951. */
  1952. function _drupal_load_stylesheet($matches) {
  1953. $filename = $matches[1];
  1954. // Load the imported stylesheet and replace @import commands in there as well.
  1955. $file = drupal_load_stylesheet($filename);
  1956. // Determine the file's directory.
  1957. $directory = dirname($filename);
  1958. // If the file is in the current directory, make sure '.' doesn't appear in
  1959. // the url() path.
  1960. $directory = $directory == '.' ? '' : $directory .'/';
  1961. // Alter all internal url() paths. Leave external paths alone. We don't need
  1962. // to normalize absolute paths here (i.e. remove folder/... segments) because
  1963. // that will be done later.
  1964. return preg_replace('/url\s*\(([\'"]?)(?![a-z]+:|\/+)/i', 'url(\1'. $directory, $file);
  1965. }
  1966. /**
  1967. * Delete all cached CSS files.
  1968. */
  1969. function drupal_clear_css_cache() {
  1970. file_scan_directory(file_create_path('css'), '.*', array('.', '..', 'CVS'), 'file_delete', TRUE);
  1971. }
  1972. /**
  1973. * Add a JavaScript file, setting or inline code to the page.
  1974. *
  1975. * The behavior of this function depends on the parameters it is called with.
  1976. * Generally, it handles the addition of JavaScript to the page, either as
  1977. * reference to an existing file or as inline code. The following actions can be
  1978. * performed using this function:
  1979. *
  1980. * - Add a file ('core', 'module' and 'theme'):
  1981. * Adds a reference to a JavaScript file to the page. JavaScript files
  1982. * are placed in a certain order, from 'core' first, to 'module' and finally
  1983. * 'theme' so that files, that are added later, can override previously added
  1984. * files with ease.
  1985. *
  1986. * - Add inline JavaScript code ('inline'):
  1987. * Executes a piece of JavaScript code on the current page by placing the code
  1988. * directly in the page. This can, for example, be useful to tell the user that
  1989. * a new message arrived, by opening a pop up, alert box etc.
  1990. *
  1991. * - Add settings ('setting'):
  1992. * Adds a setting to Drupal's global storage of JavaScript settings. Per-page
  1993. * settings are required by some modules to function properly. The settings
  1994. * will be accessible at Drupal.settings.
  1995. *
  1996. * @param $data
  1997. * (optional) If given, the value depends on the $type parameter:
  1998. * - 'core', 'module' or 'theme': Path to the file relative to base_path().
  1999. * - 'inline': The JavaScript code that should be placed in the given scope.
  2000. * - 'setting': An array with configuration options as associative array. The
  2001. * array is directly placed in Drupal.settings. You might want to wrap your
  2002. * actual configuration settings in another variable to prevent the pollution
  2003. * of the Drupal.settings namespace.
  2004. * @param $type
  2005. * (optional) The type of JavaScript that should be added to the page. Allowed
  2006. * values are 'core', 'module', 'theme', 'inline' and 'setting'. You
  2007. * can, however, specify any value. It is treated as a reference to a JavaScript
  2008. * file. Defaults to 'module'.
  2009. * @param $scope
  2010. * (optional) The location in which you want to place the script. Possible
  2011. * values are 'header' and 'footer' by default. If your theme implements
  2012. * different locations, however, you can also use these.
  2013. * @param $defer
  2014. * (optional) If set to TRUE, the defer attribute is set on the <script> tag.
  2015. * Defaults to FALSE. This parameter is not used with $type == 'setting'.
  2016. * @param $cache
  2017. * (optional) If set to FALSE, the JavaScript file is loaded anew on every page
  2018. * call, that means, it is not cached. Defaults to TRUE. Used only when $type
  2019. * references a JavaScript file.
  2020. * @param $preprocess
  2021. * (optional) Should this JS file be aggregated if this
  2022. * feature has been turned on under the performance section?
  2023. * @return
  2024. * If the first parameter is NULL, the JavaScript array that has been built so
  2025. * far for $scope is returned. If the first three parameters are NULL,
  2026. * an array with all scopes is returned.
  2027. */
  2028. function drupal_add_js($data = NULL, $type = 'module', $scope = 'header', $defer = FALSE, $cache = TRUE, $preprocess = TRUE) {
  2029. static $javascript = array();
  2030. if (isset($data)) {
  2031. // Add jquery.js and drupal.js, as well as the basePath setting, the
  2032. // first time a Javascript file is added.
  2033. if (empty($javascript)) {
  2034. $javascript['header'] = array(
  2035. 'core' => array(
  2036. 'misc/jquery.js' => array('cache' => TRUE, 'defer' => FALSE, 'preprocess' => TRUE),
  2037. 'misc/drupal.js' => array('cache' => TRUE, 'defer' => FALSE, 'preprocess' => TRUE),
  2038. ),
  2039. 'module' => array(),
  2040. 'theme' => array(),
  2041. 'setting' => array(
  2042. array('basePath' => base_path()),
  2043. ),
  2044. 'inline' => array(),
  2045. );
  2046. }
  2047. if (isset($scope) && !isset($javascript[$scope])) {
  2048. $javascript[$scope] = array('core' => array(), 'module' => array(), 'theme' => array(), 'setting' => array(), 'inline' => array());
  2049. }
  2050. if (isset($type) && isset($scope) && !isset($javascript[$scope][$type])) {
  2051. $javascript[$scope][$type] = array();
  2052. }
  2053. switch ($type) {
  2054. case 'setting':
  2055. $javascript[$scope][$type][] = $data;
  2056. break;
  2057. case 'inline':
  2058. $javascript[$scope][$type][] = array('code' => $data, 'defer' => $defer);
  2059. break;
  2060. default:
  2061. // If cache is FALSE, don't preprocess the JS file.
  2062. $javascript[$scope][$type][$data] = array('cache' => $cache, 'defer' => $defer, 'preprocess' => (!$cache ? FALSE : $preprocess));
  2063. }
  2064. }
  2065. if (isset($scope)) {
  2066. if (isset($javascript[$scope])) {
  2067. return $javascript[$scope];
  2068. }
  2069. else {
  2070. return array();
  2071. }
  2072. }
  2073. else {
  2074. return $javascript;
  2075. }
  2076. }
  2077. /**
  2078. * Returns a themed presentation of all JavaScript code for the current page.
  2079. *
  2080. * References to JavaScript files are placed in a certain order: first, all
  2081. * 'core' files, then all 'module' and finally all 'theme' JavaScript files
  2082. * are added to the page. Then, all settings are output, followed by 'inline'
  2083. * JavaScript code. If running update.php, all preprocessing is disabled.
  2084. *
  2085. * @param $scope
  2086. * (optional) The scope for which the JavaScript rules should be returned.
  2087. * Defaults to 'header'.
  2088. * @param $javascript
  2089. * (optional) An array with all JavaScript code. Defaults to the default
  2090. * JavaScript array for the given scope.
  2091. * @return
  2092. * All JavaScript code segments and includes for the scope as HTML tags.
  2093. */
  2094. function drupal_get_js($scope = 'header', $javascript = NULL) {
  2095. if ((!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') && function_exists('locale_update_js_files')) {
  2096. locale_update_js_files();
  2097. }
  2098. if (!isset($javascript)) {
  2099. $javascript = drupal_add_js(NULL, NULL, $scope);
  2100. }
  2101. if (empty($javascript)) {
  2102. return '';
  2103. }
  2104. $output = '';
  2105. $preprocessed = '';
  2106. $no_preprocess = array('core' => '', 'module' => '', 'theme' => '');
  2107. $files = array();
  2108. $preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
  2109. $directory = file_directory_path();
  2110. $is_writable = is_dir($directory) && is_writable($directory) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC);
  2111. // A dummy query-string is added to filenames, to gain control over
  2112. // browser-caching. The string changes on every update or full cache
  2113. // flush, forcing browsers to load a new copy of the files, as the
  2114. // URL changed. Files that should not be cached (see drupal_add_js())
  2115. // get time() as query-string instead, to enforce reload on every
  2116. // page request.
  2117. $query_string = '?'. substr(variable_get('css_js_query_string', '0'), 0, 1);
  2118. // For inline Javascript to validate as XHTML, all Javascript containing
  2119. // XHTML needs to be wrapped in CDATA. To make that backwards compatible
  2120. // with HTML 4, we need to comment out the CDATA-tag.
  2121. $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
  2122. $embed_suffix = "\n//--><!]]>\n";
  2123. foreach ($javascript as $type => $data) {
  2124. if (!$data) continue;
  2125. switch ($type) {
  2126. case 'setting':
  2127. $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";
  2128. break;
  2129. case 'inline':
  2130. foreach ($data as $info) {
  2131. $output .= '<script type="text/javascript"' . ($info['defer'] ? ' defer="defer"' : '') . '>' . $embed_prefix . $info['code'] . $embed_suffix . "</script>\n";
  2132. }
  2133. break;
  2134. default:
  2135. // If JS preprocessing is off, we still need to output the scripts.
  2136. // Additionally, go through any remaining scripts if JS preprocessing is on and output the non-cached ones.
  2137. foreach ($data as $path => $info) {
  2138. if (!$info['preprocess'] || !$is_writable || !$preprocess_js) {
  2139. $no_preprocess[$type] .= '<script type="text/javascript"'. ($info['defer'] ? ' defer="defer"' : '') .' src="'. base_path() . $path . ($info['cache'] ? $query_string : '?'. time()) ."\"></script>\n";
  2140. }
  2141. else {
  2142. $files[$path] = $info;
  2143. }
  2144. }
  2145. }
  2146. }
  2147. // Aggregate any remaining JS files that haven't already been output.
  2148. if ($is_writable && $preprocess_js && count($files) > 0) {
  2149. // Prefix filename to prevent blocking by firewalls which reject files
  2150. // starting with "ad*".
  2151. $filename = 'js_'. md5(serialize($files) . $query_string) .'.js';
  2152. $preprocess_file = drupal_build_js_cache($files, $filename);
  2153. $preprocessed .= '<script type="text/javascript" src="'. base_path() . $preprocess_file .'"></script>'."\n";
  2154. }
  2155. // Keep the order of JS files consistent as some are preprocessed and others are not.
  2156. // Make sure any inline or JS setting variables appear last after libraries have loaded.
  2157. $output = $preprocessed . implode('', $no_preprocess) . $output;
  2158. return $output;
  2159. }
  2160. /**
  2161. * Assist in adding the tableDrag JavaScript behavior to a themed table.
  2162. *
  2163. * Draggable tables should be used wherever an outline or list of sortable items
  2164. * needs to be arranged by an end-user. Draggable tables are very flexible and
  2165. * can manipulate the value of form elements placed within individual columns.
  2166. *
  2167. * To set up a table to use drag and drop in place of weight select-lists or
  2168. * in place of a form that contains parent relationships, the form must be
  2169. * themed into a table. The table must have an id attribute set. If using
  2170. * theme_table(), the id may be set as such:
  2171. * @code
  2172. * $output = theme('table', $header, $rows, array('id' => 'my-module-table'));
  2173. * return $output;
  2174. * @endcode
  2175. *
  2176. * In the theme function for the form, a special class must be added to each
  2177. * form element within the same column, "grouping" them together.
  2178. *
  2179. * In a situation where a single weight column is being sorted in the table, the
  2180. * classes could be added like this (in the theme function):
  2181. * @code
  2182. * $form['my_elements'][$delta]['weight']['#attributes']['class'] = "my-elements-weight";
  2183. * @endcode
  2184. *
  2185. * Each row of the table must also have a class of "draggable" in order to enable the
  2186. * drag handles:
  2187. * @code
  2188. * $row = array(...);
  2189. * $rows[] = array(
  2190. * 'data' => $row,
  2191. * 'class' => 'draggable',
  2192. * );
  2193. * @endcode
  2194. *
  2195. * When tree relationships are present, the two additional classes
  2196. * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
  2197. * - Rows with the 'tabledrag-leaf' class cannot have child rows.
  2198. * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
  2199. *
  2200. * Calling drupal_add_tabledrag() would then be written as such:
  2201. * @code
  2202. * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
  2203. * @endcode
  2204. *
  2205. * In a more complex case where there are several groups in one column (such as
  2206. * the block regions on the admin/build/block page), a separate subgroup class
  2207. * must also be added to differentiate the groups.
  2208. * @code
  2209. * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = "my-elements-weight my-elements-weight-". $region;
  2210. * @endcode
  2211. *
  2212. * $group is still 'my-element-weight', and the additional $subgroup variable
  2213. * will be passed in as 'my-elements-weight-'. $region. This also means that
  2214. * you'll need to call drupal_add_tabledrag() once for every region added.
  2215. *
  2216. * @code
  2217. * foreach ($regions as $region) {
  2218. * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight', 'my-elements-weight-'. $region);
  2219. * }
  2220. * @endcode
  2221. *
  2222. * In a situation where tree relationships are present, adding multiple
  2223. * subgroups is not necessary, because the table will contain indentations that
  2224. * provide enough information about the sibling and parent relationships.
  2225. * See theme_menu_overview_form() for an example creating a table containing
  2226. * parent relationships.
  2227. *
  2228. * Please note that this function should be called from the theme layer, such as
  2229. * in a .tpl.php file, theme_ function, or in a template_preprocess function,
  2230. * not in a form declartion. Though the same JavaScript could be added to the
  2231. * page using drupal_add_js() directly, this function helps keep template files
  2232. * clean and readable. It also prevents tabledrag.js from being added twice
  2233. * accidentally.
  2234. *
  2235. * @param $table_id
  2236. * String containing the target table's id attribute. If the table does not
  2237. * have an id, one will need to be set, such as <table id="my-module-table">.
  2238. * @param $action
  2239. * String describing the action to be done on the form item. Either 'match'
  2240. * 'depth', or 'order'. Match is typically used for parent relationships.
  2241. * Order is typically used to set weights on other form elements with the same
  2242. * group. Depth updates the target element with the current indentation.
  2243. * @param $relationship
  2244. * String describing where the $action variable should be performed. Either
  2245. * 'parent', 'sibling', 'group', or 'self'. Parent will only look for fields
  2246. * up the tree. Sibling will look for fields in the same group in rows above
  2247. * and below it. Self affects the dragged row itself. Group affects the
  2248. * dragged row, plus any children below it (the entire dragged group).
  2249. * @param $group
  2250. * A class name applied on all related form elements for this action.
  2251. * @param $subgroup
  2252. * (optional) If the group has several subgroups within it, this string should
  2253. * contain the class name identifying fields in the same subgroup.
  2254. * @param $source
  2255. * (optional) If the $action is 'match', this string should contain the class
  2256. * name identifying what field will be used as the source value when matching
  2257. * the value in $subgroup.
  2258. * @param $hidden
  2259. * (optional) The column containing the field elements may be entirely hidden
  2260. * from view dynamically when the JavaScript is loaded. Set to FALSE if the
  2261. * column should not be hidden.
  2262. * @param $limit
  2263. * (optional) Limit the maximum amount of parenting in this table.
  2264. * @see block-admin-display-form.tpl.php
  2265. * @see theme_menu_overview_form()
  2266. */
  2267. function drupal_add_tabledrag($table_id, $action, $relationship, $group, $subgroup = NULL, $source = NULL, $hidden = TRUE, $limit = 0) {
  2268. static $js_added = FALSE;
  2269. if (!$js_added) {
  2270. drupal_add_js('misc/tabledrag.js', 'core');
  2271. $js_added = TRUE;
  2272. }
  2273. // If a subgroup or source isn't set, assume it is the same as the group.
  2274. $target = isset($subgroup) ? $subgroup : $group;
  2275. $source = isset($source) ? $source : $target;
  2276. $settings['tableDrag'][$table_id][$group][] = array(
  2277. 'target' => $target,
  2278. 'source' => $source,
  2279. 'relationship' => $relationship,
  2280. 'action' => $action,
  2281. 'hidden' => $hidden,
  2282. 'limit' => $limit,
  2283. );
  2284. drupal_add_js($settings, 'setting');
  2285. }
  2286. /**
  2287. * Aggregate JS files, putting them in the files directory.
  2288. *
  2289. * @param $files
  2290. * An array of JS files to aggregate and compress into one file.
  2291. * @param $filename
  2292. * The name of the aggregate JS file.
  2293. * @return
  2294. * The name of the JS file.
  2295. */
  2296. function drupal_build_js_cache($files, $filename) {
  2297. $contents = '';
  2298. // Create the js/ within the files folder.
  2299. $jspath = file_create_path('js');
  2300. file_check_directory($jspath, FILE_CREATE_DIRECTORY);
  2301. if (!file_exists($jspath .'/'. $filename)) {
  2302. // Build aggregate JS file.
  2303. foreach ($files as $path => $info) {
  2304. if ($info['preprocess']) {
  2305. // Append a ';' and a newline after each JS file to prevent them from running together.
  2306. $contents .= file_get_contents($path) .";\n";
  2307. }
  2308. }
  2309. // Create the JS file.
  2310. file_save_data($contents, $jspath .'/'. $filename, FILE_EXISTS_REPLACE);
  2311. }
  2312. return $jspath .'/'. $filename;
  2313. }
  2314. /**
  2315. * Delete all cached JS files.
  2316. */
  2317. function drupal_clear_js_cache() {
  2318. file_scan_directory(file_create_path('js'), '.*', array('.', '..', 'CVS'), 'file_delete', TRUE);
  2319. variable_set('javascript_parsed', array());
  2320. }
  2321. /**
  2322. * Converts a PHP variable into its Javascript equivalent.
  2323. *
  2324. * We use HTML-safe strings, i.e. with <, > and & escaped.
  2325. */
  2326. function drupal_to_js($var) {
  2327. switch (gettype($var)) {
  2328. case 'boolean':
  2329. return $var ? 'true' : 'false'; // Lowercase necessary!
  2330. case 'integer':
  2331. case 'double':
  2332. return $var;
  2333. case 'resource':
  2334. case 'string':
  2335. return '"'. str_replace(array("\r", "\n", "<", ">", "&"),
  2336. array('\r', '\n', '\x3c', '\x3e', '\x26'),
  2337. addslashes($var)) .'"';
  2338. case 'array':
  2339. // Arrays in JSON can't be associative. If the array is empty or if it
  2340. // has sequential whole number keys starting with 0, it's not associative
  2341. // so we can go ahead and convert it as an array.
  2342. if (empty ($var) || array_keys($var) === range(0, sizeof($var) - 1)) {
  2343. $output = array();
  2344. foreach ($var as $v) {
  2345. $output[] = drupal_to_js($v);
  2346. }
  2347. return '[ '. implode(', ', $output) .' ]';
  2348. }
  2349. // Otherwise, fall through to convert the array as an object.
  2350. case 'object':
  2351. $output = array();
  2352. foreach ($var as $k => $v) {
  2353. $output[] = drupal_to_js(strval($k)) .': '. drupal_to_js($v);
  2354. }
  2355. return '{ '. implode(', ', $output) .' }';
  2356. default:
  2357. return 'null';
  2358. }
  2359. }
  2360. /**
  2361. * Return data in JSON format.
  2362. *
  2363. * This function should be used for JavaScript callback functions returning
  2364. * data in JSON format. It sets the header for JavaScript output.
  2365. *
  2366. * @param $var
  2367. * (optional) If set, the variable will be converted to JSON and output.
  2368. */
  2369. function drupal_json($var = NULL) {
  2370. // We are returning JSON, so tell the browser.
  2371. drupal_set_header('Content-Type: application/json');
  2372. if (isset($var)) {
  2373. echo drupal_to_js($var);
  2374. }
  2375. }
  2376. /**
  2377. * Wrapper around urlencode() which avoids Apache quirks.
  2378. *
  2379. * Should be used when placing arbitrary data in an URL. Note that Drupal paths
  2380. * are urlencoded() when passed through url() and do not require urlencoding()
  2381. * of individual components.
  2382. *
  2383. * Notes:
  2384. * - For esthetic reasons, we do not escape slashes. This also avoids a 'feature'
  2385. * in Apache where it 404s on any path containing '%2F'.
  2386. * - mod_rewrite unescapes %-encoded ampersands, hashes, and slashes when clean
  2387. * URLs are used, which are interpreted as delimiters by PHP. These
  2388. * characters are double escaped so PHP will still see the encoded version.
  2389. * - With clean URLs, Apache changes '//' to '/', so every second slash is
  2390. * double escaped.
  2391. * - This function should only be used on paths, not on query string arguments,
  2392. * otherwise unwanted double encoding will occur.
  2393. *
  2394. * @param $text
  2395. * String to encode
  2396. */
  2397. function drupal_urlencode($text) {
  2398. if (variable_get('clean_url', '0')) {
  2399. return str_replace(array('%2F', '%26', '%23', '//'),
  2400. array('/', '%2526', '%2523', '/%252F'),
  2401. rawurlencode($text));
  2402. }
  2403. else {
  2404. return str_replace('%2F', '/', rawurlencode($text));
  2405. }
  2406. }
  2407. /**
  2408. * Ensure the private key variable used to generate tokens is set.
  2409. *
  2410. * @return
  2411. * The private key.
  2412. */
  2413. function drupal_get_private_key() {
  2414. if (!($key = variable_get('drupal_private_key', 0))) {
  2415. $key = drupal_random_key();
  2416. variable_set('drupal_private_key', $key);
  2417. }
  2418. return $key;
  2419. }
  2420. /**
  2421. * Generate a token based on $value, the current user session and private key.
  2422. *
  2423. * @param $value
  2424. * An additional value to base the token on.
  2425. */
  2426. function drupal_get_token($value = '') {
  2427. $private_key = drupal_get_private_key();
  2428. return md5(session_id() . $value . $private_key);
  2429. }
  2430. /**
  2431. * Validate a token based on $value, the current user session and private key.
  2432. *
  2433. * @param $token
  2434. * The token to be validated.
  2435. * @param $value
  2436. * An additional value to base the token on.
  2437. * @param $skip_anonymous
  2438. * Set to true to skip token validation for anonymous users.
  2439. * @return
  2440. * True for a valid token, false for an invalid token. When $skip_anonymous
  2441. * is true, the return value will always be true for anonymous users.
  2442. */
  2443. function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
  2444. global $user;
  2445. return (($skip_anonymous && $user->uid == 0) || ($token === md5(session_id() . $value . variable_get('drupal_private_key', ''))));
  2446. }
  2447. /**
  2448. * Performs one or more XML-RPC request(s).
  2449. *
  2450. * @param $url
  2451. * An absolute URL of the XML-RPC endpoint.
  2452. * Example:
  2453. * http://www.example.com/xmlrpc.php
  2454. * @param ...
  2455. * For one request:
  2456. * The method name followed by a variable number of arguments to the method.
  2457. * For multiple requests (system.multicall):
  2458. * An array of call arrays. Each call array follows the pattern of the single
  2459. * request: method name followed by the arguments to the method.
  2460. * @return
  2461. * For one request:
  2462. * Either the return value of the method on success, or FALSE.
  2463. * If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
  2464. * For multiple requests:
  2465. * An array of results. Each result will either be the result
  2466. * returned by the method called, or an xmlrpc_error object if the call
  2467. * failed. See xmlrpc_error().
  2468. */
  2469. function xmlrpc($url) {
  2470. require_once './includes/xmlrpc.inc';
  2471. $args = func_get_args();
  2472. return call_user_func_array('_xmlrpc', $args);
  2473. }
  2474. function _drupal_bootstrap_full() {
  2475. static $called;
  2476. if ($called) {
  2477. return;
  2478. }
  2479. $called = 1;
  2480. require_once './includes/theme.inc';
  2481. require_once './includes/pager.inc';
  2482. require_once './includes/menu.inc';
  2483. require_once './includes/tablesort.inc';
  2484. require_once './includes/file.inc';
  2485. require_once './includes/unicode.inc';
  2486. require_once './includes/image.inc';
  2487. require_once './includes/form.inc';
  2488. require_once './includes/mail.inc';
  2489. require_once './includes/actions.inc';
  2490. // Set the Drupal custom error handler.
  2491. set_error_handler('drupal_error_handler');
  2492. // Emit the correct charset HTTP header.
  2493. drupal_set_header('Content-Type: text/html; charset=utf-8');
  2494. // Detect string handling method
  2495. unicode_check();
  2496. // Undo magic quotes
  2497. fix_gpc_magic();
  2498. // Load all enabled modules
  2499. module_load_all();
  2500. // Ensure mt_rand is reseeded, to prevent random values from one page load
  2501. // being exploited to predict random values in subsequent page loads.
  2502. $seed = unpack("L", drupal_random_bytes(4));
  2503. mt_srand($seed[1]);
  2504. // Let all modules take action before menu system handles the request
  2505. // We do not want this while running update.php.
  2506. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
  2507. module_invoke_all('init');
  2508. }
  2509. }
  2510. /**
  2511. * Store the current page in the cache.
  2512. *
  2513. * If page_compression is enabled, a gzipped version of the page is stored in
  2514. * the cache to avoid compressing the output on each request. The cache entry
  2515. * is unzipped in the relatively rare event that the page is requested by a
  2516. * client without gzip support.
  2517. *
  2518. * Page compression requires the PHP zlib extension
  2519. * (http://php.net/manual/en/ref.zlib.php).
  2520. *
  2521. * @see drupal_page_header
  2522. */
  2523. function page_set_cache() {
  2524. global $user, $base_root;
  2525. if (!$user->uid && $_SERVER['REQUEST_METHOD'] == 'GET' && page_get_cache(TRUE)) {
  2526. // This will fail in some cases, see page_get_cache() for the explanation.
  2527. if ($data = ob_get_contents()) {
  2528. if (variable_get('page_compression', TRUE) && extension_loaded('zlib')) {
  2529. $data = gzencode($data, 9, FORCE_GZIP);
  2530. }
  2531. ob_end_flush();
  2532. cache_set($base_root . request_uri(), $data, 'cache_page', CACHE_TEMPORARY, drupal_get_headers());
  2533. }
  2534. }
  2535. }
  2536. /**
  2537. * Executes a cron run when called
  2538. * @return
  2539. * Returns TRUE if ran successfully
  2540. */
  2541. function drupal_cron_run() {
  2542. // Try to allocate enough time to run all the hook_cron implementations.
  2543. if (function_exists('set_time_limit')) {
  2544. @set_time_limit(240);
  2545. }
  2546. // Fetch the cron semaphore
  2547. $semaphore = variable_get('cron_semaphore', FALSE);
  2548. if ($semaphore) {
  2549. if (time() - $semaphore > 3600) {
  2550. // Either cron has been running for more than an hour or the semaphore
  2551. // was not reset due to a database error.
  2552. watchdog('cron', 'Cron has been running for more than an hour and is most likely stuck.', array(), WATCHDOG_ERROR);
  2553. // Release cron semaphore
  2554. variable_del('cron_semaphore');
  2555. }
  2556. else {
  2557. // Cron is still running normally.
  2558. watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
  2559. }
  2560. }
  2561. else {
  2562. // Register shutdown callback
  2563. register_shutdown_function('drupal_cron_cleanup');
  2564. // Lock cron semaphore
  2565. variable_set('cron_semaphore', time());
  2566. // Iterate through the modules calling their cron handlers (if any):
  2567. module_invoke_all('cron');
  2568. // Record cron time
  2569. variable_set('cron_last', time());
  2570. watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
  2571. // Release cron semaphore
  2572. variable_del('cron_semaphore');
  2573. // Return TRUE so other functions can check if it did run successfully
  2574. return TRUE;
  2575. }
  2576. }
  2577. /**
  2578. * Shutdown function for cron cleanup.
  2579. */
  2580. function drupal_cron_cleanup() {
  2581. // See if the semaphore is still locked.
  2582. if (variable_get('cron_semaphore', FALSE)) {
  2583. watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);
  2584. // Release cron semaphore
  2585. variable_del('cron_semaphore');
  2586. }
  2587. }
  2588. /**
  2589. * Return an array of system file objects.
  2590. *
  2591. * Returns an array of file objects of the given type from the site-wide
  2592. * directory (i.e. modules/), the all-sites directory (i.e.
  2593. * sites/all/modules/), the profiles directory, and site-specific directory
  2594. * (i.e. sites/somesite/modules/). The returned array will be keyed using the
  2595. * key specified (name, basename, filename). Using name or basename will cause
  2596. * site-specific files to be prioritized over similar files in the default
  2597. * directories. That is, if a file with the same name appears in both the
  2598. * site-wide directory and site-specific directory, only the site-specific
  2599. * version will be included.
  2600. *
  2601. * @param $mask
  2602. * The regular expression of the files to find.
  2603. * @param $directory
  2604. * The subdirectory name in which the files are found. For example,
  2605. * 'modules' will search in both modules/ and
  2606. * sites/somesite/modules/.
  2607. * @param $key
  2608. * The key to be passed to file_scan_directory().
  2609. * @param $min_depth
  2610. * Minimum depth of directories to return files from.
  2611. *
  2612. * @return
  2613. * An array of file objects of the specified type.
  2614. */
  2615. function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
  2616. global $profile;
  2617. $config = conf_path();
  2618. // When this function is called during Drupal's initial installation process,
  2619. // the name of the profile that's about to be installed is stored in the global
  2620. // $profile variable. At all other times, the standard Drupal systems variable
  2621. // table contains the name of the current profile, and we can call variable_get()
  2622. // to determine what one is active.
  2623. if (!isset($profile)) {
  2624. $profile = variable_get('install_profile', 'default');
  2625. }
  2626. $searchdir = array($directory);
  2627. $files = array();
  2628. // The 'profiles' directory contains pristine collections of modules and
  2629. // themes as organized by a distribution. It is pristine in the same way
  2630. // that /modules is pristine for core; users should avoid changing anything
  2631. // there in favor of sites/all or sites/<domain> directories.
  2632. if (file_exists("profiles/$profile/$directory")) {
  2633. $searchdir[] = "profiles/$profile/$directory";
  2634. }
  2635. // Always search sites/all/* as well as the global directories
  2636. $searchdir[] = 'sites/all/'. $directory;
  2637. if (file_exists("$config/$directory")) {
  2638. $searchdir[] = "$config/$directory";
  2639. }
  2640. // Get current list of items
  2641. foreach ($searchdir as $dir) {
  2642. $files = array_merge($files, file_scan_directory($dir, $mask, array('.', '..', 'CVS'), 0, TRUE, $key, $min_depth));
  2643. }
  2644. return $files;
  2645. }
  2646. /**
  2647. * Hands off alterable variables to type-specific *_alter implementations.
  2648. *
  2649. * This dispatch function hands off the passed in variables to type-specific
  2650. * hook_TYPE_alter() implementations in modules. It ensures a consistent
  2651. * interface for all altering operations.
  2652. *
  2653. * @param $type
  2654. * A string describing the type of the alterable $data (e.g. 'form',
  2655. * 'profile').
  2656. * @param $data
  2657. * The variable that will be passed to hook_TYPE_alter() implementations to
  2658. * be altered. The type of this variable depends on $type. For example, when
  2659. * altering a 'form', $data will be a structured array. When altering a
  2660. * 'profile', $data will be an object. If you need to pass additional
  2661. * parameters by reference to the hook_TYPE_alter() functions, include them
  2662. * as an array in $data['__drupal_alter_by_ref']. They will be unpacked and
  2663. * passed to the hook_TYPE_alter() functions, before the additional
  2664. * ... parameters (see below).
  2665. * @param ...
  2666. * Any additional parameters will be passed on to the hook_TYPE_alter()
  2667. * functions (not by reference), after any by-reference parameters included
  2668. * in $data (see above)
  2669. */
  2670. function drupal_alter($type, &$data) {
  2671. // PHP's func_get_args() always returns copies of params, not references, so
  2672. // drupal_alter() can only manipulate data that comes in via the required first
  2673. // param. For the edge case functions that must pass in an arbitrary number of
  2674. // alterable parameters (hook_form_alter() being the best example), an array of
  2675. // those params can be placed in the __drupal_alter_by_ref key of the $data
  2676. // array. This is somewhat ugly, but is an unavoidable consequence of a flexible
  2677. // drupal_alter() function, and the limitations of func_get_args().
  2678. // @todo: Remove this in Drupal 7.
  2679. if (is_array($data) && isset($data['__drupal_alter_by_ref'])) {
  2680. $by_ref_parameters = $data['__drupal_alter_by_ref'];
  2681. unset($data['__drupal_alter_by_ref']);
  2682. }
  2683. // Hang onto a reference to the data array so that it isn't blown away later.
  2684. // Also, merge in any parameters that need to be passed by reference.
  2685. $args = array(&$data);
  2686. if (isset($by_ref_parameters)) {
  2687. $args = array_merge($args, $by_ref_parameters);
  2688. }
  2689. // Now, use func_get_args() to pull in any additional parameters passed into
  2690. // the drupal_alter() call.
  2691. $additional_args = func_get_args();
  2692. array_shift($additional_args);
  2693. array_shift($additional_args);
  2694. $args = array_merge($args, $additional_args);
  2695. foreach (module_implements($type .'_alter') as $module) {
  2696. $function = $module .'_'. $type .'_alter';
  2697. call_user_func_array($function, $args);
  2698. }
  2699. }
  2700. /**
  2701. * Renders HTML given a structured array tree.
  2702. *
  2703. * Recursively iterates over each of the array elements, generating HTML code.
  2704. * This function is usually called from within another function, like
  2705. * drupal_get_form() or node_view().
  2706. *
  2707. * drupal_render() flags each element with a '#printed' status to indicate that
  2708. * the element has been rendered, which allows individual elements of a given
  2709. * array to be rendered independently. This prevents elements from being
  2710. * rendered more than once on subsequent calls to drupal_render() if, for example,
  2711. * they are part of a larger array. If the same array or array element is passed
  2712. * more than once to drupal_render(), it simply returns a NULL value.
  2713. *
  2714. * @param $elements
  2715. * The structured array describing the data to be rendered.
  2716. * @return
  2717. * The rendered HTML.
  2718. */
  2719. function drupal_render(&$elements) {
  2720. if (!isset($elements) || (isset($elements['#access']) && !$elements['#access'])) {
  2721. return NULL;
  2722. }
  2723. // If the default values for this element haven't been loaded yet, populate
  2724. // them.
  2725. if (!isset($elements['#defaults_loaded']) || !$elements['#defaults_loaded']) {
  2726. if ((!empty($elements['#type'])) && ($info = _element_info($elements['#type']))) {
  2727. $elements += $info;
  2728. }
  2729. }
  2730. // Make any final changes to the element before it is rendered. This means
  2731. // that the $element or the children can be altered or corrected before the
  2732. // element is rendered into the final text.
  2733. if (isset($elements['#pre_render'])) {
  2734. foreach ($elements['#pre_render'] as $function) {
  2735. if (function_exists($function)) {
  2736. $elements = $function($elements);
  2737. }
  2738. }
  2739. }
  2740. $content = '';
  2741. // Either the elements did not go through form_builder or one of the children
  2742. // has a #weight.
  2743. if (!isset($elements['#sorted'])) {
  2744. uasort($elements, "element_sort");
  2745. }
  2746. $elements += array('#title' => NULL, '#description' => NULL);
  2747. if (!isset($elements['#children'])) {
  2748. $children = element_children($elements);
  2749. // Render all the children that use a theme function.
  2750. if (isset($elements['#theme']) && empty($elements['#theme_used'])) {
  2751. $elements['#theme_used'] = TRUE;
  2752. $previous = array();
  2753. foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
  2754. $previous[$key] = isset($elements[$key]) ? $elements[$key] : NULL;
  2755. }
  2756. // If we rendered a single element, then we will skip the renderer.
  2757. if (empty($children)) {
  2758. $elements['#printed'] = TRUE;
  2759. }
  2760. else {
  2761. $elements['#value'] = '';
  2762. }
  2763. $elements['#type'] = 'markup';
  2764. unset($elements['#prefix'], $elements['#suffix']);
  2765. $content = theme($elements['#theme'], $elements);
  2766. foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
  2767. $elements[$key] = isset($previous[$key]) ? $previous[$key] : NULL;
  2768. }
  2769. }
  2770. // Render each of the children using drupal_render and concatenate them.
  2771. if (!isset($content) || $content === '') {
  2772. foreach ($children as $key) {
  2773. $content .= drupal_render($elements[$key]);
  2774. }
  2775. }
  2776. }
  2777. if (isset($content) && $content !== '') {
  2778. $elements['#children'] = $content;
  2779. }
  2780. // Until now, we rendered the children, here we render the element itself
  2781. if (!isset($elements['#printed'])) {
  2782. $content = theme(!empty($elements['#type']) ? $elements['#type'] : 'markup', $elements);
  2783. $elements['#printed'] = TRUE;
  2784. }
  2785. if (isset($content) && $content !== '') {
  2786. // Filter the outputted content and make any last changes before the
  2787. // content is sent to the browser. The changes are made on $content
  2788. // which allows the output'ed text to be filtered.
  2789. if (isset($elements['#post_render'])) {
  2790. foreach ($elements['#post_render'] as $function) {
  2791. if (function_exists($function)) {
  2792. $content = $function($content, $elements);
  2793. }
  2794. }
  2795. }
  2796. $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
  2797. $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
  2798. return $prefix . $content . $suffix;
  2799. }
  2800. }
  2801. /**
  2802. * Function used by uasort to sort structured arrays by weight.
  2803. */
  2804. function element_sort($a, $b) {
  2805. $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
  2806. $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
  2807. if ($a_weight == $b_weight) {
  2808. return 0;
  2809. }
  2810. return ($a_weight < $b_weight) ? -1 : 1;
  2811. }
  2812. /**
  2813. * Check if the key is a property.
  2814. */
  2815. function element_property($key) {
  2816. return $key[0] == '#';
  2817. }
  2818. /**
  2819. * Get properties of a structured array element. Properties begin with '#'.
  2820. */
  2821. function element_properties($element) {
  2822. return array_filter(array_keys((array) $element), 'element_property');
  2823. }
  2824. /**
  2825. * Check if the key is a child.
  2826. */
  2827. function element_child($key) {
  2828. return !isset($key[0]) || $key[0] != '#';
  2829. }
  2830. /**
  2831. * Get keys of a structured array tree element that are not properties (i.e., do not begin with '#').
  2832. */
  2833. function element_children($element) {
  2834. return array_filter(array_keys((array) $element), 'element_child');
  2835. }
  2836. /**
  2837. * Provide theme registration for themes across .inc files.
  2838. */
  2839. function drupal_common_theme() {
  2840. return array(
  2841. // theme.inc
  2842. 'placeholder' => array(
  2843. 'arguments' => array('text' => NULL)
  2844. ),
  2845. 'page' => array(
  2846. 'arguments' => array('content' => NULL, 'show_blocks' => TRUE, 'show_messages' => TRUE),
  2847. 'template' => 'page',
  2848. ),
  2849. 'maintenance_page' => array(
  2850. 'arguments' => array('content' => NULL, 'show_blocks' => TRUE, 'show_messages' => TRUE),
  2851. 'template' => 'maintenance-page',
  2852. ),
  2853. 'update_page' => array(
  2854. 'arguments' => array('content' => NULL, 'show_messages' => TRUE),
  2855. ),
  2856. 'install_page' => array(
  2857. 'arguments' => array('content' => NULL),
  2858. ),
  2859. 'task_list' => array(
  2860. 'arguments' => array('items' => NULL, 'active' => NULL),
  2861. ),
  2862. 'status_messages' => array(
  2863. 'arguments' => array('display' => NULL),
  2864. ),
  2865. 'links' => array(
  2866. 'arguments' => array('links' => NULL, 'attributes' => array('class' => 'links')),
  2867. ),
  2868. 'image' => array(
  2869. 'arguments' => array('path' => NULL, 'alt' => '', 'title' => '', 'attributes' => NULL, 'getsize' => TRUE),
  2870. ),
  2871. 'breadcrumb' => array(
  2872. 'arguments' => array('breadcrumb' => NULL),
  2873. ),
  2874. 'help' => array(
  2875. 'arguments' => array(),
  2876. ),
  2877. 'submenu' => array(
  2878. 'arguments' => array('links' => NULL),
  2879. ),
  2880. 'table' => array(
  2881. 'arguments' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL),
  2882. ),
  2883. 'table_select_header_cell' => array(
  2884. 'arguments' => array(),
  2885. ),
  2886. 'tablesort_indicator' => array(
  2887. 'arguments' => array('style' => NULL),
  2888. ),
  2889. 'box' => array(
  2890. 'arguments' => array('title' => NULL, 'content' => NULL, 'region' => 'main'),
  2891. 'template' => 'box',
  2892. ),
  2893. 'block' => array(
  2894. 'arguments' => array('block' => NULL),
  2895. 'template' => 'block',
  2896. ),
  2897. 'mark' => array(
  2898. 'arguments' => array('type' => MARK_NEW),
  2899. ),
  2900. 'item_list' => array(
  2901. 'arguments' => array('items' => array(), 'title' => NULL, 'type' => 'ul', 'attributes' => NULL),
  2902. ),
  2903. 'more_help_link' => array(
  2904. 'arguments' => array('url' => NULL),
  2905. ),
  2906. 'xml_icon' => array(
  2907. 'arguments' => array('url' => NULL),
  2908. ),
  2909. 'feed_icon' => array(
  2910. 'arguments' => array('url' => NULL, 'title' => NULL),
  2911. ),
  2912. 'more_link' => array(
  2913. 'arguments' => array('url' => NULL, 'title' => NULL)
  2914. ),
  2915. 'closure' => array(
  2916. 'arguments' => array('main' => 0),
  2917. ),
  2918. 'blocks' => array(
  2919. 'arguments' => array('region' => NULL),
  2920. ),
  2921. 'username' => array(
  2922. 'arguments' => array('object' => NULL),
  2923. ),
  2924. 'progress_bar' => array(
  2925. 'arguments' => array('percent' => NULL, 'message' => NULL),
  2926. ),
  2927. 'indentation' => array(
  2928. 'arguments' => array('size' => 1),
  2929. ),
  2930. // from pager.inc
  2931. 'pager' => array(
  2932. 'arguments' => array('tags' => array(), 'limit' => 10, 'element' => 0, 'parameters' => array()),
  2933. ),
  2934. 'pager_first' => array(
  2935. 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'parameters' => array()),
  2936. ),
  2937. 'pager_previous' => array(
  2938. 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
  2939. ),
  2940. 'pager_next' => array(
  2941. 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
  2942. ),
  2943. 'pager_last' => array(
  2944. 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'parameters' => array()),
  2945. ),
  2946. 'pager_link' => array(
  2947. 'arguments' => array('text' => NULL, 'page_new' => NULL, 'element' => NULL, 'parameters' => array(), 'attributes' => array()),
  2948. ),
  2949. // from menu.inc
  2950. 'menu_item_link' => array(
  2951. 'arguments' => array('item' => NULL),
  2952. ),
  2953. 'menu_tree' => array(
  2954. 'arguments' => array('tree' => NULL),
  2955. ),
  2956. 'menu_item' => array(
  2957. 'arguments' => array('link' => NULL, 'has_children' => NULL, 'menu' => ''),
  2958. ),
  2959. 'menu_local_task' => array(
  2960. 'arguments' => array('link' => NULL, 'active' => FALSE),
  2961. ),
  2962. 'menu_local_tasks' => array(
  2963. 'arguments' => array(),
  2964. ),
  2965. // from form.inc
  2966. 'select' => array(
  2967. 'arguments' => array('element' => NULL),
  2968. ),
  2969. 'fieldset' => array(
  2970. 'arguments' => array('element' => NULL),
  2971. ),
  2972. 'radio' => array(
  2973. 'arguments' => array('element' => NULL),
  2974. ),
  2975. 'radios' => array(
  2976. 'arguments' => array('element' => NULL),
  2977. ),
  2978. 'password_confirm' => array(
  2979. 'arguments' => array('element' => NULL),
  2980. ),
  2981. 'date' => array(
  2982. 'arguments' => array('element' => NULL),
  2983. ),
  2984. 'item' => array(
  2985. 'arguments' => array('element' => NULL),
  2986. ),
  2987. 'checkbox' => array(
  2988. 'arguments' => array('element' => NULL),
  2989. ),
  2990. 'checkboxes' => array(
  2991. 'arguments' => array('element' => NULL),
  2992. ),
  2993. 'submit' => array(
  2994. 'arguments' => array('element' => NULL),
  2995. ),
  2996. 'button' => array(
  2997. 'arguments' => array('element' => NULL),
  2998. ),
  2999. 'image_button' => array(
  3000. 'arguments' => array('element' => NULL),
  3001. ),
  3002. 'hidden' => array(
  3003. 'arguments' => array('element' => NULL),
  3004. ),
  3005. 'token' => array(
  3006. 'arguments' => array('element' => NULL),
  3007. ),
  3008. 'textfield' => array(
  3009. 'arguments' => array('element' => NULL),
  3010. ),
  3011. 'form' => array(
  3012. 'arguments' => array('element' => NULL),
  3013. ),
  3014. 'textarea' => array(
  3015. 'arguments' => array('element' => NULL),
  3016. ),
  3017. 'markup' => array(
  3018. 'arguments' => array('element' => NULL),
  3019. ),
  3020. 'password' => array(
  3021. 'arguments' => array('element' => NULL),
  3022. ),
  3023. 'file' => array(
  3024. 'arguments' => array('element' => NULL),
  3025. ),
  3026. 'form_element' => array(
  3027. 'arguments' => array('element' => NULL, 'value' => NULL),
  3028. ),
  3029. );
  3030. }
  3031. /**
  3032. * @ingroup schemaapi
  3033. * @{
  3034. */
  3035. /**
  3036. * Get the schema definition of a table, or the whole database schema.
  3037. *
  3038. * The returned schema will include any modifications made by any
  3039. * module that implements hook_schema_alter().
  3040. *
  3041. * @param $table
  3042. * The name of the table. If not given, the schema of all tables is returned.
  3043. * @param $rebuild
  3044. * If true, the schema will be rebuilt instead of retrieved from the cache.
  3045. */
  3046. function drupal_get_schema($table = NULL, $rebuild = FALSE) {
  3047. static $schema = array();
  3048. if (empty($schema) || $rebuild) {
  3049. // Try to load the schema from cache.
  3050. if (!$rebuild && $cached = cache_get('schema')) {
  3051. $schema = $cached->data;
  3052. }
  3053. // Otherwise, rebuild the schema cache.
  3054. else {
  3055. $schema = array();
  3056. // Load the .install files to get hook_schema.
  3057. module_load_all_includes('install');
  3058. // Invoke hook_schema for all modules.
  3059. foreach (module_implements('schema') as $module) {
  3060. // Cast the result of hook_schema() to an array, as a NULL return value
  3061. // would cause array_merge() to set the $schema variable to NULL as well.
  3062. // That would break modules which use $schema further down the line.
  3063. $current = (array) module_invoke($module, 'schema');
  3064. _drupal_initialize_schema($module, $current);
  3065. $schema = array_merge($schema, $current);
  3066. }
  3067. drupal_alter('schema', $schema);
  3068. cache_set('schema', $schema);
  3069. }
  3070. }
  3071. if (!isset($table)) {
  3072. return $schema;
  3073. }
  3074. elseif (isset($schema[$table])) {
  3075. return $schema[$table];
  3076. }
  3077. else {
  3078. return FALSE;
  3079. }
  3080. }
  3081. /**
  3082. * Create all tables that a module defines in its hook_schema().
  3083. *
  3084. * Note: This function does not pass the module's schema through
  3085. * hook_schema_alter(). The module's tables will be created exactly as the
  3086. * module defines them.
  3087. *
  3088. * @param $module
  3089. * The module for which the tables will be created.
  3090. * @return
  3091. * An array of arrays with the following key/value pairs:
  3092. * - success: a boolean indicating whether the query succeeded.
  3093. * - query: the SQL query(s) executed, passed through check_plain().
  3094. */
  3095. function drupal_install_schema($module) {
  3096. $schema = drupal_get_schema_unprocessed($module);
  3097. _drupal_initialize_schema($module, $schema);
  3098. $ret = array();
  3099. foreach ($schema as $name => $table) {
  3100. db_create_table($ret, $name, $table);
  3101. }
  3102. return $ret;
  3103. }
  3104. /**
  3105. * Remove all tables that a module defines in its hook_schema().
  3106. *
  3107. * Note: This function does not pass the module's schema through
  3108. * hook_schema_alter(). The module's tables will be created exactly as the
  3109. * module defines them.
  3110. *
  3111. * @param $module
  3112. * The module for which the tables will be removed.
  3113. * @return
  3114. * An array of arrays with the following key/value pairs:
  3115. * - success: a boolean indicating whether the query succeeded.
  3116. * - query: the SQL query(s) executed, passed through check_plain().
  3117. */
  3118. function drupal_uninstall_schema($module) {
  3119. $schema = drupal_get_schema_unprocessed($module);
  3120. _drupal_initialize_schema($module, $schema);
  3121. $ret = array();
  3122. foreach ($schema as $table) {
  3123. db_drop_table($ret, $table['name']);
  3124. }
  3125. return $ret;
  3126. }
  3127. /**
  3128. * Returns the unprocessed and unaltered version of a module's schema.
  3129. *
  3130. * Use this function only if you explicitly need the original
  3131. * specification of a schema, as it was defined in a module's
  3132. * hook_schema(). No additional default values will be set,
  3133. * hook_schema_alter() is not invoked and these unprocessed
  3134. * definitions won't be cached.
  3135. *
  3136. * This function can be used to retrieve a schema specification in
  3137. * hook_schema(), so it allows you to derive your tables from existing
  3138. * specifications.
  3139. *
  3140. * It is also used by drupal_install_schema() and
  3141. * drupal_uninstall_schema() to ensure that a module's tables are
  3142. * created exactly as specified without any changes introduced by a
  3143. * module that implements hook_schema_alter().
  3144. *
  3145. * @param $module
  3146. * The module to which the table belongs.
  3147. * @param $table
  3148. * The name of the table. If not given, the module's complete schema
  3149. * is returned.
  3150. */
  3151. function drupal_get_schema_unprocessed($module, $table = NULL) {
  3152. // Load the .install file to get hook_schema.
  3153. module_load_install($module);
  3154. $schema = module_invoke($module, 'schema');
  3155. if (!is_null($table) && isset($schema[$table])) {
  3156. return $schema[$table];
  3157. }
  3158. elseif (!empty($schema)) {
  3159. return $schema;
  3160. }
  3161. return array();
  3162. }
  3163. /**
  3164. * Fill in required default values for table definitions returned by hook_schema().
  3165. *
  3166. * @param $module
  3167. * The module for which hook_schema() was invoked.
  3168. * @param $schema
  3169. * The schema definition array as it was returned by the module's
  3170. * hook_schema().
  3171. */
  3172. function _drupal_initialize_schema($module, &$schema) {
  3173. // Set the name and module key for all tables.
  3174. foreach ($schema as $name => $table) {
  3175. if (empty($table['module'])) {
  3176. $schema[$name]['module'] = $module;
  3177. }
  3178. if (!isset($table['name'])) {
  3179. $schema[$name]['name'] = $name;
  3180. }
  3181. }
  3182. }
  3183. /**
  3184. * Retrieve a list of fields from a table schema. The list is suitable for use in a SQL query.
  3185. *
  3186. * @param $table
  3187. * The name of the table from which to retrieve fields.
  3188. * @param
  3189. * An optional prefix to to all fields.
  3190. *
  3191. * @return An array of fields.
  3192. **/
  3193. function drupal_schema_fields_sql($table, $prefix = NULL) {
  3194. $schema = drupal_get_schema($table);
  3195. $fields = array_keys($schema['fields']);
  3196. if ($prefix) {
  3197. $columns = array();
  3198. foreach ($fields as $field) {
  3199. $columns[] = "$prefix.$field";
  3200. }
  3201. return $columns;
  3202. }
  3203. else {
  3204. return $fields;
  3205. }
  3206. }
  3207. /**
  3208. * Save a record to the database based upon the schema.
  3209. *
  3210. * Default values are filled in for missing items, and 'serial' (auto increment)
  3211. * types are filled in with IDs.
  3212. *
  3213. * @param $table
  3214. * The name of the table; this must exist in schema API.
  3215. * @param $object
  3216. * The object to write. This is a reference, as defaults according to
  3217. * the schema may be filled in on the object, as well as ID on the serial
  3218. * type(s). Both array an object types may be passed.
  3219. * @param $update
  3220. * If this is an update, specify the primary keys' field names. It is the
  3221. * caller's responsibility to know if a record for this object already
  3222. * exists in the database. If there is only 1 key, you may pass a simple string.
  3223. * @return
  3224. * Failure to write a record will return FALSE. Otherwise SAVED_NEW or
  3225. * SAVED_UPDATED is returned depending on the operation performed. The
  3226. * $object parameter contains values for any serial fields defined by
  3227. * the $table. For example, $object->nid will be populated after inserting
  3228. * a new node.
  3229. */
  3230. function drupal_write_record($table, &$object, $update = array()) {
  3231. // Standardize $update to an array.
  3232. if (is_string($update)) {
  3233. $update = array($update);
  3234. }
  3235. $schema = drupal_get_schema($table);
  3236. if (empty($schema)) {
  3237. return FALSE;
  3238. }
  3239. // Convert to an object if needed.
  3240. if (is_array($object)) {
  3241. $object = (object) $object;
  3242. $array = TRUE;
  3243. }
  3244. else {
  3245. $array = FALSE;
  3246. }
  3247. $fields = $defs = $values = $serials = $placeholders = array();
  3248. // Go through our schema, build SQL, and when inserting, fill in defaults for
  3249. // fields that are not set.
  3250. foreach ($schema['fields'] as $field => $info) {
  3251. // Special case -- skip serial types if we are updating.
  3252. if ($info['type'] == 'serial' && count($update)) {
  3253. continue;
  3254. }
  3255. // For inserts, populate defaults from Schema if not already provided
  3256. if (!isset($object->$field) && !count($update) && isset($info['default'])) {
  3257. $object->$field = $info['default'];
  3258. }
  3259. // Track serial fields so we can helpfully populate them after the query.
  3260. if ($info['type'] == 'serial') {
  3261. $serials[] = $field;
  3262. // Ignore values for serials when inserting data. Unsupported.
  3263. unset($object->$field);
  3264. }
  3265. // Build arrays for the fields, placeholders, and values in our query.
  3266. if (isset($object->$field)) {
  3267. $fields[] = $field;
  3268. $placeholders[] = db_type_placeholder($info['type']);
  3269. if (empty($info['serialize'])) {
  3270. $values[] = $object->$field;
  3271. }
  3272. else {
  3273. $values[] = serialize($object->$field);
  3274. }
  3275. }
  3276. }
  3277. // Build the SQL.
  3278. $query = '';
  3279. if (!count($update)) {
  3280. $query = "INSERT INTO {". $table ."} (". implode(', ', $fields) .') VALUES ('. implode(', ', $placeholders) .')';
  3281. $return = SAVED_NEW;
  3282. }
  3283. else {
  3284. $query = '';
  3285. foreach ($fields as $id => $field) {
  3286. if ($query) {
  3287. $query .= ', ';
  3288. }
  3289. $query .= $field .' = '. $placeholders[$id];
  3290. }
  3291. foreach ($update as $key){
  3292. $conditions[] = "$key = ". db_type_placeholder($schema['fields'][$key]['type']);
  3293. $values[] = $object->$key;
  3294. }
  3295. $query = "UPDATE {". $table ."} SET $query WHERE ". implode(' AND ', $conditions);
  3296. $return = SAVED_UPDATED;
  3297. }
  3298. // Execute the SQL.
  3299. if (db_query($query, $values)) {
  3300. if ($serials) {
  3301. // Get last insert ids and fill them in.
  3302. foreach ($serials as $field) {
  3303. $object->$field = db_last_insert_id($table, $field);
  3304. }
  3305. }
  3306. }
  3307. else {
  3308. $return = FALSE;
  3309. }
  3310. // If we began with an array, convert back so we don't surprise the caller.
  3311. if ($array) {
  3312. $object = (array) $object;
  3313. }
  3314. return $return;
  3315. }
  3316. /**
  3317. * @} End of "ingroup schemaapi".
  3318. */
  3319. /**
  3320. * Parse Drupal info file format.
  3321. *
  3322. * Files should use an ini-like format to specify values.
  3323. * White-space generally doesn't matter, except inside values.
  3324. * e.g.
  3325. *
  3326. * @code
  3327. * key = value
  3328. * key = "value"
  3329. * key = 'value'
  3330. * key = "multi-line
  3331. *
  3332. * value"
  3333. * key = 'multi-line
  3334. *
  3335. * value'
  3336. * key
  3337. * =
  3338. * 'value'
  3339. * @endcode
  3340. *
  3341. * Arrays are created using a GET-like syntax:
  3342. *
  3343. * @code
  3344. * key[] = "numeric array"
  3345. * key[index] = "associative array"
  3346. * key[index][] = "nested numeric array"
  3347. * key[index][index] = "nested associative array"
  3348. * @endcode
  3349. *
  3350. * PHP constants are substituted in, but only when used as the entire value:
  3351. *
  3352. * Comments should start with a semi-colon at the beginning of a line.
  3353. *
  3354. * This function is NOT for placing arbitrary module-specific settings. Use
  3355. * variable_get() and variable_set() for that.
  3356. *
  3357. * Information stored in the module.info file:
  3358. * - name: The real name of the module for display purposes.
  3359. * - description: A brief description of the module.
  3360. * - dependencies: An array of shortnames of other modules this module depends on.
  3361. * - package: The name of the package of modules this module belongs to.
  3362. *
  3363. * Example of .info file:
  3364. * @code
  3365. * name = Forum
  3366. * description = Enables threaded discussions about general topics.
  3367. * dependencies[] = taxonomy
  3368. * dependencies[] = comment
  3369. * package = Core - optional
  3370. * version = VERSION
  3371. * @endcode
  3372. *
  3373. * @param $filename
  3374. * The file we are parsing. Accepts file with relative or absolute path.
  3375. * @return
  3376. * The info array.
  3377. */
  3378. function drupal_parse_info_file($filename) {
  3379. $info = array();
  3380. $constants = get_defined_constants();
  3381. if (!file_exists($filename)) {
  3382. return $info;
  3383. }
  3384. $data = file_get_contents($filename);
  3385. if (preg_match_all('
  3386. @^\s* # Start at the beginning of a line, ignoring leading whitespace
  3387. ((?:
  3388. [^=;\[\]]| # Key names cannot contain equal signs, semi-colons or square brackets,
  3389. \[[^\[\]]*\] # unless they are balanced and not nested
  3390. )+?)
  3391. \s*=\s* # Key/value pairs are separated by equal signs (ignoring white-space)
  3392. (?:
  3393. ("(?:[^"]|(?<=\\\\)")*")| # Double-quoted string, which may contain slash-escaped quotes/slashes
  3394. (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
  3395. ([^\r\n]*?) # Non-quoted string
  3396. )\s*$ # Stop at the next end of a line, ignoring trailing whitespace
  3397. @msx', $data, $matches, PREG_SET_ORDER)) {
  3398. foreach ($matches as $match) {
  3399. // Fetch the key and value string
  3400. $i = 0;
  3401. foreach (array('key', 'value1', 'value2', 'value3') as $var) {
  3402. $$var = isset($match[++$i]) ? $match[$i] : '';
  3403. }
  3404. $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
  3405. // Parse array syntax
  3406. $keys = preg_split('/\]?\[/', rtrim($key, ']'));
  3407. $last = array_pop($keys);
  3408. $parent = &$info;
  3409. // Create nested arrays
  3410. foreach ($keys as $key) {
  3411. if ($key == '') {
  3412. $key = count($parent);
  3413. }
  3414. if (!isset($parent[$key]) || !is_array($parent[$key])) {
  3415. $parent[$key] = array();
  3416. }
  3417. $parent = &$parent[$key];
  3418. }
  3419. // Handle PHP constants.
  3420. if (isset($constants[$value])) {
  3421. $value = $constants[$value];
  3422. }
  3423. // Insert actual value
  3424. if ($last == '') {
  3425. $last = count($parent);
  3426. }
  3427. $parent[$last] = $value;
  3428. }
  3429. }
  3430. return $info;
  3431. }
  3432. /**
  3433. * @return
  3434. * Array of the possible severity levels for log messages.
  3435. *
  3436. * @see watchdog
  3437. */
  3438. function watchdog_severity_levels() {
  3439. return array(
  3440. WATCHDOG_EMERG => t('emergency'),
  3441. WATCHDOG_ALERT => t('alert'),
  3442. WATCHDOG_CRITICAL => t('critical'),
  3443. WATCHDOG_ERROR => t('error'),
  3444. WATCHDOG_WARNING => t('warning'),
  3445. WATCHDOG_NOTICE => t('notice'),
  3446. WATCHDOG_INFO => t('info'),
  3447. WATCHDOG_DEBUG => t('debug'),
  3448. );
  3449. }
  3450. /**
  3451. * Explode a string of given tags into an array.
  3452. *
  3453. * @see drupal_implode_tags()
  3454. */
  3455. function drupal_explode_tags($tags) {
  3456. // This regexp allows the following types of user input:
  3457. // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
  3458. $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
  3459. preg_match_all($regexp, $tags, $matches);
  3460. $typed_tags = array_unique($matches[1]);
  3461. $tags = array();
  3462. foreach ($typed_tags as $tag) {
  3463. // If a user has escaped a term (to demonstrate that it is a group,
  3464. // or includes a comma or quote character), we remove the escape
  3465. // formatting so to save the term into the database as the user intends.
  3466. $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
  3467. if ($tag != "") {
  3468. $tags[] = $tag;
  3469. }
  3470. }
  3471. return $tags;
  3472. }
  3473. /**
  3474. * Implode an array of tags into a string.
  3475. *
  3476. * @see drupal_explode_tags()
  3477. */
  3478. function drupal_implode_tags($tags) {
  3479. $encoded_tags = array();
  3480. foreach ($tags as $tag) {
  3481. // Commas and quotes in tag names are special cases, so encode them.
  3482. if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
  3483. $tag = '"'. str_replace('"', '""', $tag) .'"';
  3484. }
  3485. $encoded_tags[] = $tag;
  3486. }
  3487. return implode(', ', $encoded_tags);
  3488. }
  3489. /**
  3490. * Flush all cached data on the site.
  3491. *
  3492. * Empties cache tables, rebuilds the menu cache and theme registries, and
  3493. * invokes a hook so that other modules' cache data can be cleared as well.
  3494. */
  3495. function drupal_flush_all_caches() {
  3496. // Change query-strings on css/js files to enforce reload for all users.
  3497. _drupal_flush_css_js();
  3498. drupal_clear_css_cache();
  3499. drupal_clear_js_cache();
  3500. // If invoked from update.php, we must not update the theme information in the
  3501. // database, or this will result in all themes being disabled.
  3502. if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
  3503. _system_theme_data();
  3504. }
  3505. else {
  3506. system_theme_data();
  3507. }
  3508. drupal_rebuild_theme_registry();
  3509. menu_rebuild();
  3510. node_types_rebuild();
  3511. // Don't clear cache_form - in-progress form submissions may break.
  3512. // Ordered so clearing the page cache will always be the last action.
  3513. $core = array('cache', 'cache_block', 'cache_filter', 'cache_page');
  3514. $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
  3515. foreach ($cache_tables as $table) {
  3516. cache_clear_all('*', $table, TRUE);
  3517. }
  3518. }
  3519. /**
  3520. * Helper function to change query-strings on css/js files.
  3521. *
  3522. * Changes the character added to all css/js files as dummy query-string,
  3523. * so that all browsers are forced to reload fresh files. We keep
  3524. * 20 characters history (FIFO) to avoid repeats, but only the first
  3525. * (newest) character is actually used on URLs, to keep them short.
  3526. * This is also called from update.php.
  3527. */
  3528. function _drupal_flush_css_js() {
  3529. $string_history = variable_get('css_js_query_string', '00000000000000000000');
  3530. $new_character = $string_history[0];
  3531. // Not including 'q' to allow certain JavaScripts to re-use query string.
  3532. $characters = 'abcdefghijklmnoprstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  3533. while (strpos($string_history, $new_character) !== FALSE) {
  3534. $new_character = $characters[mt_rand(0, strlen($characters) - 1)];
  3535. }
  3536. variable_set('css_js_query_string', $new_character . substr($string_history, 0, 19));
  3537. }

Functions

Nombreorden descendente Descripción
base_path Returns the base URL path of the Drupal installation. At the very least, this will always default to /.
check_file
check_url Prepare a URL for use in an HTML attribute. Strips harmful protocols.
drupal_access_denied Generates a 403 error if the request is not allowed.
drupal_add_css Adds a CSS file to the stylesheet queue.
drupal_add_feed Add a feed URL for the current page.
drupal_add_js Add a JavaScript file, setting or inline code to the page.
drupal_add_link Add a <link> tag to the page's HEAD.
drupal_add_tabledrag Assist in adding the tableDrag JavaScript behavior to a themed table.
drupal_alter Hands off alterable variables to type-specific *_alter implementations.
drupal_attributes Format an attribute string to insert in a tag.
drupal_build_css_cache Aggregate and optimize CSS files, putting them in the files directory.
drupal_build_js_cache Aggregate JS files, putting them in the files directory.
drupal_clear_css_cache Delete all cached CSS files.
drupal_clear_js_cache Delete all cached JS files.
drupal_clear_path_cache Reset the static variable which holds the aliases mapped for this request.
drupal_clone Provide a substitute clone() function for PHP4.
drupal_common_theme Provide theme registration for themes across .inc files.
drupal_cron_cleanup Shutdown function for cron cleanup.
drupal_cron_run Executes a cron run when called
drupal_error_handler Log errors as defined by administrator.
drupal_eval Evaluate a string of PHP code.
drupal_explode_tags Explode a string of given tags into an array.
drupal_final_markup Make any final alterations to the rendered xhtml.
drupal_flush_all_caches Flush all cached data on the site.
drupal_get_breadcrumb Get the breadcrumb trail for the current page.
drupal_get_content Get assigned content.
drupal_get_css Returns a themed representation of all stylesheets that should be attached to the page.
drupal_get_destination Prepare a destination query string for use in combination with drupal_goto().
drupal_get_feeds Get the feed URLs for the current page.
drupal_get_headers Get the HTTP response headers for the current page.
drupal_get_html_head Retrieve output to be displayed in the head tag of the HTML page.
drupal_get_js Returns a themed presentation of all JavaScript code for the current page.
drupal_get_path Returns the path to a system item (module, theme, etc.).
drupal_get_private_key Ensure the private key variable used to generate tokens is set.
drupal_get_schema Get the schema definition of a table, or the whole database schema.
drupal_get_schema_unprocessed Returns the unprocessed and unaltered version of a module's schema.
drupal_get_token Generate a token based on $value, the current user session and private key.
drupal_goto Send the user to a different Drupal page.
drupal_http_request Perform an HTTP request.
drupal_implode_tags Implode an array of tags into a string.
drupal_install_schema Create all tables that a module defines in its hook_schema().
drupal_json Return data in JSON format.
drupal_load_stylesheet Loads the stylesheet and resolves all @import commands.
drupal_map_assoc Form an associative array from a linear array.
drupal_not_found Generates a 404 error if the request can not be handled.
drupal_page_footer Perform end-of-request tasks.
drupal_parse_info_file Parse Drupal info file format.
drupal_query_string_encode Parse an array into a valid urlencoded query string.
drupal_render Renders HTML given a structured array tree.
drupal_schema_fields_sql Retrieve a list of fields from a table schema. The list is suitable for use in a SQL query.
drupal_set_breadcrumb Set the breadcrumb trail for the current page.
drupal_set_content Set content for a specified region.
drupal_set_header Set an HTTP response header for the current page.
drupal_set_html_head Add output to the head tag of the HTML page.
drupal_site_offline Generates a site off-line message.
drupal_system_listing Return an array of system file objects.
drupal_to_js Converts a PHP variable into its Javascript equivalent.
drupal_uninstall_schema Remove all tables that a module defines in its hook_schema().
drupal_urlencode Wrapper around urlencode() which avoids Apache quirks.
drupal_valid_token Validate a token based on $value, the current user session and private key.
drupal_write_record Save a record to the database based upon the schema.
element_child Check if the key is a child.
element_children Get keys of a structured array tree element that are not properties (i.e., do not begin with '#').
element_properties Get properties of a structured array element. Properties begin with '#'.
element_property Check if the key is a property.
element_sort Function used by uasort to sort structured arrays by weight.
fix_gpc_magic Fix double-escaping problems caused by "magic quotes" in some PHP installations.
flood_is_allowed Check if the current visitor (hostname/IP) is allowed to proceed with the specified event.
flood_register_event Register an event for the current visitor (hostname/IP) to the flood control mechanism.
format_date Format a date with the given configured format or a custom format string.
format_interval Format a time interval with the requested granularity.
format_plural Format a string containing a count of items.
format_rss_channel Formats an RSS channel.
format_rss_item Format a single RSS item.
format_size Generate a string representation for the given byte count.
format_xml_elements Format XML elements.
l Formats an internal or external URL link as an HTML anchor tag.
page_set_cache Store the current page in the cache.
parse_size Parse a given byte count.
t Translate strings to the page language or a given language.
url Generates an internal or external URL.
valid_email_address Verifies the syntax of the given e-mail address.
valid_url Verify the syntax of the given URL.
watchdog_severity_levels
xmlrpc Performs one or more XML-RPC request(s).
_drupal_bootstrap_full
_drupal_build_css_path Helper function for drupal_build_css_cache().
_drupal_flush_css_js Helper function to change query-strings on css/js files.
_drupal_initialize_schema Fill in required default values for table definitions returned by hook_schema().
_drupal_load_stylesheet Loads stylesheets recursively and returns contents with corrected paths.
_fix_gpc_magic
_fix_gpc_magic_files Helper function to strip slashes from $_FILES skipping over the tmp_name keys since PHP generates single backslashes for file paths on Windows systems.
_process_comment Process comment blocks.

Constants

Nombreorden descendente Descripción
HTTP_REQUEST_TIMEOUT Error code indicating that the request made by drupal_http_request() exceeded the specified timeout.
SAVED_DELETED Return status for saving which deleted an existing item.
SAVED_NEW Return status for saving which involved creating a new item.
SAVED_UPDATED Return status for saving which involved an update to an existing item.