~ubuntu-branches/ubuntu/oneiric/drupal5/oneiric

« back to all changes in this revision

Viewing changes to includes/common.inc

  • Committer: Bazaar Package Importer
  • Author(s): Luigi Gangitano
  • Date: 2007-03-10 20:04:24 UTC
  • Revision ID: james.westby@ubuntu.com-20070310200424-w6v3crmyowlx2zsq
Tags: upstream-5.1
ImportĀ upstreamĀ versionĀ 5.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<?php
 
2
// $Id: common.inc,v 1.611 2007/01/10 23:30:07 unconed Exp $
 
3
 
 
4
/**
 
5
 * @file
 
6
 * Common functions that many Drupal modules will need to reference.
 
7
 *
 
8
 * The functions that are critical and need to be available even when serving
 
9
 * a cached page are instead located in bootstrap.inc.
 
10
 */
 
11
 
 
12
/**
 
13
 * Return status for saving which involved creating a new item.
 
14
 */
 
15
define('SAVED_NEW', 1);
 
16
 
 
17
/**
 
18
 * Return status for saving which involved an update to an existing item.
 
19
 */
 
20
define('SAVED_UPDATED', 2);
 
21
 
 
22
/**
 
23
 * Return status for saving which deleted an existing item.
 
24
 */
 
25
define('SAVED_DELETED', 3);
 
26
 
 
27
/**
 
28
 * Set content for a specified region.
 
29
 *
 
30
 * @param $region
 
31
 *   Page region the content is assigned to.
 
32
 *
 
33
 * @param $data
 
34
 *   Content to be set.
 
35
 */
 
36
function drupal_set_content($region = NULL, $data = NULL) {
 
37
  static $content = array();
 
38
 
 
39
  if (!is_null($region) && !is_null($data)) {
 
40
    $content[$region][] = $data;
 
41
  }
 
42
  return $content;
 
43
}
 
44
 
 
45
/**
 
46
 * Get assigned content.
 
47
 *
 
48
 * @param $region
 
49
 *   A specified region to fetch content for. If NULL, all regions will be returned.
 
50
 *
 
51
 * @param $delimiter
 
52
 *   Content to be inserted between exploded array elements.
 
53
 */
 
54
function drupal_get_content($region = NULL, $delimiter = ' ') {
 
55
  $content = drupal_set_content();
 
56
  if (isset($region)) {
 
57
    if (isset($content[$region]) && is_array($content[$region])) {
 
58
      return implode($delimiter, $content[$region]);
 
59
    }
 
60
  }
 
61
  else {
 
62
    foreach (array_keys($content) as $region) {
 
63
      if (is_array($content[$region])) {
 
64
        $content[$region] = implode($delimiter, $content[$region]);
 
65
      }
 
66
    }
 
67
    return $content;
 
68
  }
 
69
}
 
70
 
 
71
/**
 
72
 * Set the breadcrumb trail for the current page.
 
73
 *
 
74
 * @param $breadcrumb
 
75
 *   Array of links, starting with "home" and proceeding up to but not including
 
76
 *   the current page.
 
77
 */
 
78
function drupal_set_breadcrumb($breadcrumb = NULL) {
 
79
  static $stored_breadcrumb;
 
80
 
 
81
  if (!is_null($breadcrumb)) {
 
82
    $stored_breadcrumb = $breadcrumb;
 
83
  }
 
84
  return $stored_breadcrumb;
 
85
}
 
86
 
 
87
/**
 
88
 * Get the breadcrumb trail for the current page.
 
89
 */
 
90
function drupal_get_breadcrumb() {
 
91
  $breadcrumb = drupal_set_breadcrumb();
 
92
 
 
93
  if (is_null($breadcrumb)) {
 
94
    $breadcrumb = menu_get_active_breadcrumb();
 
95
  }
 
96
 
 
97
  return $breadcrumb;
 
98
}
 
99
 
 
100
/**
 
101
 * Add output to the head tag of the HTML page.
 
102
 * This function can be called as long the headers aren't sent.
 
103
 */
 
104
function drupal_set_html_head($data = NULL) {
 
105
  static $stored_head = '';
 
106
 
 
107
  if (!is_null($data)) {
 
108
    $stored_head .= $data ."\n";
 
109
  }
 
110
  return $stored_head;
 
111
}
 
112
 
 
113
/**
 
114
 * Retrieve output to be displayed in the head tag of the HTML page.
 
115
 */
 
116
function drupal_get_html_head() {
 
117
  $output = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
 
118
  return $output . drupal_set_html_head();
 
119
}
 
120
 
 
121
/**
 
122
 * Reset the static variable which holds the aliases mapped for this request.
 
123
 */
 
124
function drupal_clear_path_cache() {
 
125
  drupal_lookup_path('wipe');
 
126
}
 
127
 
 
128
/**
 
129
 * Set an HTTP response header for the current page.
 
130
 *
 
131
 * Note: when sending a Content-Type header, always include a 'charset' type
 
132
 * too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
 
133
 */
 
134
function drupal_set_header($header = NULL) {
 
135
  // We use an array to guarantee there are no leading or trailing delimiters.
 
136
  // Otherwise, header('') could get called when serving the page later, which
 
137
  // ends HTTP headers prematurely on some PHP versions.
 
138
  static $stored_headers = array();
 
139
 
 
140
  if (strlen($header)) {
 
141
    header($header);
 
142
    $stored_headers[] = $header;
 
143
  }
 
144
  return implode("\n", $stored_headers);
 
145
}
 
146
 
 
147
/**
 
148
 * Get the HTTP response headers for the current page.
 
149
 */
 
150
function drupal_get_headers() {
 
151
  return drupal_set_header();
 
152
}
 
153
 
 
154
/**
 
155
 * Add a feed URL for the current page.
 
156
 *
 
157
 * @param $url
 
158
 *   The url for the feed
 
159
 * @param $title
 
160
 *   The title of the feed
 
161
 */
 
162
function drupal_add_feed($url = NULL, $title = '') {
 
163
  static $stored_feed_links = array();
 
164
 
 
165
  if (!is_null($url)) {
 
166
    $stored_feed_links[$url] = theme('feed_icon', $url);
 
167
 
 
168
    drupal_add_link(array('rel' => 'alternate',
 
169
                          'type' => 'application/rss+xml',
 
170
                          'title' => $title,
 
171
                          'href' => $url));
 
172
  }
 
173
  return $stored_feed_links;
 
174
}
 
175
 
 
176
/**
 
177
 * Get the feed URLs for the current page.
 
178
 *
 
179
 * @param $delimiter
 
180
 *   The delimiter to split feeds by
 
181
 */
 
182
function drupal_get_feeds($delimiter = "\n") {
 
183
  $feeds = drupal_add_feed();
 
184
  return implode($feeds, $delimiter);
 
185
}
 
186
 
 
187
/**
 
188
 * @name HTTP handling
 
189
 * @{
 
190
 * Functions to properly handle HTTP responses.
 
191
 */
 
192
 
 
193
/**
 
194
 * Parse an array into a valid urlencoded query string.
 
195
 *
 
196
 * @param $query
 
197
 *   The array to be processed e.g. $_GET
 
198
 * @param $exclude
 
199
 *   The array filled with keys to be excluded. Use parent[child] to exclude nested items.
 
200
 * @param $urlencode
 
201
 *   If TRUE, the keys and values are both urlencoded.
 
202
 * @param $parent
 
203
 *   Should not be passed, only used in recursive calls
 
204
 * @return
 
205
 *   urlencoded string which can be appended to/as the URL query string
 
206
 */
 
207
function drupal_query_string_encode($query, $exclude = array(), $parent = '') {
 
208
  $params = array();
 
209
 
 
210
  foreach ($query as $key => $value) {
 
211
    $key = drupal_urlencode($key);
 
212
    if ($parent) {
 
213
      $key = $parent .'['. $key .']';
 
214
    }
 
215
 
 
216
    if (in_array($key, $exclude)) {
 
217
      continue;
 
218
    }
 
219
 
 
220
    if (is_array($value)) {
 
221
      $params[] = drupal_query_string_encode($value, $exclude, $key);
 
222
    }
 
223
    else {
 
224
      $params[] = $key .'='. drupal_urlencode($value);
 
225
    }
 
226
  }
 
227
 
 
228
  return implode('&', $params);
 
229
}
 
230
 
 
231
/**
 
232
 * Prepare a destination query string for use in combination with
 
233
 * drupal_goto(). Used to direct the user back to the referring page
 
234
 * after completing a form. By default the current URL is returned.
 
235
 * If a destination exists in the previous request, that destination
 
236
 * is returned. As such, a destination can persist across multiple
 
237
 * pages.
 
238
 *
 
239
 * @see drupal_goto()
 
240
 */
 
241
function drupal_get_destination() {
 
242
  if (isset($_REQUEST['destination'])) {
 
243
    return 'destination='. urlencode($_REQUEST['destination']);
 
244
  }
 
245
  else {
 
246
    // Use $_GET here to retrieve the original path in source form.
 
247
    $path = isset($_GET['q']) ? $_GET['q'] : '';
 
248
    $query = drupal_query_string_encode($_GET, array('q'));
 
249
    if ($query != '') {
 
250
      $path .= '?'. $query;
 
251
    }
 
252
    return 'destination='. urlencode($path);
 
253
  }
 
254
}
 
255
 
 
256
/**
 
257
 * Send the user to a different Drupal page.
 
258
 *
 
259
 * This issues an on-site HTTP redirect. The function makes sure the redirected
 
260
 * URL is formatted correctly.
 
261
 *
 
262
 * Usually the redirected URL is constructed from this function's input
 
263
 * parameters. However you may override that behavior by setting a
 
264
 * <em>destination</em> in either the $_REQUEST-array (i.e. by using
 
265
 * the query string of an URI) or the $_REQUEST['edit']-array (i.e. by
 
266
 * using a hidden form field). This is used to direct the user back to
 
267
 * the proper page after completing a form. For example, after editing
 
268
 * a post on the 'admin/content/node'-page or after having logged on using the
 
269
 * 'user login'-block in a sidebar. The function drupal_get_destination()
 
270
 * can be used to help set the destination URL.
 
271
 *
 
272
 * It is advised to use drupal_goto() instead of PHP's header(), because
 
273
 * drupal_goto() will append the user's session ID to the URI when PHP is
 
274
 * compiled with "--enable-trans-sid".
 
275
 *
 
276
 * This function ends the request; use it rather than a print theme('page')
 
277
 * statement in your menu callback.
 
278
 *
 
279
 * @param $path
 
280
 *   A Drupal path or a full URL.
 
281
 * @param $query
 
282
 *   The query string component, if any.
 
283
 * @param $fragment
 
284
 *   The destination fragment identifier (named anchor).
 
285
 * @param $http_response_code
 
286
 *   Valid values for an actual "goto" as per RFC 2616 section 10.3 are:
 
287
 *   - 301 Moved Permanently (the recommended value for most redirects)
 
288
 *   - 302 Found (default in Drupal and PHP, sometimes used for spamming search
 
289
 *         engines)
 
290
 *   - 303 See Other
 
291
 *   - 304 Not Modified
 
292
 *   - 305 Use Proxy
 
293
 *   - 307 Temporary Redirect (an alternative to "503 Site Down for Maintenance")
 
294
 *   Note: Other values are defined by RFC 2616, but are rarely used and poorly
 
295
 *         supported.
 
296
 * @see drupal_get_destination()
 
297
 */
 
