PageRenderTime 77ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 1ms

/includes/common.inc

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