source: sipes/cord/includes/common.inc @ a149f73

stableversion-3.0
Last change on this file since a149f73 was 6627152, checked in by José Gregorio Puentes <jpuentes@…>, 8 años ago

se actualizo el cord

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