298
function drupal_goto($path = '', $query = NULL, $fragment = NULL, $http_response_code = 302) {
 
299
  if (isset($_REQUEST['destination'])) {
 
300
    extract(parse_url(urldecode($_REQUEST['destination'])));
 
301
  }
 
302
  else if (isset($_REQUEST['edit']['destination'])) {
 
303
    extract(parse_url(urldecode($_REQUEST['edit']['destination'])));
 
304
  }
 
305
 
 
306
  $url = url($path, $query, $fragment, TRUE);
 
307
 
 
308
  // Before the redirect, allow modules to react to the end of the page request.
 
309
  module_invoke_all('exit', $url);
 
310
 
 
311
  header('Location: '. $url, TRUE, $http_response_code);
 
312
 
 
313
  // The "Location" header sends a REDIRECT status code to the http
 
314
  // daemon. In some cases this can go wrong, so we make sure none
 
315
  // of the code below the drupal_goto() call gets executed when we redirect.
 
316
  exit();
 
317
}
 
318
 
 
319
/**
 
320
 * Generates a site off-line message
 
321
 */
 
322
function drupal_site_offline() {
 
323
  drupal_set_header('HTTP/1.1 503 Service unavailable');
 
324
  drupal_set_title(t('Site off-line'));
 
325
  print theme('maintenance_page', filter_xss_admin(variable_get('site_offline_message',
 
326
    t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal'))))));
 
327
}
 
328
 
 
329
/**
 
330
 * Generates a 404 error if the request can not be handled.
 
331
 */
 
332
function drupal_not_found() {
 
333
  drupal_set_header('HTTP/1.1 404 Not Found');
 
334
 
 
335
  watchdog('page not found', check_plain($_GET['q']), WATCHDOG_WARNING);
 
336
 
 
337
  // Keep old path for reference
 
338
  if (!isset($_REQUEST['destination'])) {
 
339
    $_REQUEST['destination'] = $_GET['q'];
 
340
  }
 
341
 
 
342
  $path = drupal_get_normal_path(variable_get('site_404', ''));
 
343
  if ($path && $path != $_GET['q']) {
 
344
    menu_set_active_item($path);
 
345
    $return = menu_execute_active_handler();
 
346
  }
 
347
  else {
 
348
    // Redirect to a non-existent menu item to make possible tabs disappear.
 
349
    menu_set_active_item('');
 
350
  }
 
351
 
 
352
  if (empty($return)) {
 
353
    drupal_set_title(t('Page not found'));
 
354
  }
 
355
  // To conserve CPU and bandwidth, omit the blocks
 
356
  print theme('page', $return, FALSE);
 
357
}
 
358
 
 
359
/**
 
360
 * Generates a 403 error if the request is not allowed.
 
361
 */
 
362
function drupal_access_denied() {
 
363
  drupal_set_header('HTTP/1.1 403 Forbidden');
 
364
  watchdog('access denied', check_plain($_GET['q']), WATCHDOG_WARNING);
 
365
 
 
366
// Keep old path for reference
 
367
  if (!isset($_REQUEST['destination'])) {
 
368
    $_REQUEST['destination'] = $_GET['q'];
 
369
  }
 
370
 
 
371
  $path = drupal_get_normal_path(variable_get('site_403', ''));
 
372
  if ($path && $path != $_GET['q']) {
 
373
    menu_set_active_item($path);
 
374
    $return = menu_execute_active_handler();
 
375
  }
 
376
  else {
 
377
    // Redirect to a non-existent menu item to make possible tabs disappear.
 
378
    menu_set_active_item('');
 
379
  }
 
380
 
 
381
  if (empty($return)) {
 
382
    drupal_set_title(t('Access denied'));
 
383
    $return = t('You are not authorized to access this page.');
 
384
  }
 
385
  print theme('page', $return);
 
386
}
 
387
 
 
388
/**
 
389
 * Perform an HTTP request.
 
390
 *
 
391
 * This is a flexible and powerful HTTP client implementation. Correctly handles
 
392
 * GET, POST, PUT or any other HTTP requests. Handles redirects.
 
393
 *
 
394
 * @param $url
 
395
 *   A string containing a fully qualified URI.
 
396
 * @param $headers
 
397
 *   An array containing an HTTP header => value pair.
 
398
 * @param $method
 
399
 *   A string defining the HTTP request to use.
 
400
 * @param $data
 
401
 *   A string containing data to include in the request.
 
402
 * @param $retry
 
403
 *   An integer representing how many times to retry the request in case of a
 
404
 *   redirect.
 
405
 * @return
 
406
 *   An object containing the HTTP request headers, response code, headers,
 
407
 *   data, and redirect status.
 
408
 */
 
409
function drupal_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) {
 
410
  $result = new stdClass();
 
411
 
 
412
  // Parse the URL, and make sure we can handle the schema.
 
413
  $uri = parse_url($url);
 
414
  switch ($uri['scheme']) {
 
415
    case 'http':
 
416
      $port = isset($uri['port']) ? $uri['port'] : 80;
 
417
      $host = $uri['host'] . ($port != 80 ? ':'. $port : '');
 
418
      $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
 
419
      break;
 
420
    case 'https':
 
421
      // Note: Only works for PHP 4.3 compiled with OpenSSL.
 
422
      $port = isset($uri['port']) ? $uri['port'] : 443;
 
423
      $host = $uri['host'] . ($port != 443 ? ':'. $port : '');
 
424
      $fp = @fsockopen('ssl://'. $uri['host'], $port, $errno, $errstr, 20);
 
425
      break;
 
426
    default:
 
427
      $result->error = 'invalid schema '. $uri['scheme'];
 
428
      return $result;
 
429
  }
 
430
 
 
431
  // Make sure the socket opened properly.
 
432
  if (!$fp) {
 
433
    $result->error = trim($errno .' '. $errstr);
 
434
    return $result;
 
435
  }
 
436
 
 
437
  // Construct the path to act on.
 
438
  $path = isset($uri['path']) ? $uri['path'] : '/';
 
439
  if (isset($uri['query'])) {
 
440
    $path .= '?'. $uri['query'];
 
441
  }
 
442
 
 
443
  // Create HTTP request.
 
444
  $defaults = array(
 
445
    // RFC 2616: "non-standard ports MUST, default ports MAY be included".
 
446
    // We don't add the port to prevent from breaking rewrite rules checking
 
447
    // the host that do not take into account the port number.
 
448
    'Host' => "Host: $host",
 
449
    'User-Agent' => 'User-Agent: Drupal (+http://drupal.org/)',
 
450
    'Content-Length' => 'Content-Length: '. strlen($data)
 
451
  );
 
452
 
 
453
  foreach ($headers as $header => $value) {
 
454
    $defaults[$header] = $header .': '. $value;
 
455
  }
 
456
 
 
457
  $request = $method .' '. $path ." HTTP/1.0\r\n";
 
458
  $request .= implode("\r\n", $defaults);
 
459
  $request .= "\r\n\r\n";
 
460
  if ($data) {
 
461
    $request .= $data ."\r\n";
 
462
  }
 
463
  $result->request = $request;
 
464
 
 
465
  fwrite($fp, $request);
 
466
 
 
467
  // Fetch response.
 
468
  $response = '';
 
469
  while (!feof($fp) && $chunk = fread($fp, 1024)) {
 
470
    $response .= $chunk;
 
471
  }
 
472
  fclose($fp);
 
473
 
 
474
  // Parse response.
 
475
  list($split, $result->data) = explode("\r\n\r\n", $response, 2);
 
476
  $split = preg_split("/\r\n|\n|\r/", $split);
 
477
 
 
478
  list($protocol, $code, $text) = explode(' ', trim(array_shift($split)), 3);
 
479
  $result->headers = array();
 
480
 
 
481
  // Parse headers.
 
482
  while ($line = trim(array_shift($split))) {
 
483
    list($header, $value) = explode(':', $line, 2);
 
484
    if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
 
485
      // RFC 2109: the Set-Cookie response header comprises the token Set-
 
486
      // Cookie:, followed by a comma-separated list of one or more cookies.
 
487
      $result->headers[$header] .= ','. trim($value);
 
488
    }
 
489
    else {
 
490
      $result->headers[$header] = trim($value);
 
491
    }
 
492
  }
 
493
 
 
494
  $responses = array(
 
495
    100 => 'Continue', 101 => 'Switching Protocols',
 
496
    200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
 
497
    300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
 
498
    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',
 
499
    500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'
 
500
  );
 
501
  // RFC 2616 states that all unknown HTTP codes must be treated the same as
 
502
  // the base code in their class.
 
503
  if (!isset($responses[$code])) {
 
504
    $code = floor($code / 100) * 100;
 
505
  }
 
506
 
 
507
  switch ($code) {
 
508
    case 200: // OK
 
509
    case 304: // Not modified
 
510
      break;
 
511
    case 301: // Moved permanently
 
512
    case 302: // Moved temporarily
 
513
    case 307: // Moved temporarily
 
514
      $location = $result->headers['Location'];
 
515
 
 
516
      if ($retry) {
 
517
        $result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
 
518
        $result->redirect_code = $result->code;
 
519
      }
 
520
      $result->redirect_url = $location;
 
521
 
 
522
      break;
 
523
    default:
 
524
      $result->error = $text;
 
525
  }
 
526
 
 
527
  $result->code = $code;
 
528
  return $result;
 
529
}
 
530
/**
 
531
 * @} End of "HTTP handling".
 
532
 */
 
533
 
 
534
/**
 
535
 * Log errors as defined by administrator
 
536
 * Error levels:
 
537
 *  0 = Log errors to database.
 
538
 *  1 = Log errors to database and to screen.
 
539
 */
 
540
function error_handler($errno, $message, $filename, $line) {
 
541
  // If the @ error suppression operator was used, error_reporting is temporarily set to 0
 
542
  if (error_reporting() == 0) {
 
543
    return;
 
544
  }
 
545
 
 
546
  if ($errno & (E_ALL ^ E_NOTICE)) {
 
547
    $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');
 
548
    $entry = $types[$errno] .': '. $message .' in '. $filename .' on line '. $line .'.';
 
549
 
 
550
    // Force display of error messages in update.php
 
551
    if (variable_get('error_level', 1) == 1 || strstr($_SERVER['PHP_SELF'], 'update.php')) {
 
552
      drupal_set_message($entry, 'error');
 
553
    }
 
554
 
 
555
    watchdog('php', t('%message in %file on line %line.', array('%error' => $types[$errno], '%message' => $message, '%file' => $filename, '%line' => $line)), WATCHDOG_ERROR);
 
556
  }
 
557
}
 
558
 
 
559
function _fix_gpc_magic(&$item) {
 
560
  if (is_array($item)) {
 
561
    array_walk($item, '_fix_gpc_magic');
 
562
  }
 
563
  else {
 
564
    $item = stripslashes($item);
 
565
  }
 
566
}
 
567
 
 
568
/**
 
569
 * Helper function to strip slashes from $_FILES skipping over the tmp_name keys
 
570
 * since PHP generates single backslashes for file paths on Windows systems.
 
571
 *
 
572
 * tmp_name does not have backslashes added see
 
573
 * http://php.net/manual/en/features.file-upload.php#42280
 
574
 */
 
575
function _fix_gpc_magic_files(&$item, $key) {
 
576
  if ($key != 'tmp_name') {
 
577
    if (is_array($item)) {
 
578
      array_walk($item, '_fix_gpc_magic_files');
 
579
    }
 
580
    else {
 
581
      $item = stripslashes($item);
 
582
    }
 
583
  }
 
584
}
 
585
 
 
586
/**
 
587
 * Correct double-escaping problems caused by "magic quotes" in some PHP
 
588
 * installations.
 
589
 */
 
590
function fix_gpc_magic() {
 
591
  static $fixed = FALSE;
 
592
  if (!$fixed && ini_get('magic_quotes_gpc')) {
 
593
    array_walk($_GET, '_fix_gpc_magic');
 
594
    array_walk($_POST, '_fix_gpc_magic');
 
595
    array_walk($_COOKIE, '_fix_gpc_magic');
 
596
    array_walk($_REQUEST, '_fix_gpc_magic');
 
597
    array_walk($_FILES, '_fix_gpc_magic_files');
 
598
    $fixed = TRUE;
 
599
  }
 
600
}
 
601
 
 
602
/**
 
603
 * Initialize the localization system.
 
604
 */
 
605
function locale_initialize() {
 
606
  global $user;
 
607
 
 
608
  if (function_exists('i18n_get_lang')) {
 
609
    return i18n_get_lang();
 
610
  }
 
611
 
 
612
  if (function_exists('locale')) {
 
613
    $languages = locale_supported_languages();
 
614
    $languages = $languages['name'];
 
615
  }
 
616
  else {
 
617
    // Ensure the locale/language is correctly returned, even without locale.module.
 
618
    // Useful for e.g. XML/HTML 'lang' attributes.
 
619
    $languages = array('en' => 'English');
 
620
  }
 
621
  if ($user->uid && isset($languages[$user->language])) {
 
622
    return $user->language;
 
623
  }
 
624
  else {
 
625
    return key($languages);
 
626
  }
 
627
}
 
628
 
 
629
/**
 
630
 * Translate strings to the current locale.
 
631
 *
 
632
 * All human-readable text that will be displayed somewhere within a page should be
 
633
 * run through the t() function.
 
634
 *
 
635
 * Examples:
 
636
 * @code
 
637
 *   if (!$info || !$info['extension']) {
 
638
 *     form_set_error('picture_upload', t('The uploaded file was not an image.'));
 
639
 *   }
 
640
 *
 
641
 *   $form['submit'] = array(
 
642
 *     '#type' => 'submit',
 
643
 *     '#value' => t('Log in'),
 
644
 *   );
 
645
 * @endcode
 
646
 *
 
647
 * Any text within t() can be extracted by translators and changed into
 
648
 * the equivalent text in their native language.
 
649
 *
 
650
 * Special variables called "placeholders" are used to signal dynamic
 
651
 * information in a string which should not be translated. Placeholders
 
652
 * can also be used for text that may change from time to time
 
653
 * (such as link paths) to be changed without requiring updates to translations.
 
654
 *
 
655
 * For example:
 
656
 * @code
 
657
 *   $output = t('There are currently %members and %visitors online.', array(
 
658
 *     '%members' => format_plural($total_users, '1 user', '@count users'),
 
659
 *     '%visitors' => format_plural($guests->count, '1 guest', '@count guests')));
 
660
 * @endcode
 
661
 *
 
662
 * There are three styles of placeholders:
 
663
 * - !variable, which indicates that the text should be inserted as-is. This is
 
664
 *   useful for inserting variables into things like e-mail.
 
665
 *   @code
 
666
 *     $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", NULL, NULL, TRUE)));
 
667
 *   @endcode
 
668
 *
 
669
 * - @variable, which indicates that the text should be run through check_plain,
 
670
 *   to strip out HTML characters. Use this for any output that's displayed within
 
671
 *   a Drupal page.
 
672
 *   @code
 
673
 *     drupal_set_title($title = t("@name's blog", array('@name' => $account->name)));
 
674
 *   @endcode
 
675
 *
 
676
 * - %variable, which indicates that the string should be highlighted with
 
677
 *   theme_placeholder() which shows up by default as <em>emphasized</em>.
 
678
 *   @code
 
679
 *     watchdog('mail', t('%name-from sent %name-to an e-mail.', array('%name-from' => $user->name, '%name-to' => $account->name)));
 
680
 *   @endcode
 
681
 *
 
682
 * When using t(), try to put entire sentences and strings in one t() call.
 
683
 * This makes it easier for translators, as it provides context as to what
 
684
 * each word refers to. HTML markup within translation strings is allowed,
 
685
 * but should be avoided if possible. The exception is embedded links; link
 
686
 * titles add additional context for translators so should be kept in the main
 
687
 * string.
 
688
 *
 
689
 * Here is an example of an incorrect use if t():
 
690
 * @code
 
691
 *   $output .= t('<p>Go to the @contact-page.</p>', array('@contact-page' => l(t('contact page'), 'contact')));
 
692
 * @endcode
 
693
 *
 
694
 * Here is an example of t() used correctly:
 
695
 * @code
 
696
 *   $output .= '<p>'. t('Go to the <a href="@contact-page">contact page</a>.', array('@contact-page' => url('contact'))) .'</p>';
 
697
 * @endcode
 
698
 *
 
699
 * Also avoid escaping quotation marks wherever possible.
 
700
 *
 
701
 * Incorrect:
 
702
 * @code
 
703
 *   $output .= t('Don\'t click me.');
 
704
 * @endcode
 
705
 *
 
706
 * Correct:
 
707
 * @code
 
708
 *   $output .= t("Don't click me.");
 
709
 * @endcode
 
710
 *
 
711
 * @param $string
 
712
 *   A string containing the English string to translate.
 
713
 * @param $args
 
714
 *   An associative array of replacements to make after translation. Incidences
 
715
 *   of any key in this array are replaced with the corresponding value.
 
716
 *   Based on the first character of the key, the value is escaped and/or themed:
 
717
 *    - !variable: inserted as is
 
718
 *    - @variable: escape plain text to HTML (check_plain)
 
719
 *    - %variable: escape text and theme as a placeholder for user-submitted
 
720
 *      content (check_plain + theme_placeholder)
 
721
 * @return
 
722
 *   The translated string.
 
723
 */
 
724
function t($string, $args = 0) {
 
725
  global $locale;
 
726
  if (function_exists('locale') && $locale != 'en') {
 
727
    $string = locale($string);
 
728
  }
 
729
  if (!$args) {
 
730
    return $string;
 
731
  }
 
732
  else {
 
733
    // Transform arguments before inserting them
 
734
    foreach ($args as $key => $value) {
 
735
      switch ($key[0]) {
 
736
        // Escaped only
 
737
        case '@':
 
738
          $args[$key] = check_plain($value);
 
739
        break;
 
740
        // Escaped and placeholder
 
741
        case '%':
 
742
        default:
 
743
          $args[$key] = theme('placeholder', $value);
 
744
          break;
 
745
        // Pass-through
 
746
        case '!':
 
747
      }
 
748
    }
 
749
    return strtr($string, $args);
 
750
  }
 
751
}
 
752
 
 
753
/**
 
754
 * @defgroup validation Input validation
 
755
 * @{
 
756
 * Functions to validate user input.
 
757
 */
 
758
 
 
759
/**
 
760
 * Verify the syntax of the given e-mail address.
 
761
 *
 
762
 * Empty e-mail addresses are allowed. See RFC 2822 for details.
 
763
 *
 
764
 * @param $mail
 
765
 *   A string containing an e-mail address.
 
766
 * @return
 
767
 *   TRUE if the address is in a valid format.
 
768
 */
 
769
function valid_email_address($mail) {
 
770
  $user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
 
771
  $domain = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+';
 
772
  $ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
 
773
  $ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';
 
774
 
 
775
  return preg_match("/^$user@($domain|(\[($ipv4|$ipv6)\]))$/", $mail);
 
776
}
 
777
 
 
778
/**
 
779
 * Verify the syntax of the given URL.
 
780
 *
 
781
 * This function should only be used on actual URLs. It should not be used for
 
782
 * Drupal menu paths, which can contain arbitrary characters.
 
783
 *
 
784
 * @param $url
 
785
 *   The URL to verify.
 
786
 * @param $absolute
 
787
 *   Whether the URL is absolute (beginning with a scheme such as "http:").
 
788
 * @return
 
789
 *   TRUE if the URL is in a valid format.
 
790
 */
 
791
function valid_url($url, $absolute = FALSE) {
 
792
  $allowed_characters = '[a-z0-9\/:_\-_\.\?\$,;~=#&%\+]';
 
793
  if ($absolute) {
 
794
    return preg_match("/^(http|https|ftp):\/\/". $allowed_characters ."+$/i", $url);
 
795
  }
 
796
  else {
 
797
    return preg_match("/^". $allowed_characters ."+$/i", $url);
 
798
  }
 
799
}
 
800
 
 
801
/**
 
802
 * Register an event for the current visitor (hostname/IP) to the flood control mechanism.
 
803
 *
 
804
 * @param $name
 
805
 *   The name of the event.
 
806
 */
 
807
function flood_register_event($name) {
 
808
  db_query("INSERT INTO {flood} (event, hostname, timestamp) VALUES ('%s', '%s', %d)", $name, $_SERVER['REMOTE_ADDR'], time());
 
809
}
 
810
 
 
811
/**
 
812
 * Check if the current visitor (hostname/IP) is allowed to proceed with the specified event.
 
813
 * The user is allowed to proceed if he did not trigger the specified event more than
 
814
 * $threshold times per hour.
 
815
 *
 
816
 * @param $name
 
817
 *   The name of the event.
 
818
 * @param $number
 
819
 *   The maximum number of the specified event per hour (per visitor).
 
820
 * @return
 
821
 *   True if the user did not exceed the hourly threshold. False otherwise.
 
822
 */
 
823
function flood_is_allowed($name, $threshold) {
 
824
  $number = db_num_rows(db_query("SELECT event FROM {flood} WHERE event = '%s' AND hostname = '%s' AND timestamp > %d", $name, $_SERVER['REMOTE_ADDR'], time() - 3600));
 
825
  return ($number < $threshold ? TRUE : FALSE);
 
826
}
 
827
 
 
828
function check_file($filename) {
 
829
  return is_uploaded_file($filename);
 
830
}
 
831
 
 
832
/**
 
833
 * Prepare a URL for use in an HTML attribute. Strips harmful protocols.
 
834
 *
 
835
 */
 
836
function check_url($uri) {
 
837
  return filter_xss_bad_protocol($uri, FALSE);
 
838
}
 
839
 
 
840
/**
 
841
 * @defgroup format Formatting
 
842
 * @{
 
843
 * Functions to format numbers, strings, dates, etc.
 
844
 */
 
845
 
 
846
/**
 
847
 * Formats an RSS channel.
 
848
 *
 
849
 * Arbitrary elements may be added using the $args associative array.
 
850
 */
 
851
function format_rss_channel($title, $link, $description, $items, $language = 'en', $args = array()) {
 
852
  // arbitrary elements may be added using the $args associative array
 
853
 
 
854
  $output = "<channel>\n";
 
855
  $output .= ' <title>'. check_plain($title) ."</title>\n";
 
856
  $output .= ' <link>'. check_url($link) ."</link>\n";
 
857
 
 
858
  // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
 
859
  // We strip all HTML tags, but need to prevent double encoding from properly
 
860
  // escaped source data (such as &amp becoming &amp;amp;).
 
861
  $output .= ' <description>'. check_plain(decode_entities(strip_tags($description))) ."</description>\n";
 
862
  $output .= ' <language>'. check_plain($language) ."</language>\n";
 
863
  $output .= format_xml_elements($args);
 
864
  $output .= $items;
 
865
  $output .= "</channel>\n";
 
866
 
 
867
  return $output;
 
868
}
 
869
 
 
870
/**
 
871
 * Format a single RSS item.
 
872
 *
 
873
 * Arbitrary elements may be added using the $args associative array.
 
874
 */
 
875
function format_rss_item($title, $link, $description, $args = array()) {
 
876
  $output = "<item>\n";
 
877
  $output .= ' <title>'. check_plain($title) ."</title>\n";
 
878
  $output .= ' <link>'. check_url($link) ."</link>\n";
 
879
  $output .= ' <description>'. check_plain($description) ."</description>\n";
 
880
  $output .= format_xml_elements($args);
 
881
  $output .= "</item>\n";
 
882
 
 
883
  return $output;
 
884
}
 
885
 
 
886
/**
 
887
 * Format XML elements.
 
888
 *
 
889
 * @param $array
 
890
 *   An array where each item represent an element and is either a:
 
891
 *   - (key => value) pair (<key>value</key>)
 
892
 *   - Associative array with fields:
 
893
 *     - 'key': element name
 
894
 *     - 'value': element contents
 
895
 *     - 'attributes': associative array of element attributes
 
896
 *
 
897
 * In both cases, 'value' can be a simple string, or it can be another array
 
898
 * with the same format as $array itself for nesting.
 
899
 */
 
900
function format_xml_elements($array) {
 
901
  foreach ($array as $key => $value) {
 
902
    if (is_numeric($key)) {
 
903
      if ($value['key']) {
 
904
        $output .= ' <'. $value['key'];
 
905
        if (isset($value['attributes']) && is_array($value['attributes'])) {
 
906
          $output .= drupal_attributes($value['attributes']);
 
907
        }
 
908
 
 
909
        if ($value['value'] != '') {
 
910
          $output .= '>'. (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) .'</'. $value['key'] .">\n";
 
911
        }
 
912
        else {
 
913
          $output .= " />\n";
 
914
        }
 
915
      }
 
916
    }
 
917
    else {
 
918
      $output .= ' <'. $key .'>'. (is_array($value) ? format_xml_elements($value) : check_plain($value)) ."</$key>\n";
 
919
    }
 
920
  }
 
921
  return $output;
 
922
}
 
923
 
 
924
/**
 
925
 * Format a string containing a count of items.
 
926
 *
 
927
 * This function ensures that the string is pluralized correctly. Since t() is
 
928
 * called by this function, make sure not to pass already-localized strings to it.
 
929
 *
 
930
 * @param $count
 
931
 *   The item count to display.
 
932
 * @param $singular
 
933
 *   The string for the singular case. Please make sure it is clear this is
 
934
 *   singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
 
935
 * @param $plural
 
936
 *   The string for the plural case. Please make sure it is clear this is plural,
 
937
 *   to ease translation. Use @count in place of the item count, as in "@count
 
938
 *   new comments".
 
939
 * @return
 
940
 *   A translated string.
 
941
 */
 
942
function format_plural($count, $singular, $plural) {
 
943
  if ($count == 1) return t($singular, array("@count" => $count));
 
944
 
 
945
  // get the plural index through the gettext formula
 
946
  $index = (function_exists('locale_get_plural')) ? locale_get_plural($count) : -1;
 
947
  if ($index < 0) { // backward compatibility
 
948
    return t($plural, array("@count" => $count));
 
949
  }
 
950
  else {
 
951
    switch ($index) {
 
952
      case "0":
 
953
        return t($singular, array("@count" => $count));
 
954
      case "1":
 
955
        return t($plural, array("@count" => $count));
 
956
      default:
 
957
        return t(strtr($plural, array("@count" => '@count['. $index .']')), array('@count['. $index .']' => $count));
 
958
    }
 
959
  }
 
960
}
 
961
 
 
962
/**
 
963
 * Parse a given byte count.
 
964
 *
 
965
 * @param $size
 
966
 *   The size expressed as a number of bytes with optional SI size and unit
 
967
 *   suffix (e.g. 2, 3K, 5MB, 10G).
 
968
 * @return
 
969
 *   An integer representation of the size.
 
970
 */
 
971
function parse_size($size) {
 
972
  $suffixes = array(
 
973
    '' => 1,
 
974
    'k' => 1024,
 
975
    'm' => 1048576, // 1024 * 1024
 
976
    'g' => 1073741824, // 1024 * 1024 * 1024
 
977
  );
 
978
  if (preg_match('/([0-9]+)\s*(k|m|g)?(b?(ytes?)?)/i', $size, $match)) {
 
979
    return $match[1] * $suffixes[drupal_strtolower($match[2])];
 
980
  }
 
981
}
 
982
 
 
983
/**
 
984
 * Generate a string representation for the given byte count.
 
985
 *
 
986
 * @param $size
 
987
 *   The size in bytes.
 
988
 * @return
 
989
 *   A translated string representation of the size.
 
990
 */
 
991
function format_size($size) {
 
992
  if ($size < 1024) {
 
993
    return format_plural($size, '1 byte', '@count bytes');
 
994
  }
 
995
  else {
 
996
    $size = round($size / 1024, 2);
 
997
    $suffix = t('KB');
 
998
    if ($size >= 1024) {
 
999
      $size = round($size / 1024, 2);
 
1000
      $suffix = t('MB');
 
1001
    }
 
1002
    return t('@size @suffix', array('@size' => $size, '@suffix' => $suffix));
 
1003
  }
 
1004
}
 
1005
 
 
1006
/**
 
1007
 * Format a time interval with the requested granularity.
 
1008
 *
 
1009
 * @param $timestamp
 
1010
 *   The length of the interval in seconds.
 
1011
 * @param $granularity
 
1012
 *   How many different units to display in the string.
 
1013
 * @return
 
1014
 *   A translated string representation of the interval.
 
1015
 */
 
1016
function format_interval($timestamp, $granularity = 2) {
 
1017
  $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);
 
1018
  $output = '';
 
1019
  foreach ($units as $key => $value) {
 
1020
    $key = explode('|', $key);
 
1021
    if ($timestamp >= $value) {
 
1022
      $output .= ($output ? ' ' : '') . format_plural(floor($timestamp / $value), $key[0], $key[1]);
 
1023
      $timestamp %= $value;
 
1024
      $granularity--;
 
1025
    }
 
1026
 
 
1027
    if ($granularity == 0) {
 
1028
      break;
 
1029
    }
 
1030
  }
 
1031
  return $output ? $output : t('0 sec');
 
1032
}
 
1033
 
 
1034
/**
 
1035
 * Format a date with the given configured format or a custom format string.
 
1036
 *
 
1037
 * Drupal allows administrators to select formatting strings for 'small',
 
1038
 * 'medium' and 'large' date formats. This function can handle these formats,
 
1039
 * as well as any custom format.
 
1040
 *
 
1041
 * @param $timestamp
 
1042
 *   The exact date to format, as a UNIX timestamp.
 
1043
 * @param $type
 
1044
 *   The format to use. Can be "small", "medium" or "large" for the preconfigured
 
1045
 *   date formats. If "custom" is specified, then $format is required as well.
 
1046
 * @param $format
 
1047
 *   A PHP date format string as required by date(). A backslash should be used
 
1048
 *   before a character to avoid interpreting the character as part of a date
 
1049
 *   format.
 
1050
 * @param $timezone
 
1051
 *   Time zone offset in seconds; if omitted, the user's time zone is used.
 
1052
 * @return
 
1053
 *   A translated date string in the requested format.
 
1054
 */
 
1055
function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL) {
 
1056
  if (!isset($timezone)) {
 
1057
    global $user;
 
1058
    if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
 
1059
      $timezone = $user->timezone;
 
1060
    }
 
1061
    else {
 
1062
      $timezone = variable_get('date_default_timezone', 0);
 
1063
    }
 
1064
  }
 
1065
 
 
1066
  $timestamp += $timezone;
 
1067
 
 
1068
  switch ($type) {
 
1069
    case 'small':
 
1070
      $format = variable_get('date_format_short', 'm/d/Y - H:i');
 
1071
      break;
 
1072
    case 'large':
 
1073
      $format = variable_get('date_format_long', 'l, F j, Y - H:i');
 
1074
      break;
 
1075
    case 'custom':
 
1076
      // No change to format
 
1077
      break;
 
1078
    case 'medium':
 
1079
    default:
 
1080
      $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
 
1081
  }
 
1082
 
 
1083
  $max = strlen($format);
 
1084
  $date = '';
 
1085
  for ($i = 0; $i < $max; $i++) {
 
1086
    $c = $format[$i];
 
1087
    if (strpos('AaDFlM', $c) !== FALSE) {
 
1088
      $date .= t(gmdate($c, $timestamp));
 
1089
    }
 
1090
    else if (strpos('BdgGhHiIjLmnsStTUwWYyz', $c) !== FALSE) {
 
1091
      $date .= gmdate($c, $timestamp);
 
1092
    }
 
1093
    else if ($c == 'r') {
 
1094
      $date .= format_date($timestamp - $timezone, 'custom', 'D, d M Y H:i:s O', $timezone);
 
1095
    }
 
1096
    else if ($c == 'O') {
 
1097
      $date .= sprintf('%s%02d%02d', ($timezone < 0 ? '-' : '+'), abs($timezone / 3600), abs($timezone % 3600) / 60);
 
1098
    }
 
1099
    else if ($c == 'Z') {
 
1100
      $date .= $timezone;
 
1101
    }
 
1102
    else if ($c == '\\') {
 
1103
      $date .= $format[++$i];
 
1104
    }
 
1105
    else {
 
1106
      $date .= $c;
 
1107
    }
 
1108
  }
 
1109
 
 
1110
  return $date;
 
1111
}
 
1112
 
 
1113
/**
 
1114
 * @} End of "defgroup format".
 
1115
 */
 
1116
 
 
1117
/**
 
1118
 * Generate a URL from a Drupal menu path. Will also pass-through existing URLs.
 
1119
 *
 
1120
 * @param $path
 
1121
 *   The Drupal path being linked to, such as "admin/content/node", or an existing URL
 
1122
 *   like "http://drupal.org/".
 
1123
 * @param $query
 
1124
 *   A query string to append to the link or URL.
 
1125
 * @param $fragment
 
1126
 *   A fragment identifier (named anchor) to append to the link. If an existing
 
1127
 *   URL with a fragment identifier is used, it will be replaced. Note, do not
 
1128
 *   include the '#'.
 
1129
 * @param $absolute
 
1130
 *   Whether to force the output to be an absolute link (beginning with http:).
 
1131
 *   Useful for links that will be displayed outside the site, such as in an
 
1132
 *   RSS feed.
 
1133
 * @return
 
1134
 *   a string containing a URL to the given path.
 
1135
 *
 
1136
 * When creating links in modules, consider whether l() could be a better
 
1137
 * alternative than url().
 
1138
 */
 
1139
function url($path = NULL, $query = NULL, $fragment = NULL, $absolute = FALSE) {
 
1140
  if (isset($fragment)) {
 
1141
    $fragment = '#'. $fragment;
 
1142
  }
 
1143
 
 
1144
  // Return an external link if $path contains an allowed absolute URL.
 
1145
  // Only call the slow filter_xss_bad_protocol if $path contains a ':' before any / ? or #.
 
1146
  $colonpos = strpos($path, ':');
 
1147
  if ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && filter_xss_bad_protocol($path, FALSE) == check_plain($path)) {
 
1148
    // Split off the fragment
 
1149
    if (strpos($path, '#') !== FALSE) {
 
1150
      list($path, $old_fragment) = explode('#', $path, 2);
 
1151
      if (isset($old_fragment) && !isset($fragment)) {
 
1152
        $fragment = '#'. $old_fragment;
 
1153
      }
 
1154
    }
 
1155
    // Append the query
 
1156
    if (isset($query)) {
 
1157
      $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . $query;
 
1158
    }
 
1159
    // Reassemble
 
1160
    return $path . $fragment;
 
1161
  }
 
1162
 
 
1163
  global $base_url;
 
1164
  static $script;
 
1165
  static $clean_url;
 
1166
 
 
1167
  if (empty($script)) {
 
1168
    // On some web servers, such as IIS, we can't omit "index.php". So, we
 
1169
    // generate "index.php?q=foo" instead of "?q=foo" on anything that is not
 
1170
    // Apache.
 
1171
    $script = (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') === FALSE) ? 'index.php' : '';
 
1172
  }
 
1173
 
 
1174
  // Cache the clean_url variable to improve performance.
 
1175
  if (!isset($clean_url)) {
 
1176
    $clean_url = (bool)variable_get('clean_url', '0');
 
1177
  }
 
1178
 
 
1179
  $base = ($absolute ? $base_url . '/' : base_path());
 
1180
 
 
1181
  // The special path '<front>' links to the default front page.
 
1182
  if (!empty($path) && $path != '<front>') {
 
1183
    $path = drupal_get_path_alias($path);
 
1184
    $path = drupal_urlencode($path);
 
1185
    if (!$clean_url) {
 
1186
      if (isset($query)) {
 
1187
        return $base . $script .'?q='. $path .'&'. $query . $fragment;
 
1188
      }
 
1189
      else {
 
1190
        return $base . $script .'?q='. $path . $fragment;
 
1191
      }
 
1192
    }
 
1193
    else {
 
1194
      if (isset($query)) {
 
1195
        return $base . $path .'?'. $query . $fragment;
 
1196
      }
 
1197
      else {
 
1198
        return $base . $path . $fragment;
 
1199
      }
 
1200
    }
 
1201
  }
 
1202
  else {
 
1203
    if (isset($query)) {
 
1204
      return $base . $script .'?'. $query . $fragment;
 
1205
    }
 
1206
    else {
 
1207
      return $base . $fragment;
 
1208
    }
 
1209
  }
 
1210
}
 
1211
 
 
1212
/**
 
1213
 * Format an attribute string to insert in a tag.
 
1214
 *
 
1215
 * @param $attributes
 
1216
 *   An associative array of HTML attributes.
 
1217
 * @return
 
1218
 *   An HTML string ready for insertion in a tag.
 
1219
 */
 
1220
function drupal_attributes($attributes = array()) {
 
1221
  if (is_array($attributes)) {
 
1222
    $t = '';
 
1223
    foreach ($attributes as $key => $value) {
 
1224
      $t .= " $key=".'"'. check_plain($value) .'"';
 
1225
    }
 
1226
    return $t;
 
1227
  }
 
1228
}
 
1229
 
 
1230
/**
 
1231
 * Format an internal Drupal link.
 
1232
 *
 
1233
 * This function correctly handles aliased paths, and allows themes to highlight
 
1234
 * links to the current page correctly, so all internal links output by modules
 
1235
 * should be generated by this function if possible.
 
1236
 *
 
1237
 * @param $text
 
1238
 *   The text to be enclosed with the anchor tag.
 
1239
 * @param $path
 
1240
 *   The Drupal path being linked to, such as "admin/content/node". Can be an external
 
1241
 *   or internal URL.
 
1242
 *     - If you provide the full URL, it will be considered an
 
1243
 *   external URL.
 
1244
 *     - If you provide only the path (e.g. "admin/content/node"), it is considered an
 
1245
 *   internal link. In this case, it must be a system URL as the url() function
 
1246
 *   will generate the alias.
 
1247
 * @param $attributes
 
1248
 *   An associative array of HTML attributes to apply to the anchor tag.
 
1249
 * @param $query
 
1250
 *   A query string to append to the link.
 
1251
 * @param $fragment
 
1252
 *   A fragment identifier (named anchor) to append to the link.
 
1253
 * @param $absolute
 
1254
 *   Whether to force the output to be an absolute link (beginning with http:).
 
1255
 *   Useful for links that will be displayed outside the site, such as in an RSS
 
1256
 *   feed.
 
1257
 * @param $html
 
1258
 *   Whether the title is HTML, or just plain-text. For example for making an
 
1259
 *   image a link, this must be set to TRUE, or else you will see the encoded
 
1260
 *   HTML.
 
1261
 * @return
 
1262
 *   an HTML string containing a link to the given path.
 
1263
 */
 
1264
function l($text, $path, $attributes = array(), $query = NULL, $fragment = NULL, $absolute = FALSE, $html = FALSE) {
 
1265
  if ($path == $_GET['q']) {
 
1266
    if (isset($attributes['class'])) {
 
1267
      $attributes['class'] .= ' active';
 
1268
    }
 
1269
    else {
 
1270
      $attributes['class'] = 'active';
 
1271
    }
 
1272
  }
 
1273
  return '<a href="'. check_url(url($path, $query, $fragment, $absolute)) .'"'. drupal_attributes($attributes) .'>'. ($html ? $text : check_plain($text)) .'</a>';
 
1274
}
 
1275
 
 
1276
/**
 
1277
 * Perform end-of-request tasks.
 
1278
 *
 
1279
 * This function sets the page cache if appropriate, and allows modules to
 
1280
 * react to the closing of the page by calling hook_exit().
 
1281
 */
 
1282
function drupal_page_footer() {
 
1283
  if (variable_get('cache', 0)) {
 
1284
    page_set_cache();
 
1285
  }
 
1286
 
 
1287
  module_invoke_all('exit');
 
1288
}
 
1289
 
 
1290
/**
 
1291
 * Form an associative array from a linear array.
 
1292
 *
 
1293
 * This function walks through the provided array and constructs an associative
 
1294
 * array out of it. The keys of the resulting array will be the values of the
 
1295
 * input array. The values will be the same as the keys unless a function is
 
1296
 * specified, in which case the output of the function is used for the values
 
1297
 * instead.
 
1298
 *
 
1299
 * @param $array
 
1300
 *   A linear array.
 
1301
 * @param $function
 
1302
 *   The name of a function to apply to all values before output.
 
1303
 * @result
 
1304
 *   An associative array.
 
1305
 */
 
1306
function drupal_map_assoc($array, $function = NULL) {
 
1307
  if (!isset($function)) {
 
1308
    $result = array();
 
1309
    foreach ($array as $value) {
 
1310
      $result[$value] = $value;
 
1311
    }
 
1312
    return $result;
 
1313
  }
 
1314
  elseif (function_exists($function)) {
 
1315
    $result = array();
 
1316
    foreach ($array as $value) {
 
1317
      $result[$value] = $function($value);
 
1318
    }
 
1319
    return $result;
 
1320
  }
 
1321
}
 
1322
 
 
1323
/**
 
1324
 * Evaluate a string of PHP code.
 
1325
 *
 
1326
 * This is a wrapper around PHP's eval(). It uses output buffering to capture both
 
1327
 * returned and printed text. Unlike eval(), we require code to be surrounded by
 
1328
 * <?php ?> tags; in other words, we evaluate the code as if it were a stand-alone
 
1329
 * PHP file.
 
1330
 *
 
1331
 * Using this wrapper also ensures that the PHP code which is evaluated can not
 
1332
 * overwrite any variables in the calling code, unlike a regular eval() call.
 
1333
 *
 
1334
 * @param $code
 
1335
 *   The code to evaluate.
 
1336
 * @return
 
1337
 *   A string containing the printed output of the code, followed by the returned
 
1338
 *   output of the code.
 
1339
 */
 
1340
function drupal_eval($code) {
 
1341
  ob_start();
 
1342
  print eval('?>'. $code);
 
1343
  $output = ob_get_contents();
 
1344
  ob_end_clean();
 
1345
  return $output;
 
1346
}
 
1347
 
 
1348
/**
 
1349
 * Returns the path to a system item (module, theme, etc.).
 
1350
 *
 
1351
 * @param $type
 
1352
 *   The type of the item (i.e. theme, theme_engine, module).
 
1353
 * @param $name
 
1354
 *   The name of the item for which the path is requested.
 
1355
 *
 
1356
 * @return
 
1357
 *   The path to the requested item.
 
1358
 */
 
1359
function drupal_get_path($type, $name) {
 
1360
  return dirname(drupal_get_filename($type, $name));
 
1361
}
 
1362
 
 
1363
/**
 
1364
 * Returns the base URL path of the Drupal installation.
 
1365
 * At the very least, this will always default to /.
 
1366
 */
 
1367
function base_path() {
 
1368
  return $GLOBALS['base_path'];
 
1369
}
 
1370
 
 
1371
/**
 
1372
 * Provide a substitute clone() function for PHP4.
 
1373
 */
 
1374
function drupal_clone($object) {
 
1375
  return version_compare(phpversion(), '5.0') < 0 ? $object : clone($object);
 
1376
}
 
1377
 
 
1378
/**
 
1379
 * Add a <link> tag to the page's HEAD.
 
1380
 */
 
1381
function drupal_add_link($attributes) {
 
1382
  drupal_set_html_head('<link'. drupal_attributes($attributes) ." />\n");
 
1383
}
 
1384
 
 
1385
/**
 
1386
 * Adds a CSS file to the stylesheet queue.
 
1387
 *
 
1388
 * @param $path
 
1389
 *   (optional) The path to the CSS file relative to the base_path(), e.g.,
 
1390
 *   /modules/devel/devel.css.
 
1391
 * @param $type
 
1392
 *   (optional) The type of stylesheet that is being added. Types are: module
 
1393
 *   or theme.
 
1394
 * @param $media
 
1395
 *   (optional) The media type for the stylesheet, e.g., all, print, screen.
 
1396
 * @param $preprocess
 
1397
 *   (optional) Should this CSS file be aggregated and compressed if this
 
1398
 *   feature has been turned on under the performance section?
 
1399
 *
 
1400
 *   What does this actually mean?
 
1401
 *   CSS preprocessing is the process of aggregating a bunch of separate CSS
 
1402
 *   files into one file that is then compressed by removing all extraneous
 
1403
 *   white space.
 
1404
 *
 
1405
 *   The reason for merging the CSS files is outlined quite thoroughly here:
 
1406
 *   http://www.die.net/musings/page_load_time/
 
1407
 *   "Load fewer external objects. Due to request overhead, one bigger file
 
1408
 *   just loads faster than two smaller ones half its size."
 
1409
 *
 
1410
 *   However, you should *not* preprocess every file as this can lead to
 
1411
 *   redundant caches. You should set $preprocess = FALSE when:
 
1412
 *
 
1413
 *     - Your styles are only used rarely on the site. This could be a special
 
1414
 *       admin page, the homepage, or a handful of pages that does not represent
 
1415
 *       the majority of the pages on your site.
 
1416
 *
 
1417
 *   Typical candidates for caching are for example styles for nodes across
 
1418
 *   the site, or used in the theme.
 
1419
 * @return
 
1420
 *   An array of CSS files.
 
1421
 */
 
1422
function drupal_add_css($path = NULL, $type = 'module', $media = 'all', $preprocess = TRUE) {
 
1423
  static $css = array();
 
1424
 
 
1425
  // Create an array of CSS files for each media type first, since each type needs to be served
 
1426
  // to the browser differently.
 
1427
  if (isset($path)) {
 
1428
    // This check is necessary to ensure proper cascading of styles and is faster than an asort().
 
1429
    if (!isset($css[$media])) {
 
1430
      $css[$media] = array('module' => array(), 'theme' => array());
 
1431
    }
 
1432
    $css[$media][$type][$path] = $preprocess;
 
1433
  }
 
1434
 
 
1435
  return $css;
 
1436
}
 
1437
 
 
1438
/**
 
1439
 * Returns a themed representation of all stylesheets that should be attached to the page.
 
1440
 * It loads the CSS in order, with 'core' CSS first, then 'module' CSS, then 'theme' CSS files.
 
1441
 * This ensures proper cascading of styles for easy overriding in modules and themes.
 
1442
 *
 
1443
 * @param $css
 
1444
 *   (optional) An array of CSS files. If no array is provided, the default stylesheets array is used instead.
 
1445
 * @return
 
1446
 *   A string of XHTML CSS tags.
 
1447
 */
 
1448
function drupal_get_css($css = NULL) {
 
1449
  $output = '';
 
1450
  if (!isset($css)) {
 
1451
    $css = drupal_add_css();
 
1452
  }
 
1453
 
 
1454
  $preprocess_css = variable_get('preprocess_css', FALSE);
 
1455
  $directory = file_directory_path();
 
1456
  $is_writable = is_dir($directory) && is_writable($directory) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC);
 
1457
 
 
1458
  foreach ($css as $media => $types) {
 
1459
    // If CSS preprocessing is off, we still need to output the styles.
 
1460
    // Additionally, go through any remaining styles if CSS preprocessing is on and output the non-cached ones.
 
1461
    foreach ($types as $type => $files) {
 
1462
      foreach ($types[$type] as $file => $preprocess) {
 
1463
        if (!$preprocess || !($is_writable && $preprocess_css)) {
 
1464
          // If a CSS file is not to be preprocessed and it's a module CSS file, it needs to *always* appear at the *top*,
 
1465
          // regardless of whether preprocessing is on or off.
 
1466
          if (!$preprocess && $type == 'module') {
 
1467
            $no_module_preprocess .= '<style type="text/css" media="'. $media .'">@import "'. base_path() . $file .'";</style>' ."\n";
 
1468
          }
 
1469
          // If a CSS file is not to be preprocessed and it's a theme CSS file, it needs to *always* appear at the *bottom*,
 
1470
          // regardless of whether preprocessing is on or off.
 
1471
          else if (!$preprocess && $type == 'theme') {
 
1472
            $no_theme_preprocess .= '<style type="text/css" media="'. $media .'">@import "'. base_path() . $file .'";</style>' ."\n";
 
1473
          }
 
1474
          else {
 
1475
            $output .= '<style type="text/css" media="'. $media .'">@import "'. base_path() . $file .'";</style>' ."\n";
 
1476
          }
 
1477
        }
 
1478
      }
 
1479
    }
 
1480
 
 
1481
    if ($is_writable && $preprocess_css) {
 
1482
      $filename = md5(serialize($types)) .'.css';
 
1483
      $preprocess_file = drupal_build_css_cache($types, $filename);
 
1484
      $output .= '<style type="text/css" media="'. $media .'">@import "'. base_path() . $preprocess_file .'";</style>'. "\n";
 
1485
    }
 
1486
  }
 
1487
 
 
1488
  return $no_module_preprocess . $output . $no_theme_preprocess;
 
1489
}
 
1490
 
 
1491
/**
 
1492
 * Aggregate and optimize CSS files, putting them in the files directory.
 
1493
 *
 
1494
 * @param $types
 
1495
 *   An array of types of CSS files (e.g., screen, print) to aggregate and compress into one file.
 
1496
 * @param $filename
 
1497
 *   The name of the aggregate CSS file.
 
1498
 * @return
 
1499
 *   The name of the CSS file.
 
1500
 */
 
1501
function drupal_build_css_cache($types, $filename) {
 
1502
  $data = '';
 
1503
 
 
1504
  // Create the css/ within the files folder.
 
1505
  $csspath = file_create_path('css');
 
1506
  file_check_directory($csspath, FILE_CREATE_DIRECTORY);
 
1507
 
 
1508
  if (!file_exists($csspath .'/'. $filename)) {
 
1509
    // Build aggregate CSS file.
 
1510
    foreach ($types as $type) {
 
1511
      foreach ($type as $file => $cache) {
 
1512
        if ($cache) {
 
1513
          $contents = file_get_contents($file);
 
1514
          // Return the path to where this CSS file originated from, stripping off the name of the file at the end of the path.
 
1515
          $path = base_path() . substr($file, 0, strrpos($file, '/')) .'/';
 
1516
          // Wraps all @import arguments in url().
 
1517
          $contents = preg_replace('/@import\s+(?!url)[\'"]?(\S*)\b[\'"]?/i', '@import url("\1")', $contents);
 
1518
          // Fix all paths within this CSS file, ignoring absolute paths.
 
1519
          $data .= preg_replace('/url\(([\'"]?)(?![a-z]+:)/i', 'url(\1'. $path . '\2', $contents);
 
1520
        }
 
1521
      }
 
1522
    }
 
1523
 
 
1524
    // @import rules must proceed any other style, so we move those to the top.
 
1525
    $regexp = '/@import[^;]+;/i';
 
1526
    preg_match_all($regexp, $data, $matches);
 
1527
    $data = preg_replace($regexp, '', $data);
 
1528
    $data = implode('', $matches[0]) . $data;
 
1529
 
 
1530
    // Perform some safe CSS optimizations.
 
1531
    $data = preg_replace('<
 
1532
      \s*([@{}:;,]|\)\s|\s\()\s* |  # Remove whitespace around separators, but keep space around parentheses.
 
1533
      /\*([^*\\\\]|\*(?!/))+\*/ |   # Remove comments that are not CSS hacks.
 
1534
      [\n\r]                        # Remove line breaks.
 
1535
      >x', '\1', $data);
 
1536
 
 
1537
    // Create the CSS file.
 
1538
    file_save_data($data, $csspath .'/'. $filename, FILE_EXISTS_REPLACE);
 
1539
  }
 
1540
  return $csspath .'/'. $filename;
 
1541
}
 
1542
 
 
1543
/**
 
1544
 * Delete all cached CSS files.
 
1545
 */
 
1546
function drupal_clear_css_cache() {
 
1547
  file_scan_directory(file_create_path('css'), '.*', array('.', '..', 'CVS'), 'file_delete', TRUE);
 
1548
}
 
1549
 
 
1550
/**
 
1551
 * Add a JavaScript file, setting or inline code to the page.
 
1552
 *
 
1553
 * The behavior of this function depends on the parameters it is called with.
 
1554
 * Generally, it handles the addition of JavaScript to the page, either as
 
1555
 * reference to an existing file or as inline code. The following actions can be
 
1556
 * performed using this function:
 
1557
 *
 
1558
 * - Add a file ('core', 'module' and 'theme'):
 
1559
 *   Adds a reference to a JavaScript file to the page. JavaScript files
 
1560
 *   are placed in a certain order, from 'core' first, to 'module' and finally
 
1561
 *   'theme' so that files, that are added later, can override previously added
 
1562
 *   files with ease.
 
1563
 *
 
1564
 * - Add inline JavaScript code ('inline'):
 
1565
 *   Executes a piece of JavaScript code on the current page by placing the code
 
1566
 *   directly in the page. This can, for example, be useful to tell the user that
 
1567
 *   a new message arrived, by opening a pop up, alert box etc.
 
1568
 *
 
1569
 * - Add settings ('setting'):
 
1570
 *   Adds a setting to Drupal's global storage of JavaScript settings. Per-page
 
1571
 *   settings are required by some modules to function properly. The settings
 
1572
 *   will be accessible at Drupal.settings.
 
1573
 *
 
1574
 * @param $data
 
1575
 *   (optional) If given, the value depends on the $type parameter:
 
1576
 *   - 'core', 'module' or 'theme': Path to the file relative to base_path().
 
1577
 *   - 'inline': The JavaScript code that should be placed in the given scope.
 
1578
 *   - 'setting': An array with configuration options as associative array. The
 
1579
 *       array is directly placed in Drupal.settings. You might want to wrap your
 
1580
 *       actual configuration settings in another variable to prevent the pollution
 
1581
 *       of the Drupal.settings namespace.
 
1582
 * @param $type
 
1583
 *   (optional) The type of JavaScript that should be added to the page. Allowed
 
1584
 *   values are 'core', 'module', 'theme', 'inline' and 'setting'. You
 
1585
 *   can, however, specify any value. It is treated as a reference to a JavaScript
 
1586
 *   file. Defaults to 'module'.
 
1587
 * @param $scope
 
1588
 *   (optional) The location in which you want to place the script. Possible
 
1589
 *   values are 'header' and 'footer' by default. If your theme implements
 
1590
 *   different locations, however, you can also use these.
 
1591
 * @param $defer
 
1592
 *   (optional) If set to TRUE, the defer attribute is set on the <script> tag.
 
1593
 *   Defaults to FALSE. This parameter is not used with $type == 'setting'.
 
1594
 * @param $cache
 
1595
 *   (optional) If set to FALSE, the JavaScript file is loaded anew on every page
 
1596
 *   call, that means, it is not cached. Defaults to TRUE. Used only when $type
 
1597
 *   references a JavaScript file.
 
1598
 * @return
 
1599
 *   If the first parameter is NULL, the JavaScript array that has been built so
 
1600
 *   far for $scope is returned.
 
1601
 */
 
1602
function drupal_add_js($data = NULL, $type = 'module', $scope = 'header', $defer = FALSE, $cache = TRUE) {
 
1603
  if (!is_null($data)) {
 
1604
    _drupal_add_js('misc/jquery.js', 'core', 'header', FALSE, $cache);
 
1605
    _drupal_add_js('misc/drupal.js', 'core', 'header', FALSE, $cache);
 
1606
  }
 
1607
  return _drupal_add_js($data, $type, $scope, $defer, $cache);
 
1608
}
 
1609
 
 
1610
/**
 
1611
 * Helper function for drupal_add_js().
 
1612
 */
 
1613
function _drupal_add_js($data, $type, $scope, $defer, $cache) {
 
1614
  static $javascript = array();
 
1615
 
 
1616
  if (!isset($javascript[$scope])) {
 
1617
    $javascript[$scope] = array('core' => array(), 'module' => array(), 'theme' => array(), 'setting' => array(), 'inline' => array());
 
1618
  }
 
1619
 
 
1620
  if (!isset($javascript[$scope][$type])) {
 
1621
    $javascript[$scope][$type] = array();
 
1622
  }
 
1623
 
 
1624
  if (!is_null($data)) {
 
1625
    switch ($type) {
 
1626
      case 'setting':
 
1627
        $javascript[$scope][$type][] = $data;
 
1628
        break;
 
1629
      case 'inline':
 
1630
        $javascript[$scope][$type][] = array('code' => $data, 'defer' => $defer);
 
1631
        break;
 
1632
      default:
 
1633
        $javascript[$scope][$type][$data] = array('cache' => $cache, 'defer' => $defer);
 
1634
    }
 
1635
  }
 
1636
 
 
1637
  return $javascript[$scope];
 
1638
}
 
1639
 
 
1640
/**
 
1641
 * Returns a themed presentation of all JavaScript code for the current page.
 
1642
 * References to JavaScript files are placed in a certain order: first, all
 
1643
 * 'core' files, then all 'module' and finally all 'theme' JavaScript files
 
1644
 * are added to the page. Then, all settings are output, followed by 'inline'
 
1645
 * JavaScript code.
 
1646
 *
 
1647
 * @parameter $scope
 
1648
 *   (optional) The scope for which the JavaScript rules should be returned.
 
1649
 *   Defaults to 'header'.
 
1650
 * @parameter $javascript
 
1651
 *   (optional) An array with all JavaScript code. Defaults to the default
 
1652
 *   JavaScript array for the given scope.
 
1653
 * @return
 
1654
 *   All JavaScript code segments and includes for the scope as HTML tags.
 
1655
 */
 
1656
function drupal_get_js($scope = 'header', $javascript = NULL) {
 
1657
  $output = '';
 
1658
  if (is_null($javascript)) {
 
1659
    $javascript = drupal_add_js(NULL, NULL, $scope);
 
1660
  }
 
1661
 
 
1662
  foreach ($javascript as $type => $data) {
 
1663
    if (!$data) continue;
 
1664
 
 
1665
    switch ($type) {
 
1666
      case 'setting':
 
1667
        $output .= '<script type="text/javascript">Drupal.extend({ settings: '. drupal_to_js(call_user_func_array('array_merge_recursive', $data)) ." });</script>\n";
 
1668
        break;
 
1669
      case 'inline':
 
1670
        foreach ($data as $info) {
 
1671
          $output .= '<script type="text/javascript"'. ($info['defer'] ? ' defer="defer"' : '') .'>'. $info['code'] ."</script>\n";
 
1672
        }
 
1673
        break;
 
1674
      default:
 
1675
        foreach ($data as $path => $info) {
 
1676
          $output .= '<script type="text/javascript"'. ($info['defer'] ? ' defer="defer"' : '') .' src="'. check_url(base_path() . $path) . ($info['cache'] ? '' : '?'. time()) ."\"></script>\n";
 
1677
        }
 
1678
    }
 
1679
  }
 
1680
 
 
1681
  return $output;
 
1682
}
 
1683
 
 
1684
/**
 
1685
 * Converts a PHP variable into its Javascript equivalent.
 
1686
 *
 
1687
 * We use HTML-safe strings, i.e. with <, > and & escaped.
 
1688
 */
 
1689
function drupal_to_js($var) {
 
1690
  switch (gettype($var)) {
 
1691
    case 'boolean':
 
1692
      return $var ? 'true' : 'false'; // Lowercase necessary!
 
1693
    case 'integer':
 
1694
    case 'double':
 
1695
      return $var;
 
1696
    case 'resource':
 
1697
    case 'string':
 
1698
      return '"'. str_replace(array("\r", "\n", "<", ">", "&"),
 
1699
                              array('\r', '\n', '\x3c', '\x3e', '\x26'),
 
1700
                              addslashes($var)) .'"';
 
1701
    case 'array':
 
1702
      if (array_keys($var) === range(0, sizeof($var) - 1)) {
 
1703
        $output = array();
 
1704
        foreach ($var as $v) {
 
1705
          $output[] = drupal_to_js($v);
 
1706
        }
 
1707
        return '[ '. implode(', ', $output) .' ]';
 
1708
      }
 
1709
      // Fall through
 
1710
    case 'object':
 
1711
      $output = array();
 
1712
      foreach ($var as $k => $v) {
 
1713
        $output[] = drupal_to_js(strval($k)) .': '. drupal_to_js($v);
 
1714
      }
 
1715
      return '{ '. implode(', ', $output) .' }';
 
1716
    default:
 
1717
      return 'null';
 
1718
  }
 
1719
}
 
1720
 
 
1721
/**
 
1722
 * Wrapper around urlencode() which avoids Apache quirks.
 
1723
 *
 
1724
 * Should be used when placing arbitrary data in an URL. Note that Drupal paths
 
1725
 * are urlencoded() when passed through url() and do not require urlencoding()
 
1726
 * of individual components.
 
1727
 *
 
1728
 * Notes:
 
1729
 * - For esthetic reasons, we do not escape slashes. This also avoids a 'feature'
 
1730
 *   in Apache where it 404s on any path containing '%2F'.
 
1731
 * - mod_rewrite's unescapes %-encoded ampersands and hashes when clean URLs
 
1732
 *   are used, which are interpreted as delimiters by PHP. These characters are
 
1733
 *   double escaped so PHP will still see the encoded version.
 
1734
 *
 
1735
 * @param $text
 
1736
 *   String to encode
 
1737
 */
 
1738
function drupal_urlencode($text) {
 
1739
  if (variable_get('clean_url', '0')) {
 
1740
    return str_replace(array('%2F', '%26', '%23'),
 
1741
                       array('/', '%2526', '%2523'),
 
1742
                       urlencode($text));
 
1743
  }
 
1744
  else {
 
1745
    return str_replace('%2F', '/', urlencode($text));
 
1746
  }
 
1747
}
 
1748
 
 
1749
/**
 
1750
 * Ensure the private key variable used to generate tokens is set.
 
1751
 *
 
1752
 * @return
 
1753
 *   The private key
 
1754
 */
 
1755
function drupal_get_private_key() {
 
1756
  if (!($key = variable_get('drupal_private_key', 0))) {
 
1757
    $key = md5(uniqid(mt_rand(), true)) . md5(uniqid(mt_rand(), true));
 
1758
    variable_set('drupal_private_key', $key);
 
1759
  }
 
1760
  return $key;
 
1761
}
 
1762
 
 
1763
/**
 
1764
 * Generate a token based on $value, the current user session and private key.
 
1765
 *
 
1766
 * @param $value
 
1767
 *   An additional value to base the token on
 
1768
 */
 
1769
function drupal_get_token($value = '') {
 
1770
  $private_key = drupal_get_private_key();
 
1771
  return md5(session_id() . $value . $private_key);
 
1772
}
 
1773
 
 
1774
/**
 
1775
 * Validate a token based on $value, the current user session and private key.
 
1776
 *
 
1777
 * @param $token
 
1778
 *   The token to be validated.
 
1779
 * @param $value
 
1780
 *   An additional value to base the token on.
 
1781
 * @param $skip_anonymous
 
1782
 *   Set to true to skip token validation for anonymous users.
 
1783
 * @return
 
1784
 *   True for a valid token, false for an invalid token. When $skip_anonymous is true, the return value will always be true for anonymous users.
 
1785
 */
 
1786
function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
 
1787
  global $user;
 
1788
  return (($skip_anonymous && $user->uid == 0) || ($token == md5(session_id() . $value . variable_get('drupal_private_key', ''))));
 
1789
}
 
1790
 
 
1791
/**
 
1792
 * Performs one or more XML-RPC request(s).
 
1793
 *
 
1794
 * @param $url
 
1795
 *   An absolute URL of the XML-RPC endpoint.
 
1796
 *     Example:
 
1797
 *     http://www.example.com/xmlrpc.php
 
1798
 * @param ...
 
1799
 *   For one request:
 
1800
 *     The method name followed by a variable number of arguments to the method.
 
1801
 *   For multiple requests (system.multicall):
 
1802
 *     An array of call arrays. Each call array follows the pattern of the single
 
1803
 *     request: method name followed by the arguments to the method.
 
1804
 * @return
 
1805
 *   For one request:
 
1806
 *     Either the return value of the method on success, or FALSE.
 
1807
 *     If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
 
1808
 *   For multiple requests:
 
1809
 *     An array of results. Each result will either be the result
 
1810
 *     returned by the method called, or an xmlrpc_error object if the call
 
1811
 *     failed. See xmlrpc_error().
 
1812
 */
 
1813
function xmlrpc($url) {
 
1814
  require_once './includes/xmlrpc.inc';
 
1815
  $args = func_get_args();
 
1816
  return call_user_func_array('_xmlrpc', $args);
 
1817
}
 
1818
 
 
1819
function _drupal_bootstrap_full() {
 
1820
  static $called;
 
1821
  global $locale;
 
1822
 
 
1823
  if ($called) {
 
1824
    return;
 
1825
  }
 
1826
  $called = 1;
 
1827
  require_once './includes/theme.inc';
 
1828
  require_once './includes/pager.inc';
 
1829
  require_once './includes/menu.inc';
 
1830
  require_once './includes/tablesort.inc';
 
1831
  require_once './includes/file.inc';
 
1832
  require_once './includes/unicode.inc';
 
1833
  require_once './includes/image.inc';
 
1834
  require_once './includes/form.inc';
 
1835
  // Set the Drupal custom error handler.
 
1836
  set_error_handler('error_handler');
 
1837
  // Emit the correct charset HTTP header.
 
1838
  drupal_set_header('Content-Type: text/html; charset=utf-8');
 
1839
  // Detect string handling method
 
1840
  unicode_check();
 
1841
  // Undo magic quotes
 
1842
  fix_gpc_magic();
 
1843
  // Load all enabled modules
 
1844
  module_load_all();
 
1845
  // Initialize the localization system.  Depends on i18n.module being loaded already.
 
1846
  $locale = locale_initialize();
 
1847
  // Let all modules take action before menu system handles the reqest
 
1848
  module_invoke_all('init');
 
1849
 
 
1850
}
 
1851
 
 
1852
/**
 
1853
 * Store the current page in the cache.
 
1854
 *
 
1855
 * We try to store a gzipped version of the cache. This requires the
 
1856
 * PHP zlib extension (http://php.net/manual/en/ref.zlib.php).
 
1857
 * Presence of the extension is checked by testing for the function
 
1858
 * gzencode. There are two compression algorithms: gzip and deflate.
 
1859
 * The majority of all modern browsers support gzip or both of them.
 
1860
 * We thus only deal with the gzip variant and unzip the cache in case
 
1861
 * the browser does not accept gzip encoding.
 
1862
 *
 
1863
 * @see drupal_page_header
 
1864
 */
 
1865
function page_set_cache() {
 
1866
  global $user, $base_root;
 
1867
 
 
1868
  if (!$user->uid && $_SERVER['REQUEST_METHOD'] == 'GET' && count(drupal_get_messages(NULL, FALSE)) == 0) {
 
1869
    // This will fail in some cases, see page_get_cache() for the explanation.
 
1870
    if ($data = ob_get_contents()) {
 
1871
      $cache = TRUE;
 
1872
      if (function_exists('gzencode')) {
 
1873
        // We do not store the data in case the zlib mode is deflate.
 
1874
        // This should be rarely happening.
 
1875
        if (zlib_get_coding_type() == 'deflate') {
 
1876
          $cache = FALSE;
 
1877
        }
 
1878
        else if (zlib_get_coding_type() == FALSE) {
 
1879
          $data = gzencode($data, 9, FORCE_GZIP);
 
1880
        }
 
1881
        // The remaining case is 'gzip' which means the data is
 
1882
        // already compressed and nothing left to do but to store it.
 
1883
      }
 
1884
      ob_end_flush();
 
1885
      if ($cache && $data) {
 
1886
        cache_set($base_root . request_uri(), 'cache_page', $data, CACHE_TEMPORARY, drupal_get_headers());
 
1887
      }
 
1888
    }
 
1889
  }
 
1890
}
 
1891
 
 
1892
/**
 
1893
 * Send an e-mail message, using Drupal variables and default settings.
 
1894
 * More information in the <a href="http://php.net/manual/en/function.mail.php">
 
1895
 * PHP function reference for mail()</a>
 
1896
 * @param $mailkey
 
1897
 *   A key to identify the mail sent, for altering.
 
1898
 * @param $to
 
1899
 *   The mail address or addresses where the message will be send to. The
 
1900
 *   formatting of this string must comply with RFC 2822. Some examples are:
 
1901
 *    user@example.com
 
1902
 *    user@example.com, anotheruser@example.com
 
1903
 *    User <user@example.com>
 
1904
 *    User <user@example.com>, Another User <anotheruser@example.com>
 
1905
 * @param $subject
 
1906
 *   Subject of the e-mail to be sent. This must not contain any newline
 
1907
 *   characters, or the mail may not be sent properly.
 
1908
 * @param $body
 
1909
 *   Message to be sent. Drupal will format the correct line endings for you.
 
1910
 * @param $from
 
1911
 *   Sets From, Reply-To, Return-Path and Error-To to this value, if given.
 
1912
 * @param $headers
 
1913
 *   Associative array containing the headers to add. This is typically
 
1914
 *   used to add extra headers (From, Cc, and Bcc).
 
1915
 *   <em>When sending mail, the mail must contain a From header.</em>
 
1916
 * @return Returns TRUE if the mail was successfully accepted for delivery,
 
1917
 *   FALSE otherwise.
 
1918
 */
 
1919
function drupal_mail($mailkey, $to, $subject, $body, $from = NULL, $headers = array()) {
 
1920
  $defaults = array(
 
1921
    'MIME-Version' => '1.0',
 
1922
    'Content-Type' => 'text/plain; charset=UTF-8; format=flowed',
 
1923
    'Content-Transfer-Encoding' => '8Bit',
 
1924
    'X-Mailer' => 'Drupal'
 
1925
  );
 
1926
  if (isset($from)) {
 
1927
    $defaults['From'] = $defaults['Reply-To'] = $defaults['Return-Path'] = $defaults['Errors-To'] = $from;
 
1928
  }
 
1929
  $headers = array_merge($defaults, $headers);
 
1930
  // Custom hook traversal to allow pass by reference
 
1931
  foreach (module_implements('mail_alter') AS $module) {
 
1932
    $function = $module .'_mail_alter';
 
1933
    $function($mailkey, $to, $subject, $body, $from, $headers);
 
1934
  }
 
1935
  // Allow for custom mail backend
 
1936
  if (variable_get('smtp_library', '') && file_exists(variable_get('smtp_library', ''))) {
 
1937
    include_once './' . variable_get('smtp_library', '');
 
1938
    return drupal_mail_wrapper($mailkey, $to, $subject, $body, $from, $headers);
 
1939
  }
 
1940
  else {
 
1941
    /*
 
1942
    ** Note: if you are having problems with sending mail, or mails look wrong
 
1943
    ** when they are received you may have to modify the str_replace to suit
 
1944
    ** your systems.
 
1945
    **  - \r\n will work under dos and windows.
 
1946
    **  - \n will work for linux, unix and BSDs.
 
1947
    **  - \r will work for macs.
 
1948
    **
 
1949
    ** According to RFC 2646, it's quite rude to not wrap your e-mails:
 
1950
    **
 
1951
    ** "The Text/Plain media type is the lowest common denominator of
 
1952
    ** Internet e-mail, with lines of no more than 997 characters (by
 
1953
    ** convention usually no more than 80), and where the CRLF sequence
 
1954
    ** represents a line break [MIME-IMT]."
 
1955
    **
 
1956
    ** CRLF === \r\n
 
1957
    **
 
1958
    ** http://www.rfc-editor.org/rfc/rfc2646.txt
 
1959
    **
 
1960
    */
 
1961
    $mimeheaders = array();
 
1962
    foreach ($headers as $name => $value) {
 
1963
      $mimeheaders[] = $name .': '. mime_header_encode($value);
 
1964
    }
 
1965
    return mail(
 
1966
      $to,
 
1967
      mime_header_encode($subject),
 
1968
      str_replace("\r", '', $body),
 
1969
      join("\n", $mimeheaders)
 
1970
    );
 
1971
  }
 
1972
}
 
1973
 
 
1974
/**
 
1975
 * Executes a cron run when called
 
1976
 * @return
 
1977
 * Returns TRUE if ran successfully
 
1978
 */
 
1979
function drupal_cron_run() {
 
1980
  // If not in 'safe mode', increase the maximum execution time:
 
1981
  if (!ini_get('safe_mode')) {
 
1982
    set_time_limit(240);
 
1983
  }
 
1984
 
 
1985
  // Fetch the cron semaphore
 
1986
  $semaphore = variable_get('cron_semaphore', FALSE);
 
1987
 
 
1988
  if ($semaphore) {
 
1989
    if (time() - $semaphore > 3600) {
 
1990
      // Either cron has been running for more than an hour or the semaphore
 
1991
      // was not reset due to a database error.
 
1992
      watchdog('cron', t('Cron has been running for more than an hour and is most likely stuck.'), WATCHDOG_ERROR);
 
1993
 
 
1994
      // Release cron semaphore
 
1995
      variable_del('cron_semaphore');
 
1996
    }
 
1997
    else {
 
1998
      // Cron is still running normally.
 
1999
      watchdog('cron', t('Attempting to re-run cron while it is already running.'), WATCHDOG_WARNING);
 
2000
    }
 
2001
  }
 
2002
  else {
 
2003
    // Register shutdown callback
 
2004
    register_shutdown_function('drupal_cron_cleanup');
 
2005
 
 
2006
    // Lock cron semaphore
 
2007
    variable_set('cron_semaphore', time());
 
2008
 
 
2009
    // Iterate through the modules calling their cron handlers (if any):
 
2010
    module_invoke_all('cron');
 
2011
 
 
2012
    // Record cron time
 
2013
    variable_set('cron_last', time());
 
2014
    watchdog('cron', t('Cron run completed.'), WATCHDOG_NOTICE);
 
2015
 
 
2016
    // Release cron semaphore
 
2017
    variable_del('cron_semaphore');
 
2018
 
 
2019
    // Return TRUE so other functions can check if it did run successfully
 
2020
    return TRUE;
 
2021
  }
 
2022
}
 
2023
 
 
2024
/**
 
2025
 * Shutdown function for cron cleanup.
 
2026
 */
 
2027
function drupal_cron_cleanup() {
 
2028
  // See if the semaphore is still locked.
 
2029
  if (variable_get('cron_semaphore', FALSE)) {
 
2030
    watchdog('cron', t('Cron run exceeded the time limit and was aborted.'), WATCHDOG_WARNING);
 
2031
 
 
2032
    // Release cron semaphore
 
2033
    variable_del('cron_semaphore');
 
2034
  }
 
2035
}
 
2036
 
 
2037
/**
 
2038
 * Returns an array of files objects of the given type from the site-wide
 
2039
 * directory (i.e. modules/), the all-sites directory (i.e.
 
2040
 * sites/all/modules/), the profiles directory, and site-specific directory
 
2041
 * (i.e. sites/somesite/modules/). The returned array will be keyed using the
 
2042
 * key specified (name, basename, filename). Using name or basename will cause
 
2043
 * site-specific files to be prioritized over similar files in the default
 
2044
 * directories. That is, if a file with the same name appears in both the
 
2045
 * site-wide directory and site-specific directory, only the site-specific
 
2046
 * version will be included.
 
2047
 *
 
2048
 * @param $mask
 
2049
 *   The regular expression of the files to find.
 
2050
 * @param $directory
 
2051
 *   The subdirectory name in which the files are found. For example,
 
2052
 *   'modules' will search in both modules/ and
 
2053
 *   sites/somesite/modules/.
 
2054
 * @param $key
 
2055
 *   The key to be passed to file_scan_directory().
 
2056
 * @param $min_depth
 
2057
 *   Minimum depth of directories to return files from.
 
2058
 *
 
2059
 * @return
 
2060
 *   An array of file objects of the specified type.
 
2061
 */
 
2062
function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
 
2063
  global $profile;
 
2064
  $config = conf_path();
 
2065
 
 
2066
  // When this function is called during Drupal's initial installation process,
 
2067
  // the name of the profile that's about to be installed is stored in the global
 
2068
  // $profile variable. At all other times, the standard Drupal systems variable
 
2069
  // table contains the name of the current profile, and we can call variable_get()
 
2070
  // to determine what one is active.
 
2071
  if (!isset($profile)) {
 
2072
    $profile = variable_get('install_profile', 'default');
 
2073
  }
 
2074
  $searchdir = array($directory);
 
2075
  $files = array();
 
2076
 
 
2077
  // Always search sites/all/* as well as the global directories
 
2078
  $searchdir[] = 'sites/all/'. $directory;
 
2079
 
 
2080
  // The 'profiles' directory contains pristine collections of modules and
 
2081
  // themes as organized by a distribution.  It is pristine in the same way
 
2082
  // that /modules is pristine for core; users should avoid changing anything
 
2083
  // there in favor of sites/all or sites/<domain> directories.
 
2084
  if (file_exists("profiles/$profile/$directory")) {
 
2085
    $searchdir[] = "profiles/$profile/$directory";
 
2086
  }
 
2087
 
 
2088
  if (file_exists("$config/$directory")) {
 
2089
    $searchdir[] = "$config/$directory";
 
2090
  }
 
2091
 
 
2092
  // Get current list of items
 
2093
  foreach ($searchdir as $dir) {
 
2094
    $files = array_merge($files, file_scan_directory($dir, $mask, array('.', '..', 'CVS'), 0, TRUE, $key, $min_depth));
 
2095
  }
 
2096
 
 
2097
  return $files;
 
2098
}
 
2099
 
 
2100
/**
 
2101
 * Renders HTML given a structured array tree. Recursively iterates over each
 
2102
 * of the array elements, generating HTML code. This function is usually
 
2103
 * called from within a another function, like drupal_get_form() or node_view().
 
2104
 *
 
2105
 * @param $elements
 
2106
 *   The structured array describing the data to be rendered.
 
2107
 * @return
 
2108
 *   The rendered HTML.
 
2109
 */
 
2110
function drupal_render(&$elements) {
 
2111
  if (!isset($elements) || (isset($elements['#access']) && !$elements['#access'])) {
 
2112
    return NULL;
 
2113
  }
 
2114
 
 
2115
  $content = '';
 
2116
  // Either the elements did not go through form_builder or one of the children
 
2117
  // has a #weight.
 
2118
  if (!isset($elements['#sorted'])) {
 
2119
    uasort($elements, "_element_sort");
 
2120
  }
 
2121
  if (!isset($elements['#children'])) {
 
2122
    $children = element_children($elements);
 
2123
    /* Render all the children that use a theme function */
 
2124
    if (isset($elements['#theme']) && empty($elements['#theme_used'])) {
 
2125
      $elements['#theme_used'] = TRUE;
 
2126
 
 
2127
      $previous = array();
 
2128
      foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
 
2129
        $previous[$key] = isset($elements[$key]) ? $elements[$key] : NULL;
 
2130
      }
 
2131
      // If we rendered a single element, then we will skip the renderer.
 
2132
      if (empty($children)) {
 
2133
        $elements['#printed'] = TRUE;
 
2134
      }
 
2135
      else {
 
2136
        $elements['#value'] = '';
 
2137
      }
 
2138
      $elements['#type'] = 'markup';
 
2139
 
 
2140
      unset($elements['#prefix'], $elements['#suffix']);
 
2141
      $content = theme($elements['#theme'], $elements);
 
2142
 
 
2143
      foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
 
2144
        $elements[$key] = isset($previous[$key]) ? $previous[$key] : NULL;
 
2145
      }
 
2146
    }
 
2147
    /* render each of the children using drupal_render and concatenate them */
 
2148
    if (!isset($content) || $content === '') {
 
2149
      foreach ($children as $key) {
 
2150
        $content .= drupal_render($elements[$key]);
 
2151
      }
 
2152
    }
 
2153
  }
 
2154
  if (isset($content) && $content !== '') {
 
2155
    $elements['#children'] = $content;
 
2156
  }
 
2157
 
 
2158
  // Until now, we rendered the children, here we render the element itself
 
2159
  if (!isset($elements['#printed'])) {
 
2160
    $content = theme(!empty($elements['#type']) ? $elements['#type'] : 'markup', $elements);
 
2161
    $elements['#printed'] = TRUE;
 
2162
  }
 
2163
 
 
2164
  if (isset($content) && $content !== '') {
 
2165
    $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
 
2166
    $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
 
2167
    return $prefix . $content . $suffix;
 
2168
  }
 
2169
}
 
2170
 
 
2171
/**
 
2172
 * Function used by uasort in drupal_render() to sort structured arrays
 
2173
 * by weight.
 
2174
 */
 
2175
function _element_sort($a, $b) {
 
2176
  $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
 
2177
  $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
 
2178
  if ($a_weight == $b_weight) {
 
2179
    return 0;
 
2180
  }
 
2181
  return ($a_weight < $b_weight) ? -1 : 1;
 
2182
}
 
2183
 
 
2184
/**
 
2185
 * Check if the key is a property.
 
2186
 */
 
2187
function element_property($key) {
 
2188
  return $key[0] == '#';
 
2189
}
 
2190
 
 
2191
/**
 
2192
 * Get properties of a structured array element. Properties begin with '#'.
 
2193
 */
 
2194
function element_properties($element) {
 
2195
  return array_filter(array_keys((array) $element), 'element_property');
 
2196
}
 
2197
 
 
2198
/**
 
2199
 * Check if the key is a child.
 
2200
 */
 
2201
function element_child($key) {
 
2202
  return $key[0] != '#';
 
2203
}
 
2204
 
 
2205
/**
 
2206
 * Get keys of a structured array tree element that are not properties
 
2207
 * (i.e., do not begin with '#').
 
2208
 */
 
2209
function element_children($element) {
 
2210
  return array_filter(array_keys((array) $element), 'element_child');
 
2211
}