Project

General

Profile

Paste
Download (308 KB) Statistics
| Branch: | Revision:

root / drupal7 / includes / common.inc @ cd5c298a

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
 * @defgroup php_wrappers PHP wrapper functions
13
 * @{
14
 * Functions that are wrappers or custom implementations of PHP functions.
15
 *
16
 * Certain PHP functions should not be used in Drupal. Instead, Drupal's
17
 * replacement functions should be used.
18
 *
19
 * For example, for improved or more secure UTF8-handling, or RFC-compliant
20
 * handling of URLs in Drupal.
21
 *
22
 * For ease of use and memorizing, all these wrapper functions use the same name
23
 * as the original PHP function, but prefixed with "drupal_". Beware, however,
24
 * that not all wrapper functions support the same arguments as the original
25
 * functions.
26
 *
27
 * You should always use these wrapper functions in your code.
28
 *
29
 * Wrong:
30
 * @code
31
 *   $my_substring = substr($original_string, 0, 5);
32
 * @endcode
33
 *
34
 * Correct:
35
 * @code
36
 *   $my_substring = drupal_substr($original_string, 0, 5);
37
 * @endcode
38
 *
39
 * @}
40
 */
41

    
42
/**
43
 * Return status for saving which involved creating a new item.
44
 */
45
define('SAVED_NEW', 1);
46

    
47
/**
48
 * Return status for saving which involved an update to an existing item.
49
 */
50
define('SAVED_UPDATED', 2);
51

    
52
/**
53
 * Return status for saving which deleted an existing item.
54
 */
55
define('SAVED_DELETED', 3);
56

    
57
/**
58
 * The default group for system CSS files added to the page.
59
 */
60
define('CSS_SYSTEM', -100);
61

    
62
/**
63
 * The default group for module CSS files added to the page.
64
 */
65
define('CSS_DEFAULT', 0);
66

    
67
/**
68
 * The default group for theme CSS files added to the page.
69
 */
70
define('CSS_THEME', 100);
71

    
72
/**
73
 * The default group for JavaScript and jQuery libraries added to the page.
74
 */
75
define('JS_LIBRARY', -100);
76

    
77
/**
78
 * The default group for module JavaScript code added to the page.
79
 */
80
define('JS_DEFAULT', 0);
81

    
82
/**
83
 * The default group for theme JavaScript code added to the page.
84
 */
85
define('JS_THEME', 100);
86

    
87
/**
88
 * Error code indicating that the request exceeded the specified timeout.
89
 *
90
 * @see drupal_http_request()
91
 */
92
define('HTTP_REQUEST_TIMEOUT', -1);
93

    
94
/**
95
 * @defgroup block_caching Block Caching
96
 * @{
97
 * Constants that define each block's caching state.
98
 *
99
 * Modules specify how their blocks can be cached in their hook_block_info()
100
 * implementations. Caching can be turned off (DRUPAL_NO_CACHE), managed by the
101
 * module declaring the block (DRUPAL_CACHE_CUSTOM), or managed by the core
102
 * Block module. If the Block module is managing the cache, you can specify that
103
 * the block is the same for every page and user (DRUPAL_CACHE_GLOBAL), or that
104
 * it can change depending on the page (DRUPAL_CACHE_PER_PAGE) or by user
105
 * (DRUPAL_CACHE_PER_ROLE or DRUPAL_CACHE_PER_USER). Page and user settings can
106
 * be combined with a bitwise-binary or operator; for example,
107
 * DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE means that the block can change
108
 * depending on the user role or page it is on.
109
 *
110
 * The block cache is cleared in cache_clear_all(), and uses the same clearing
111
 * policy than page cache (node, comment, user, taxonomy added or updated...).
112
 * Blocks requiring more fine-grained clearing might consider disabling the
113
 * built-in block cache (DRUPAL_NO_CACHE) and roll their own.
114
 *
115
 * Note that user 1 is excluded from block caching.
116
 */
117

    
118
/**
119
 * The block should not get cached.
120
 *
121
 * This setting should be used:
122
 * - For simple blocks (notably those that do not perform any db query), where
123
 *   querying the db cache would be more expensive than directly generating the
124
 *   content.
125
 * - For blocks that change too frequently.
126
 */
127
define('DRUPAL_NO_CACHE', -1);
128

    
129
/**
130
 * The block is handling its own caching in its hook_block_view().
131
 *
132
 * This setting is useful when time based expiration is needed or a site uses a
133
 * node access which invalidates standard block cache.
134
 */
135
define('DRUPAL_CACHE_CUSTOM', -2);
136

    
137
/**
138
 * The block or element can change depending on the user's roles.
139
 *
140
 * This is the default setting for blocks, used when the block does not specify
141
 * anything.
142
 */
143
define('DRUPAL_CACHE_PER_ROLE', 0x0001);
144

    
145
/**
146
 * The block or element can change depending on the user.
147
 *
148
 * This setting can be resource-consuming for sites with large number of users,
149
 * and thus should only be used when DRUPAL_CACHE_PER_ROLE is not sufficient.
150
 */
151
define('DRUPAL_CACHE_PER_USER', 0x0002);
152

    
153
/**
154
 * The block or element can change depending on the page being viewed.
155
 */
156
define('DRUPAL_CACHE_PER_PAGE', 0x0004);
157

    
158
/**
159
 * The block or element is the same for every user and page that it is visible.
160
 */
161
define('DRUPAL_CACHE_GLOBAL', 0x0008);
162

    
163
/**
164
 * @} End of "defgroup block_caching".
165
 */
166

    
167
/**
168
 * Adds content to a specified region.
169
 *
170
 * @param $region
171
 *   Page region the content is added to.
172
 * @param $data
173
 *   Content to be added.
174
 */
175
function drupal_add_region_content($region = NULL, $data = NULL) {
176
  static $content = array();
177

    
178
  if (isset($region) && isset($data)) {
179
    $content[$region][] = $data;
180
  }
181
  return $content;
182
}
183

    
184
/**
185
 * Gets assigned content for a given region.
186
 *
187
 * @param $region
188
 *   A specified region to fetch content for. If NULL, all regions will be
189
 *   returned.
190
 * @param $delimiter
191
 *   Content to be inserted between imploded array elements.
192
 */
193
function drupal_get_region_content($region = NULL, $delimiter = ' ') {
194
  $content = drupal_add_region_content();
195
  if (isset($region)) {
196
    if (isset($content[$region]) && is_array($content[$region])) {
197
      return implode($delimiter, $content[$region]);
198
    }
199
  }
200
  else {
201
    foreach (array_keys($content) as $region) {
202
      if (is_array($content[$region])) {
203
        $content[$region] = implode($delimiter, $content[$region]);
204
      }
205
    }
206
    return $content;
207
  }
208
}
209

    
210
/**
211
 * Gets the name of the currently active installation profile.
212
 *
213
 * When this function is called during Drupal's initial installation process,
214
 * the name of the profile that's about to be installed is stored in the global
215
 * installation state. At all other times, the standard Drupal systems variable
216
 * table contains the name of the current profile, and we can call
217
 * variable_get() to determine what one is active.
218
 *
219
 * @return $profile
220
 *   The name of the installation profile.
221
 */
222
function drupal_get_profile() {
223
  global $install_state;
224

    
225
  if (isset($install_state['parameters']['profile'])) {
226
    $profile = $install_state['parameters']['profile'];
227
  }
228
  else {
229
    $profile = variable_get('install_profile', 'standard');
230
  }
231

    
232
  return $profile;
233
}
234

    
235

    
236
/**
237
 * Sets the breadcrumb trail for the current page.
238
 *
239
 * @param $breadcrumb
240
 *   Array of links, starting with "home" and proceeding up to but not including
241
 *   the current page.
242
 */
243
function drupal_set_breadcrumb($breadcrumb = NULL) {
244
  $stored_breadcrumb = &drupal_static(__FUNCTION__);
245

    
246
  if (isset($breadcrumb)) {
247
    $stored_breadcrumb = $breadcrumb;
248
  }
249
  return $stored_breadcrumb;
250
}
251

    
252
/**
253
 * Gets the breadcrumb trail for the current page.
254
 */
255
function drupal_get_breadcrumb() {
256
  $breadcrumb = drupal_set_breadcrumb();
257

    
258
  if (!isset($breadcrumb)) {
259
    $breadcrumb = menu_get_active_breadcrumb();
260
  }
261

    
262
  return $breadcrumb;
263
}
264

    
265
/**
266
 * Returns a string containing RDF namespace declarations for use in XML and
267
 * XHTML output.
268
 */
269
function drupal_get_rdf_namespaces() {
270
  $xml_rdf_namespaces = array();
271

    
272
  // Serializes the RDF namespaces in XML namespace syntax.
273
  if (function_exists('rdf_get_namespaces')) {
274
    foreach (rdf_get_namespaces() as $prefix => $uri) {
275
      $xml_rdf_namespaces[] = 'xmlns:' . $prefix . '="' . $uri . '"';
276
    }
277
  }
278
  return count($xml_rdf_namespaces) ? "\n  " . implode("\n  ", $xml_rdf_namespaces) : '';
279
}
280

    
281
/**
282
 * Adds output to the HEAD tag of the HTML page.
283
 *
284
 * This function can be called as long as the headers aren't sent. Pass no
285
 * arguments (or NULL for both) to retrieve the currently stored elements.
286
 *
287
 * @param $data
288
 *   A renderable array. If the '#type' key is not set then 'html_tag' will be
289
 *   added as the default '#type'.
290
 * @param $key
291
 *   A unique string key to allow implementations of hook_html_head_alter() to
292
 *   identify the element in $data. Required if $data is not NULL.
293
 *
294
 * @return
295
 *   An array of all stored HEAD elements.
296
 *
297
 * @see theme_html_tag()
298
 */
299
function drupal_add_html_head($data = NULL, $key = NULL) {
300
  $stored_head = &drupal_static(__FUNCTION__);
301

    
302
  if (!isset($stored_head)) {
303
    // Make sure the defaults, including Content-Type, come first.
304
    $stored_head = _drupal_default_html_head();
305
  }
306

    
307
  if (isset($data) && isset($key)) {
308
    if (!isset($data['#type'])) {
309
      $data['#type'] = 'html_tag';
310
    }
311
    $stored_head[$key] = $data;
312
  }
313
  return $stored_head;
314
}
315

    
316
/**
317
 * Returns elements that are always displayed in the HEAD tag of the HTML page.
318
 */
319
function _drupal_default_html_head() {
320
  // Add default elements. Make sure the Content-Type comes first because the
321
  // IE browser may be vulnerable to XSS via encoding attacks from any content
322
  // that comes before this META tag, such as a TITLE tag.
323
  $elements['system_meta_content_type'] = array(
324
    '#type' => 'html_tag',
325
    '#tag' => 'meta',
326
    '#attributes' => array(
327
      'http-equiv' => 'Content-Type',
328
      'content' => 'text/html; charset=utf-8',
329
    ),
330
    // Security: This always has to be output first.
331
    '#weight' => -1000,
332
  );
333
  // Show Drupal and the major version number in the META GENERATOR tag.
334
  // Get the major version.
335
  list($version, ) = explode('.', VERSION);
336
  $elements['system_meta_generator'] = array(
337
    '#type' => 'html_tag',
338
    '#tag' => 'meta',
339
    '#attributes' => array(
340
      'name' => 'Generator',
341
      'content' => 'Drupal ' . $version . ' (http://drupal.org)',
342
    ),
343
  );
344
  // Also send the generator in the HTTP header.
345
  $elements['system_meta_generator']['#attached']['drupal_add_http_header'][] = array('X-Generator', $elements['system_meta_generator']['#attributes']['content']);
346
  return $elements;
347
}
348

    
349
/**
350
 * Retrieves output to be displayed in the HEAD tag of the HTML page.
351
 */
352
function drupal_get_html_head() {
353
  $elements = drupal_add_html_head();
354
  drupal_alter('html_head', $elements);
355
  return drupal_render($elements);
356
}
357

    
358
/**
359
 * Adds a feed URL for the current page.
360
 *
361
 * This function can be called as long the HTML header hasn't been sent.
362
 *
363
 * @param $url
364
 *   An internal system path or a fully qualified external URL of the feed.
365
 * @param $title
366
 *   The title of the feed.
367
 */
368
function drupal_add_feed($url = NULL, $title = '') {
369
  $stored_feed_links = &drupal_static(__FUNCTION__, array());
370

    
371
  if (isset($url)) {
372
    $stored_feed_links[$url] = theme('feed_icon', array('url' => $url, 'title' => $title));
373

    
374
    drupal_add_html_head_link(array(
375
      'rel' => 'alternate',
376
      'type' => 'application/rss+xml',
377
      'title' => $title,
378
      // Force the URL to be absolute, for consistency with other <link> tags
379
      // output by Drupal.
380
      'href' => url($url, array('absolute' => TRUE)),
381
    ));
382
  }
383
  return $stored_feed_links;
384
}
385

    
386
/**
387
 * Gets the feed URLs for the current page.
388
 *
389
 * @param $delimiter
390
 *   A delimiter to split feeds by.
391
 */
392
function drupal_get_feeds($delimiter = "\n") {
393
  $feeds = drupal_add_feed();
394
  return implode($feeds, $delimiter);
395
}
396

    
397
/**
398
 * @defgroup http_handling HTTP handling
399
 * @{
400
 * Functions to properly handle HTTP responses.
401
 */
402

    
403
/**
404
 * Processes a URL query parameter array to remove unwanted elements.
405
 *
406
 * @param $query
407
 *   (optional) An array to be processed. Defaults to $_GET.
408
 * @param $exclude
409
 *   (optional) A list of $query array keys to remove. Use "parent[child]" to
410
 *   exclude nested items. Defaults to array('q').
411
 * @param $parent
412
 *   Internal use only. Used to build the $query array key for nested items.
413
 *
414
 * @return
415
 *   An array containing query parameters, which can be used for url().
416
 */
417
function drupal_get_query_parameters(array $query = NULL, array $exclude = array('q'), $parent = '') {
418
  // Set defaults, if none given.
419
  if (!isset($query)) {
420
    $query = $_GET;
421
  }
422
  // If $exclude is empty, there is nothing to filter.
423
  if (empty($exclude)) {
424
    return $query;
425
  }
426
  elseif (!$parent) {
427
    $exclude = array_flip($exclude);
428
  }
429

    
430
  $params = array();
431
  foreach ($query as $key => $value) {
432
    $string_key = ($parent ? $parent . '[' . $key . ']' : $key);
433
    if (isset($exclude[$string_key])) {
434
      continue;
435
    }
436

    
437
    if (is_array($value)) {
438
      $params[$key] = drupal_get_query_parameters($value, $exclude, $string_key);
439
    }
440
    else {
441
      $params[$key] = $value;
442
    }
443
  }
444

    
445
  return $params;
446
}
447

    
448
/**
449
 * Splits a URL-encoded query string into an array.
450
 *
451
 * @param $query
452
 *   The query string to split.
453
 *
454
 * @return
455
 *   An array of URL decoded couples $param_name => $value.
456
 */
457
function drupal_get_query_array($query) {
458
  $result = array();
459
  if (!empty($query)) {
460
    foreach (explode('&', $query) as $param) {
461
      $param = explode('=', $param, 2);
462
      $result[$param[0]] = isset($param[1]) ? rawurldecode($param[1]) : '';
463
    }
464
  }
465
  return $result;
466
}
467

    
468
/**
469
 * Parses an array into a valid, rawurlencoded query string.
470
 *
471
 * This differs from http_build_query() as we need to rawurlencode() (instead of
472
 * urlencode()) all query parameters.
473
 *
474
 * @param $query
475
 *   The query parameter array to be processed, e.g. $_GET.
476
 * @param $parent
477
 *   Internal use only. Used to build the $query array key for nested items.
478
 *
479
 * @return
480
 *   A rawurlencoded string which can be used as or appended to the URL query
481
 *   string.
482
 *
483
 * @see drupal_get_query_parameters()
484
 * @ingroup php_wrappers
485
 */
486
function drupal_http_build_query(array $query, $parent = '') {
487
  $params = array();
488

    
489
  foreach ($query as $key => $value) {
490
    $key = $parent ? $parent . rawurlencode('[' . $key . ']') : rawurlencode($key);
491

    
492
    // Recurse into children.
493
    if (is_array($value)) {
494
      $params[] = drupal_http_build_query($value, $key);
495
    }
496
    // If a query parameter value is NULL, only append its key.
497
    elseif (!isset($value)) {
498
      $params[] = $key;
499
    }
500
    else {
501
      // For better readability of paths in query strings, we decode slashes.
502
      $params[] = $key . '=' . str_replace('%2F', '/', rawurlencode($value));
503
    }
504
  }
505

    
506
  return implode('&', $params);
507
}
508

    
509
/**
510
 * Prepares a 'destination' URL query parameter for use with drupal_goto().
511
 *
512
 * Used to direct the user back to the referring page after completing a form.
513
 * By default the current URL is returned. If a destination exists in the
514
 * previous request, that destination is returned. As such, a destination can
515
 * persist across multiple pages.
516
 *
517
 * @return
518
 *   An associative array containing the key:
519
 *   - destination: The path provided via the destination query string or, if
520
 *     not available, the current path.
521
 *
522
 * @see current_path()
523
 * @see drupal_goto()
524
 */
525
function drupal_get_destination() {
526
  $destination = &drupal_static(__FUNCTION__);
527

    
528
  if (isset($destination)) {
529
    return $destination;
530
  }
531

    
532
  if (isset($_GET['destination'])) {
533
    $destination = array('destination' => $_GET['destination']);
534
  }
535
  else {
536
    $path = $_GET['q'];
537
    $query = drupal_http_build_query(drupal_get_query_parameters());
538
    if ($query != '') {
539
      $path .= '?' . $query;
540
    }
541
    $destination = array('destination' => $path);
542
  }
543
  return $destination;
544
}
545

    
546
/**
547
 * Parses a URL string into its path, query, and fragment components.
548
 *
549
 * This function splits both internal paths like @code node?b=c#d @endcode and
550
 * external URLs like @code https://example.com/a?b=c#d @endcode into their
551
 * component parts. See
552
 * @link http://tools.ietf.org/html/rfc3986#section-3 RFC 3986 @endlink for an
553
 * explanation of what the component parts are.
554
 *
555
 * Note that, unlike the RFC, when passed an external URL, this function
556
 * groups the scheme, authority, and path together into the path component.
557
 *
558
 * @param string $url
559
 *   The internal path or external URL string to parse.
560
 *
561
 * @return array
562
 *   An associative array containing:
563
 *   - path: The path component of $url. If $url is an external URL, this
564
 *     includes the scheme, authority, and path.
565
 *   - query: An array of query parameters from $url, if they exist.
566
 *   - fragment: The fragment component from $url, if it exists.
567
 *
568
 * @see drupal_goto()
569
 * @see l()
570
 * @see url()
571
 * @see http://tools.ietf.org/html/rfc3986
572
 *
573
 * @ingroup php_wrappers
574
 */
575
function drupal_parse_url($url) {
576
  $options = array(
577
    'path' => NULL,
578
    'query' => array(),
579
    'fragment' => '',
580
  );
581

    
582
  // External URLs: not using parse_url() here, so we do not have to rebuild
583
  // the scheme, host, and path without having any use for it.
584
  if (strpos($url, '://') !== FALSE) {
585
    // Split off everything before the query string into 'path'.
586
    $parts = explode('?', $url);
587
    $options['path'] = $parts[0];
588
    // If there is a query string, transform it into keyed query parameters.
589
    if (isset($parts[1])) {
590
      $query_parts = explode('#', $parts[1]);
591
      parse_str($query_parts[0], $options['query']);
592
      // Take over the fragment, if there is any.
593
      if (isset($query_parts[1])) {
594
        $options['fragment'] = $query_parts[1];
595
      }
596
    }
597
  }
598
  // Internal URLs.
599
  else {
600
    // parse_url() does not support relative URLs, so make it absolute. E.g. the
601
    // relative URL "foo/bar:1" isn't properly parsed.
602
    $parts = parse_url('http://example.com/' . $url);
603
    // Strip the leading slash that was just added.
604
    $options['path'] = substr($parts['path'], 1);
605
    if (isset($parts['query'])) {
606
      parse_str($parts['query'], $options['query']);
607
    }
608
    if (isset($parts['fragment'])) {
609
      $options['fragment'] = $parts['fragment'];
610
    }
611
  }
612
  // The 'q' parameter contains the path of the current page if clean URLs are
613
  // disabled. It overrides the 'path' of the URL when present, even if clean
614
  // URLs are enabled, due to how Apache rewriting rules work. The path
615
  // parameter must be a string.
616
  if (isset($options['query']['q']) && is_string($options['query']['q'])) {
617
    $options['path'] = $options['query']['q'];
618
    unset($options['query']['q']);
619
  }
620

    
621
  return $options;
622
}
623

    
624
/**
625
 * Encodes a Drupal path for use in a URL.
626
 *
627
 * For aesthetic reasons slashes are not escaped.
628
 *
629
 * Note that url() takes care of calling this function, so a path passed to that
630
 * function should not be encoded in advance.
631
 *
632
 * @param $path
633
 *   The Drupal path to encode.
634
 */
635
function drupal_encode_path($path) {
636
  return str_replace('%2F', '/', rawurlencode($path));
637
}
638

    
639
/**
640
 * Sends the user to a different page.
641
 *
642
 * This issues an on-site HTTP redirect. The function makes sure the redirected
643
 * URL is formatted correctly.
644
 *
645
 * Usually the redirected URL is constructed from this function's input
646
 * parameters. However you may override that behavior by setting a
647
 * destination in either the $_REQUEST-array (i.e. by using
648
 * the query string of an URI) This is used to direct the user back to
649
 * the proper page after completing a form. For example, after editing
650
 * a post on the 'admin/content'-page or after having logged on using the
651
 * 'user login'-block in a sidebar. The function drupal_get_destination()
652
 * can be used to help set the destination URL.
653
 *
654
 * Drupal will ensure that messages set by drupal_set_message() and other
655
 * session data are written to the database before the user is redirected.
656
 *
657
 * This function ends the request; use it instead of a return in your menu
658
 * callback.
659
 *
660
 * @param $path
661
 *   (optional) A Drupal path or a full URL, which will be passed to url() to
662
 *   compute the redirect for the URL.
663
 * @param $options
664
 *   (optional) An associative array of additional URL options to pass to url().
665
 * @param $http_response_code
666
 *   (optional) The HTTP status code to use for the redirection, defaults to
667
 *   302. The valid values for 3xx redirection status codes are defined in
668
 *   @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3 RFC 2616 @endlink
669
 *   and the
670
 *   @link http://tools.ietf.org/html/draft-reschke-http-status-308-07 draft for the new HTTP status codes: @endlink
671
 *   - 301: Moved Permanently (the recommended value for most redirects).
672
 *   - 302: Found (default in Drupal and PHP, sometimes used for spamming search
673
 *     engines).
674
 *   - 303: See Other.
675
 *   - 304: Not Modified.
676
 *   - 305: Use Proxy.
677
 *   - 307: Temporary Redirect.
678
 *
679
 * @see drupal_get_destination()
680
 * @see url()
681
 */
682
function drupal_goto($path = '', array $options = array(), $http_response_code = 302) {
683
  // A destination in $_GET always overrides the function arguments.
684
  // We do not allow absolute URLs to be passed via $_GET, as this can be an attack vector.
685
  if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
686
    $destination = drupal_parse_url($_GET['destination']);
687
    $path = $destination['path'];
688
    $options['query'] = $destination['query'];
689
    $options['fragment'] = $destination['fragment'];
690
  }
691

    
692
  // In some cases modules call drupal_goto(current_path()). We need to ensure
693
  // that such a redirect is not to an external URL.
694
  if ($path === current_path() && empty($options['external']) && url_is_external($path)) {
695
    // Force url() to generate a non-external URL.
696
    $options['external'] = FALSE;
697
  }
698

    
699
  drupal_alter('drupal_goto', $path, $options, $http_response_code);
700

    
701
  // The 'Location' HTTP header must be absolute.
702
  $options['absolute'] = TRUE;
703

    
704
  $url = url($path, $options);
705

    
706
  header('Location: ' . $url, TRUE, $http_response_code);
707

    
708
  // The "Location" header sends a redirect status code to the HTTP daemon. In
709
  // some cases this can be wrong, so we make sure none of the code below the
710
  // drupal_goto() call gets executed upon redirection.
711
  drupal_exit($url);
712
}
713

    
714
/**
715
 * Delivers a "site is under maintenance" message to the browser.
716
 *
717
 * Page callback functions wanting to report a "site offline" message should
718
 * return MENU_SITE_OFFLINE instead of calling drupal_site_offline(). However,
719
 * functions that are invoked in contexts where that return value might not
720
 * bubble up to menu_execute_active_handler() should call drupal_site_offline().
721
 */
722
function drupal_site_offline() {
723
  drupal_deliver_page(MENU_SITE_OFFLINE);
724
}
725

    
726
/**
727
 * Delivers a "page not found" error to the browser.
728
 *
729
 * Page callback functions wanting to report a "page not found" message should
730
 * return MENU_NOT_FOUND instead of calling drupal_not_found(). However,
731
 * functions that are invoked in contexts where that return value might not
732
 * bubble up to menu_execute_active_handler() should call drupal_not_found().
733
 */
734
function drupal_not_found() {
735
  drupal_deliver_page(MENU_NOT_FOUND);
736
}
737

    
738
/**
739
 * Delivers an "access denied" error to the browser.
740
 *
741
 * Page callback functions wanting to report an "access denied" message should
742
 * return MENU_ACCESS_DENIED instead of calling drupal_access_denied(). However,
743
 * functions that are invoked in contexts where that return value might not
744
 * bubble up to menu_execute_active_handler() should call
745
 * drupal_access_denied().
746
 */
747
function drupal_access_denied() {
748
  drupal_deliver_page(MENU_ACCESS_DENIED);
749
}
750

    
751
/**
752
 * Performs an HTTP request.
753
 *
754
 * This is a flexible and powerful HTTP client implementation. Correctly
755
 * handles GET, POST, PUT or any other HTTP requests. Handles redirects.
756
 *
757
 * @param $url
758
 *   A string containing a fully qualified URI.
759
 * @param array $options
760
 *   (optional) An array that can have one or more of the following elements:
761
 *   - headers: An array containing request headers to send as name/value pairs.
762
 *   - method: A string containing the request method. Defaults to 'GET'.
763
 *   - data: A string containing the request body, formatted as
764
 *     'param=value&param=value&...'; to generate this, use http_build_query().
765
 *     Defaults to NULL.
766
 *   - max_redirects: An integer representing how many times a redirect
767
 *     may be followed. Defaults to 3.
768
 *   - timeout: A float representing the maximum number of seconds the function
769
 *     call may take. The default is 30 seconds. If a timeout occurs, the error
770
 *     code is set to the HTTP_REQUEST_TIMEOUT constant.
771
 *   - context: A context resource created with stream_context_create().
772
 *
773
 * @return object
774
 *   An object that can have one or more of the following components:
775
 *   - request: A string containing the request body that was sent.
776
 *   - code: An integer containing the response status code, or the error code
777
 *     if an error occurred.
778
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
779
 *   - status_message: The status message from the response, if a response was
780
 *     received.
781
 *   - redirect_code: If redirected, an integer containing the initial response
782
 *     status code.
783
 *   - redirect_url: If redirected, a string containing the URL of the redirect
784
 *     target.
785
 *   - error: If an error occurred, the error message. Otherwise not set.
786
 *   - headers: An array containing the response headers as name/value pairs.
787
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
788
 *     easy access the array keys are returned in lower case.
789
 *   - data: A string containing the response body that was received.
790
 *
791
 * @see http_build_query()
792
 */
793
function drupal_http_request($url, array $options = array()) {
794
  // Allow an alternate HTTP client library to replace Drupal's default
795
  // implementation.
796
  $override_function = variable_get('drupal_http_request_function', FALSE);
797
  if (!empty($override_function) && function_exists($override_function)) {
798
    return $override_function($url, $options);
799
  }
800

    
801
  $result = new stdClass();
802

    
803
  // Parse the URL and make sure we can handle the schema.
804
  $uri = @parse_url($url);
805

    
806
  if ($uri == FALSE) {
807
    $result->error = 'unable to parse URL';
808
    $result->code = -1001;
809
    return $result;
810
  }
811

    
812
  if (!isset($uri['scheme'])) {
813
    $result->error = 'missing schema';
814
    $result->code = -1002;
815
    return $result;
816
  }
817

    
818
  timer_start(__FUNCTION__);
819

    
820
  // Merge the default options.
821
  $options += array(
822
    'headers' => array(),
823
    'method' => 'GET',
824
    'data' => NULL,
825
    'max_redirects' => 3,
826
    'timeout' => 30.0,
827
    'context' => NULL,
828
  );
829

    
830
  // Merge the default headers.
831
  $options['headers'] += array(
832
    'User-Agent' => 'Drupal (+http://drupal.org/)',
833
  );
834

    
835
  // stream_socket_client() requires timeout to be a float.
836
  $options['timeout'] = (float) $options['timeout'];
837

    
838
  // Use a proxy if one is defined and the host is not on the excluded list.
839
  $proxy_server = variable_get('proxy_server', '');
840
  if ($proxy_server && _drupal_http_use_proxy($uri['host'])) {
841
    // Set the scheme so we open a socket to the proxy server.
842
    $uri['scheme'] = 'proxy';
843
    // Set the path to be the full URL.
844
    $uri['path'] = $url;
845
    // Since the URL is passed as the path, we won't use the parsed query.
846
    unset($uri['query']);
847

    
848
    // Add in username and password to Proxy-Authorization header if needed.
849
    if ($proxy_username = variable_get('proxy_username', '')) {
850
      $proxy_password = variable_get('proxy_password', '');
851
      $options['headers']['Proxy-Authorization'] = 'Basic ' . base64_encode($proxy_username . (!empty($proxy_password) ? ":" . $proxy_password : ''));
852
    }
853
    // Some proxies reject requests with any User-Agent headers, while others
854
    // require a specific one.
855
    $proxy_user_agent = variable_get('proxy_user_agent', '');
856
    // The default value matches neither condition.
857
    if ($proxy_user_agent === NULL) {
858
      unset($options['headers']['User-Agent']);
859
    }
860
    elseif ($proxy_user_agent) {
861
      $options['headers']['User-Agent'] = $proxy_user_agent;
862
    }
863
  }
864

    
865
  switch ($uri['scheme']) {
866
    case 'proxy':
867
      // Make the socket connection to a proxy server.
868
      $socket = 'tcp://' . $proxy_server . ':' . variable_get('proxy_port', 8080);
869
      // The Host header still needs to match the real request.
870
      if (!isset($options['headers']['Host'])) {
871
        $options['headers']['Host'] = $uri['host'];
872
        $options['headers']['Host'] .= isset($uri['port']) && $uri['port'] != 80 ? ':' . $uri['port'] : '';
873
      }
874
      break;
875

    
876
    case 'http':
877
    case 'feed':
878
      $port = isset($uri['port']) ? $uri['port'] : 80;
879
      $socket = 'tcp://' . $uri['host'] . ':' . $port;
880
      // RFC 2616: "non-standard ports MUST, default ports MAY be included".
881
      // We don't add the standard port to prevent from breaking rewrite rules
882
      // checking the host that do not take into account the port number.
883
      if (!isset($options['headers']['Host'])) {
884
        $options['headers']['Host'] = $uri['host'] . ($port != 80 ? ':' . $port : '');
885
      }
886
      break;
887

    
888
    case 'https':
889
      // Note: Only works when PHP is compiled with OpenSSL support.
890
      $port = isset($uri['port']) ? $uri['port'] : 443;
891
      $socket = 'ssl://' . $uri['host'] . ':' . $port;
892
      if (!isset($options['headers']['Host'])) {
893
        $options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
894
      }
895
      break;
896

    
897
    default:
898
      $result->error = 'invalid schema ' . $uri['scheme'];
899
      $result->code = -1003;
900
      return $result;
901
  }
902

    
903
  if (empty($options['context'])) {
904
    $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout']);
905
  }
906
  else {
907
    // Create a stream with context. Allows verification of a SSL certificate.
908
    $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
909
  }
910

    
911
  // Make sure the socket opened properly.
912
  if (!$fp) {
913
    // When a network error occurs, we use a negative number so it does not
914
    // clash with the HTTP status codes.
915
    $result->code = -$errno;
916
    $result->error = trim($errstr) ? trim($errstr) : t('Error opening socket @socket', array('@socket' => $socket));
917

    
918
    // Mark that this request failed. This will trigger a check of the web
919
    // server's ability to make outgoing HTTP requests the next time that
920
    // requirements checking is performed.
921
    // See system_requirements().
922
    variable_set('drupal_http_request_fails', TRUE);
923

    
924
    return $result;
925
  }
926

    
927
  // Construct the path to act on.
928
  $path = isset($uri['path']) ? $uri['path'] : '/';
929
  if (isset($uri['query'])) {
930
    $path .= '?' . $uri['query'];
931
  }
932

    
933
  // Only add Content-Length if we actually have any content or if it is a POST
934
  // or PUT request. Some non-standard servers get confused by Content-Length in
935
  // at least HEAD/GET requests, and Squid always requires Content-Length in
936
  // POST/PUT requests.
937
  $content_length = strlen($options['data']);
938
  if ($content_length > 0 || $options['method'] == 'POST' || $options['method'] == 'PUT') {
939
    $options['headers']['Content-Length'] = $content_length;
940
  }
941

    
942
  // If the server URL has a user then attempt to use basic authentication.
943
  if (isset($uri['user'])) {
944
    $options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ':'));
945
  }
946

    
947
  // If the database prefix is being used by SimpleTest to run the tests in a copied
948
  // database then set the user-agent header to the database prefix so that any
949
  // calls to other Drupal pages will run the SimpleTest prefixed database. The
950
  // user-agent is used to ensure that multiple testing sessions running at the
951
  // same time won't interfere with each other as they would if the database
952
  // prefix were stored statically in a file or database variable.
953
  $test_info = &$GLOBALS['drupal_test_info'];
954
  if (!empty($test_info['test_run_id'])) {
955
    $options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
956
  }
957

    
958
  $request = $options['method'] . ' ' . $path . " HTTP/1.0\r\n";
959
  foreach ($options['headers'] as $name => $value) {
960
    $request .= $name . ': ' . trim($value) . "\r\n";
961
  }
962
  $request .= "\r\n" . $options['data'];
963
  $result->request = $request;
964
  // Calculate how much time is left of the original timeout value.
965
  $timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
966
  if ($timeout > 0) {
967
    stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
968
    fwrite($fp, $request);
969
  }
970

    
971
  // Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
972
  // and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
973
  // instead must invoke stream_get_meta_data() each iteration.
974
  $info = stream_get_meta_data($fp);
975
  $alive = !$info['eof'] && !$info['timed_out'];
976
  $response = '';
977

    
978
  while ($alive) {
979
    // Calculate how much time is left of the original timeout value.
980
    $timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
981
    if ($timeout <= 0) {
982
      $info['timed_out'] = TRUE;
983
      break;
984
    }
985
    stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
986
    $chunk = fread($fp, 1024);
987
    $response .= $chunk;
988
    $info = stream_get_meta_data($fp);
989
    $alive = !$info['eof'] && !$info['timed_out'] && $chunk;
990
  }
991
  fclose($fp);
992

    
993
  if ($info['timed_out']) {
994
    $result->code = HTTP_REQUEST_TIMEOUT;
995
    $result->error = 'request timed out';
996
    return $result;
997
  }
998
  // Parse response headers from the response body.
999
  // Be tolerant of malformed HTTP responses that separate header and body with
1000
  // \n\n or \r\r instead of \r\n\r\n.
1001
  list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
1002
  $response = preg_split("/\r\n|\n|\r/", $response);
1003

    
1004
  // Parse the response status line.
1005
  $response_status_array = _drupal_parse_response_status(trim(array_shift($response)));
1006
  $result->protocol = $response_status_array['http_version'];
1007
  $result->status_message = $response_status_array['reason_phrase'];
1008
  $code = $response_status_array['response_code'];
1009

    
1010
  $result->headers = array();
1011

    
1012
  // Parse the response headers.
1013
  while ($line = trim(array_shift($response))) {
1014
    list($name, $value) = explode(':', $line, 2);
1015
    $name = strtolower($name);
1016
    if (isset($result->headers[$name]) && $name == 'set-cookie') {
1017
      // RFC 2109: the Set-Cookie response header comprises the token Set-
1018
      // Cookie:, followed by a comma-separated list of one or more cookies.
1019
      $result->headers[$name] .= ',' . trim($value);
1020
    }
1021
    else {
1022
      $result->headers[$name] = trim($value);
1023
    }
1024
  }
1025

    
1026
  $responses = array(
1027
    100 => 'Continue',
1028
    101 => 'Switching Protocols',
1029
    200 => 'OK',
1030
    201 => 'Created',
1031
    202 => 'Accepted',
1032
    203 => 'Non-Authoritative Information',
1033
    204 => 'No Content',
1034
    205 => 'Reset Content',
1035
    206 => 'Partial Content',
1036
    300 => 'Multiple Choices',
1037
    301 => 'Moved Permanently',
1038
    302 => 'Found',
1039
    303 => 'See Other',
1040
    304 => 'Not Modified',
1041
    305 => 'Use Proxy',
1042
    307 => 'Temporary Redirect',
1043
    400 => 'Bad Request',
1044
    401 => 'Unauthorized',
1045
    402 => 'Payment Required',
1046
    403 => 'Forbidden',
1047
    404 => 'Not Found',
1048
    405 => 'Method Not Allowed',
1049
    406 => 'Not Acceptable',
1050
    407 => 'Proxy Authentication Required',
1051
    408 => 'Request Time-out',
1052
    409 => 'Conflict',
1053
    410 => 'Gone',
1054
    411 => 'Length Required',
1055
    412 => 'Precondition Failed',
1056
    413 => 'Request Entity Too Large',
1057
    414 => 'Request-URI Too Large',
1058
    415 => 'Unsupported Media Type',
1059
    416 => 'Requested range not satisfiable',
1060
    417 => 'Expectation Failed',
1061
    500 => 'Internal Server Error',
1062
    501 => 'Not Implemented',
1063
    502 => 'Bad Gateway',
1064
    503 => 'Service Unavailable',
1065
    504 => 'Gateway Time-out',
1066
    505 => 'HTTP Version not supported',
1067
  );
1068
  // RFC 2616 states that all unknown HTTP codes must be treated the same as the
1069
  // base code in their class.
1070
  if (!isset($responses[$code])) {
1071
    $code = floor($code / 100) * 100;
1072
  }
1073
  $result->code = $code;
1074

    
1075
  switch ($code) {
1076
    case 200: // OK
1077
    case 201: // Created
1078
    case 202: // Accepted
1079
    case 203: // Non-Authoritative Information
1080
    case 204: // No Content
1081
    case 205: // Reset Content
1082
    case 206: // Partial Content
1083
    case 304: // Not modified
1084
      break;
1085
    case 301: // Moved permanently
1086
    case 302: // Moved temporarily
1087
    case 307: // Moved temporarily
1088
      $location = $result->headers['location'];
1089
      $options['timeout'] -= timer_read(__FUNCTION__) / 1000;
1090
      if ($options['timeout'] <= 0) {
1091
        $result->code = HTTP_REQUEST_TIMEOUT;
1092
        $result->error = 'request timed out';
1093
      }
1094
      elseif ($options['max_redirects']) {
1095
        // Redirect to the new location.
1096
        $options['max_redirects']--;
1097
        $result = drupal_http_request($location, $options);
1098
        $result->redirect_code = $code;
1099
      }
1100
      if (!isset($result->redirect_url)) {
1101
        $result->redirect_url = $location;
1102
      }
1103
      break;
1104
    default:
1105
      $result->error = $result->status_message;
1106
  }
1107

    
1108
  return $result;
1109
}
1110

    
1111
/**
1112
 * Splits an HTTP response status line into components.
1113
 *
1114
 * See the @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html status line definition @endlink
1115
 * in RFC 2616.
1116
 *
1117
 * @param string $respone
1118
 *   The response status line, for example 'HTTP/1.1 500 Internal Server Error'.
1119
 *
1120
 * @return array
1121
 *   Keyed array containing the component parts. If the response is malformed,
1122
 *   all possible parts will be extracted. 'reason_phrase' could be empty.
1123
 *   Possible keys:
1124
 *   - 'http_version'
1125
 *   - 'response_code'
1126
 *   - 'reason_phrase'
1127
 */
1128
function _drupal_parse_response_status($response) {
1129
  $response_array = explode(' ', trim($response), 3);
1130
  // Set up empty values.
1131
  $result = array(
1132
    'reason_phrase' => '',
1133
  );
1134
  $result['http_version'] = $response_array[0];
1135
  $result['response_code'] = $response_array[1];
1136
  if (isset($response_array[2])) {
1137
    $result['reason_phrase'] = $response_array[2];
1138
  }
1139
  return $result;
1140
}
1141

    
1142
/**
1143
 * Helper function for determining hosts excluded from needing a proxy.
1144
 *
1145
 * @return
1146
 *   TRUE if a proxy should be used for this host.
1147
 */
1148
function _drupal_http_use_proxy($host) {
1149
  $proxy_exceptions = variable_get('proxy_exceptions', array('localhost', '127.0.0.1'));
1150
  return !in_array(strtolower($host), $proxy_exceptions, TRUE);
1151
}
1152

    
1153
/**
1154
 * @} End of "HTTP handling".
1155
 */
1156

    
1157
/**
1158
 * Strips slashes from a string or array of strings.
1159
 *
1160
 * Callback for array_walk() within fix_gpx_magic().
1161
 *
1162
 * @param $item
1163
 *   An individual string or array of strings from superglobals.
1164
 */
1165
function _fix_gpc_magic(&$item) {
1166
  if (is_array($item)) {
1167
    array_walk($item, '_fix_gpc_magic');
1168
  }
1169
  else {
1170
    $item = stripslashes($item);
1171
  }
1172
}
1173

    
1174
/**
1175
 * Strips slashes from $_FILES items.
1176
 *
1177
 * Callback for array_walk() within fix_gpc_magic().
1178
 *
1179
 * The tmp_name key is skipped keys since PHP generates single backslashes for
1180
 * file paths on Windows systems.
1181
 *
1182
 * @param $item
1183
 *   An item from $_FILES.
1184
 * @param $key
1185
 *   The key for the item within $_FILES.
1186
 *
1187
 * @see http://php.net/manual/features.file-upload.php#42280
1188
 */
1189
function _fix_gpc_magic_files(&$item, $key) {
1190
  if ($key != 'tmp_name') {
1191
    if (is_array($item)) {
1192
      array_walk($item, '_fix_gpc_magic_files');
1193
    }
1194
    else {
1195
      $item = stripslashes($item);
1196
    }
1197
  }
1198
}
1199

    
1200
/**
1201
 * Fixes double-escaping caused by "magic quotes" in some PHP installations.
1202
 *
1203
 * @see _fix_gpc_magic()
1204
 * @see _fix_gpc_magic_files()
1205
 */
1206
function fix_gpc_magic() {
1207
  static $fixed = FALSE;
1208
  if (!$fixed && ini_get('magic_quotes_gpc')) {
1209
    array_walk($_GET, '_fix_gpc_magic');
1210
    array_walk($_POST, '_fix_gpc_magic');
1211
    array_walk($_COOKIE, '_fix_gpc_magic');
1212
    array_walk($_REQUEST, '_fix_gpc_magic');
1213
    array_walk($_FILES, '_fix_gpc_magic_files');
1214
  }
1215
  $fixed = TRUE;
1216
}
1217

    
1218
/**
1219
 * @defgroup validation Input validation
1220
 * @{
1221
 * Functions to validate user input.
1222
 */
1223

    
1224
/**
1225
 * Verifies the syntax of the given e-mail address.
1226
 *
1227
 * This uses the
1228
 * @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
1229
 *
1230
 * @param $mail
1231
 *   A string containing an e-mail address.
1232
 *
1233
 * @return
1234
 *   TRUE if the address is in a valid format.
1235
 */
1236
function valid_email_address($mail) {
1237
  return (bool)filter_var($mail, FILTER_VALIDATE_EMAIL);
1238
}
1239

    
1240
/**
1241
 * Verifies the syntax of the given URL.
1242
 *
1243
 * This function should only be used on actual URLs. It should not be used for
1244
 * Drupal menu paths, which can contain arbitrary characters.
1245
 * Valid values per RFC 3986.
1246
 * @param $url
1247
 *   The URL to verify.
1248
 * @param $absolute
1249
 *   Whether the URL is absolute (beginning with a scheme such as "http:").
1250
 *
1251
 * @return
1252
 *   TRUE if the URL is in a valid format.
1253
 */
1254
function valid_url($url, $absolute = FALSE) {
1255
  if ($absolute) {
1256
    return (bool)preg_match("
1257
      /^                                                      # Start at the beginning of the text
1258
      (?:ftp|https?|feed):\/\/                                # Look for ftp, http, https or feed schemes
1259
      (?:                                                     # Userinfo (optional) which is typically
1260
        (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)*      # a username or a username and password
1261
        (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@          # combination
1262
      )?
1263
      (?:
1264
        (?:[a-z0-9\-\.]|%[0-9a-f]{2})+                        # A domain name or a IPv4 address
1265
        |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\])         # or a well formed IPv6 address
1266
      )
1267
      (?::[0-9]+)?                                            # Server port number (optional)
1268
      (?:[\/|\?]
1269
        (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})   # The path and query (optional)
1270
      *)?
1271
    $/xi", $url);
1272
  }
1273
  else {
1274
    return (bool)preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url);
1275
  }
1276
}
1277

    
1278
/**
1279
 * @} End of "defgroup validation".
1280
 */
1281

    
1282
/**
1283
 * Registers an event for the current visitor to the flood control mechanism.
1284
 *
1285
 * @param $name
1286
 *   The name of an event.
1287
 * @param $window
1288
 *   Optional number of seconds before this event expires. Defaults to 3600 (1
1289
 *   hour). Typically uses the same value as the flood_is_allowed() $window
1290
 *   parameter. Expired events are purged on cron run to prevent the flood table
1291
 *   from growing indefinitely.
1292
 * @param $identifier
1293
 *   Optional identifier (defaults to the current user's IP address).
1294
 */
1295
function flood_register_event($name, $window = 3600, $identifier = NULL) {
1296
  if (!isset($identifier)) {
1297
    $identifier = ip_address();
1298
  }
1299
  db_insert('flood')
1300
    ->fields(array(
1301
      'event' => $name,
1302
      'identifier' => $identifier,
1303
      'timestamp' => REQUEST_TIME,
1304
      'expiration' => REQUEST_TIME + $window,
1305
    ))
1306
    ->execute();
1307
}
1308

    
1309
/**
1310
 * Makes the flood control mechanism forget an event for the current visitor.
1311
 *
1312
 * @param $name
1313
 *   The name of an event.
1314
 * @param $identifier
1315
 *   Optional identifier (defaults to the current user's IP address).
1316
 */
1317
function flood_clear_event($name, $identifier = NULL) {
1318
  if (!isset($identifier)) {
1319
    $identifier = ip_address();
1320
  }
1321
  db_delete('flood')
1322
    ->condition('event', $name)
1323
    ->condition('identifier', $identifier)
1324
    ->execute();
1325
}
1326

    
1327
/**
1328
 * Checks whether a user is allowed to proceed with the specified event.
1329
 *
1330
 * Events can have thresholds saying that each user can only do that event
1331
 * a certain number of times in a time window. This function verifies that the
1332
 * current user has not exceeded this threshold.
1333
 *
1334
 * @param $name
1335
 *   The unique name of the event.
1336
 * @param $threshold
1337
 *   The maximum number of times each user can do this event per time window.
1338
 * @param $window
1339
 *   Number of seconds in the time window for this event (default is 3600
1340
 *   seconds, or 1 hour).
1341
 * @param $identifier
1342
 *   Unique identifier of the current user. Defaults to their IP address.
1343
 *
1344
 * @return
1345
 *   TRUE if the user is allowed to proceed. FALSE if they have exceeded the
1346
 *   threshold and should not be allowed to proceed.
1347
 */
1348
function flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) {
1349
  if (!isset($identifier)) {
1350
    $identifier = ip_address();
1351
  }
1352
  $number = db_query("SELECT COUNT(*) FROM {flood} WHERE event = :event AND identifier = :identifier AND timestamp > :timestamp", array(
1353
    ':event' => $name,
1354
    ':identifier' => $identifier,
1355
    ':timestamp' => REQUEST_TIME - $window))
1356
    ->fetchField();
1357
  return ($number < $threshold);
1358
}
1359

    
1360
/**
1361
 * @defgroup sanitization Sanitization functions
1362
 * @{
1363
 * Functions to sanitize values.
1364
 *
1365
 * See http://drupal.org/writing-secure-code for information
1366
 * on writing secure code.
1367
 */
1368

    
1369
/**
1370
 * Strips dangerous protocols (e.g. 'javascript:') from a URI.
1371
 *
1372
 * This function must be called for all URIs within user-entered input prior
1373
 * to being output to an HTML attribute value. It is often called as part of
1374
 * check_url() or filter_xss(), but those functions return an HTML-encoded
1375
 * string, so this function can be called independently when the output needs to
1376
 * be a plain-text string for passing to t(), l(), drupal_attributes(), or
1377
 * another function that will call check_plain() separately.
1378
 *
1379
 * @param $uri
1380
 *   A plain-text URI that might contain dangerous protocols.
1381
 *
1382
 * @return
1383
 *   A plain-text URI stripped of dangerous protocols. As with all plain-text
1384
 *   strings, this return value must not be output to an HTML page without
1385
 *   check_plain() being called on it. However, it can be passed to functions
1386
 *   expecting plain-text strings.
1387
 *
1388
 * @see check_url()
1389
 */
1390
function drupal_strip_dangerous_protocols($uri) {
1391
  static $allowed_protocols;
1392

    
1393
  if (!isset($allowed_protocols)) {
1394
    $allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal')));
1395
  }
1396

    
1397
  // Iteratively remove any invalid protocol found.
1398
  do {
1399
    $before = $uri;
1400
    $colonpos = strpos($uri, ':');
1401
    if ($colonpos > 0) {
1402
      // We found a colon, possibly a protocol. Verify.
1403
      $protocol = substr($uri, 0, $colonpos);
1404
      // If a colon is preceded by a slash, question mark or hash, it cannot
1405
      // possibly be part of the URL scheme. This must be a relative URL, which
1406
      // inherits the (safe) protocol of the base document.
1407
      if (preg_match('![/?#]!', $protocol)) {
1408
        break;
1409
      }
1410
      // Check if this is a disallowed protocol. Per RFC2616, section 3.2.3
1411
      // (URI Comparison) scheme comparison must be case-insensitive.
1412
      if (!isset($allowed_protocols[strtolower($protocol)])) {
1413
        $uri = substr($uri, $colonpos + 1);
1414
      }
1415
    }
1416
  } while ($before != $uri);
1417

    
1418
  return $uri;
1419
}
1420

    
1421
/**
1422
 * Strips dangerous protocols from a URI and encodes it for output to HTML.
1423
 *
1424
 * @param $uri
1425
 *   A plain-text URI that might contain dangerous protocols.
1426
 *
1427
 * @return
1428
 *   A URI stripped of dangerous protocols and encoded for output to an HTML
1429
 *   attribute value. Because it is already encoded, it should not be set as a
1430
 *   value within a $attributes array passed to drupal_attributes(), because
1431
 *   drupal_attributes() expects those values to be plain-text strings. To pass
1432
 *   a filtered URI to drupal_attributes(), call
1433
 *   drupal_strip_dangerous_protocols() instead.
1434
 *
1435
 * @see drupal_strip_dangerous_protocols()
1436
 */
1437
function check_url($uri) {
1438
  return check_plain(drupal_strip_dangerous_protocols($uri));
1439
}
1440

    
1441
/**
1442
 * Applies a very permissive XSS/HTML filter for admin-only use.
1443
 *
1444
 * Use only for fields where it is impractical to use the
1445
 * whole filter system, but where some (mainly inline) mark-up
1446
 * is desired (so check_plain() is not acceptable).
1447
 *
1448
 * Allows all tags that can be used inside an HTML body, save
1449
 * for scripts and styles.
1450
 */
1451
function filter_xss_admin($string) {
1452
  return filter_xss($string, array('a', 'abbr', 'acronym', 'address', 'article', 'aside', 'b', 'bdi', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'command', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'menu', 'meter', 'nav', 'ol', 'output', 'p', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'small', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time', 'tr', 'tt', 'u', 'ul', 'var', 'wbr'));
1453
}
1454

    
1455
/**
1456
 * Filters HTML to prevent cross-site-scripting (XSS) vulnerabilities.
1457
 *
1458
 * Based on kses by Ulf Harnhammar, see http://sourceforge.net/projects/kses.
1459
 * For examples of various XSS attacks, see: http://ha.ckers.org/xss.html.
1460
 *
1461
 * This code does four things:
1462
 * - Removes characters and constructs that can trick browsers.
1463
 * - Makes sure all HTML entities are well-formed.
1464
 * - Makes sure all HTML tags and attributes are well-formed.
1465
 * - Makes sure no HTML tags contain URLs with a disallowed protocol (e.g.
1466
 *   javascript:).
1467
 *
1468
 * @param $string
1469
 *   The string with raw HTML in it. It will be stripped of everything that can
1470
 *   cause an XSS attack.
1471
 * @param $allowed_tags
1472
 *   An array of allowed tags.
1473
 *
1474
 * @return
1475
 *   An XSS safe version of $string, or an empty string if $string is not
1476
 *   valid UTF-8.
1477
 *
1478
 * @see drupal_validate_utf8()
1479
 */
1480
function filter_xss($string, $allowed_tags = array('a', 'em', 'strong', 'cite', 'blockquote', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd')) {
1481
  // Only operate on valid UTF-8 strings. This is necessary to prevent cross
1482
  // site scripting issues on Internet Explorer 6.
1483
  if (!drupal_validate_utf8($string)) {
1484
    return '';
1485
  }
1486
  // Store the text format.
1487
  _filter_xss_split($allowed_tags, TRUE);
1488
  // Remove NULL characters (ignored by some browsers).
1489
  $string = str_replace(chr(0), '', $string);
1490
  // Remove Netscape 4 JS entities.
1491
  $string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
1492

    
1493
  // Defuse all HTML entities.
1494
  $string = str_replace('&', '&amp;', $string);
1495
  // Change back only well-formed entities in our whitelist:
1496
  // Decimal numeric entities.
1497
  $string = preg_replace('/&amp;#([0-9]+;)/', '&#\1', $string);
1498
  // Hexadecimal numeric entities.
1499
  $string = preg_replace('/&amp;#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\1', $string);
1500
  // Named entities.
1501
  $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string);
1502

    
1503
  return preg_replace_callback('%
1504
    (
1505
    <(?=[^a-zA-Z!/])  # a lone <
1506
    |                 # or
1507
    <!--.*?-->        # a comment
1508
    |                 # or
1509
    <[^>]*(>|$)       # a string that starts with a <, up until the > or the end of the string
1510
    |                 # or
1511
    >                 # just a >
1512
    )%x', '_filter_xss_split', $string);
1513
}
1514

    
1515
/**
1516
 * Processes an HTML tag.
1517
 *
1518
 * @param $m
1519
 *   An array with various meaning depending on the value of $store.
1520
 *   If $store is TRUE then the array contains the allowed tags.
1521
 *   If $store is FALSE then the array has one element, the HTML tag to process.
1522
 * @param $store
1523
 *   Whether to store $m.
1524
 *
1525
 * @return
1526
 *   If the element isn't allowed, an empty string. Otherwise, the cleaned up
1527
 *   version of the HTML element.
1528
 */
1529
function _filter_xss_split($m, $store = FALSE) {
1530
  static $allowed_html;
1531

    
1532
  if ($store) {
1533
    $allowed_html = array_flip($m);
1534
    return;
1535
  }
1536

    
1537
  $string = $m[1];
1538

    
1539
  if (substr($string, 0, 1) != '<') {
1540
    // We matched a lone ">" character.
1541
    return '&gt;';
1542
  }
1543
  elseif (strlen($string) == 1) {
1544
    // We matched a lone "<" character.
1545
    return '&lt;';
1546
  }
1547

    
1548
  if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9\-]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
1549
    // Seriously malformed.
1550
    return '';
1551
  }
1552

    
1553
  $slash = trim($matches[1]);
1554
  $elem = &$matches[2];
1555
  $attrlist = &$matches[3];
1556
  $comment = &$matches[4];
1557

    
1558
  if ($comment) {
1559
    $elem = '!--';
1560
  }
1561

    
1562
  if (!isset($allowed_html[strtolower($elem)])) {
1563
    // Disallowed HTML element.
1564
    return '';
1565
  }
1566

    
1567
  if ($comment) {
1568
    return $comment;
1569
  }
1570

    
1571
  if ($slash != '') {
1572
    return "</$elem>";
1573
  }
1574

    
1575
  // Is there a closing XHTML slash at the end of the attributes?
1576
  $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
1577
  $xhtml_slash = $count ? ' /' : '';
1578

    
1579
  // Clean up attributes.
1580
  $attr2 = implode(' ', _filter_xss_attributes($attrlist));
1581
  $attr2 = preg_replace('/[<>]/', '', $attr2);
1582
  $attr2 = strlen($attr2) ? ' ' . $attr2 : '';
1583

    
1584
  return "<$elem$attr2$xhtml_slash>";
1585
}
1586

    
1587
/**
1588
 * Processes a string of HTML attributes.
1589
 *
1590
 * @return
1591
 *   Cleaned up version of the HTML attributes.
1592
 */
1593
function _filter_xss_attributes($attr) {
1594
  $attrarr = array();
1595
  $mode = 0;
1596
  $attrname = '';
1597

    
1598
  while (strlen($attr) != 0) {
1599
    // Was the last operation successful?
1600
    $working = 0;
1601

    
1602
    switch ($mode) {
1603
      case 0:
1604
        // Attribute name, href for instance.
1605
        if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
1606
          $attrname = strtolower($match[1]);
1607
          $skip = ($attrname == 'style' || substr($attrname, 0, 2) == 'on');
1608
          $working = $mode = 1;
1609
          $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
1610
        }
1611
        break;
1612

    
1613
      case 1:
1614
        // Equals sign or valueless ("selected").
1615
        if (preg_match('/^\s*=\s*/', $attr)) {
1616
          $working = 1; $mode = 2;
1617
          $attr = preg_replace('/^\s*=\s*/', '', $attr);
1618
          break;
1619
        }
1620

    
1621
        if (preg_match('/^\s+/', $attr)) {
1622
          $working = 1; $mode = 0;
1623
          if (!$skip) {
1624
            $attrarr[] = $attrname;
1625
          }
1626
          $attr = preg_replace('/^\s+/', '', $attr);
1627
        }
1628
        break;
1629

    
1630
      case 2:
1631
        // Attribute value, a URL after href= for instance.
1632
        if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
1633
          $thisval = filter_xss_bad_protocol($match[1]);
1634

    
1635
          if (!$skip) {
1636
            $attrarr[] = "$attrname=\"$thisval\"";
1637
          }
1638
          $working = 1;
1639
          $mode = 0;
1640
          $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
1641
          break;
1642
        }
1643

    
1644
        if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match)) {
1645
          $thisval = filter_xss_bad_protocol($match[1]);
1646

    
1647
          if (!$skip) {
1648
            $attrarr[] = "$attrname='$thisval'";
1649
          }
1650
          $working = 1; $mode = 0;
1651
          $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
1652
          break;
1653
        }
1654

    
1655
        if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match)) {
1656
          $thisval = filter_xss_bad_protocol($match[1]);
1657

    
1658
          if (!$skip) {
1659
            $attrarr[] = "$attrname=\"$thisval\"";
1660
          }
1661
          $working = 1; $mode = 0;
1662
          $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
1663
        }
1664
        break;
1665
    }
1666

    
1667
    if ($working == 0) {
1668
      // Not well formed; remove and try again.
1669
      $attr = preg_replace('/
1670
        ^
1671
        (
1672
        "[^"]*("|$)     # - a string that starts with a double quote, up until the next double quote or the end of the string
1673
        |               # or
1674
        \'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
1675
        |               # or
1676
        \S              # - a non-whitespace character
1677
        )*              # any number of the above three
1678
        \s*             # any number of whitespaces
1679
        /x', '', $attr);
1680
      $mode = 0;
1681
    }
1682
  }
1683

    
1684
  // The attribute list ends with a valueless attribute like "selected".
1685
  if ($mode == 1 && !$skip) {
1686
    $attrarr[] = $attrname;
1687
  }
1688
  return $attrarr;
1689
}
1690

    
1691
/**
1692
 * Processes an HTML attribute value and strips dangerous protocols from URLs.
1693
 *
1694
 * @param $string
1695
 *   The string with the attribute value.
1696
 * @param $decode
1697
 *   (deprecated) Whether to decode entities in the $string. Set to FALSE if the
1698
 *   $string is in plain text, TRUE otherwise. Defaults to TRUE. This parameter
1699
 *   is deprecated and will be removed in Drupal 8. To process a plain-text URI,
1700
 *   call drupal_strip_dangerous_protocols() or check_url() instead.
1701
 *
1702
 * @return
1703
 *   Cleaned up and HTML-escaped version of $string.
1704
 */
1705
function filter_xss_bad_protocol($string, $decode = TRUE) {
1706
  // Get the plain text representation of the attribute value (i.e. its meaning).
1707
  // @todo Remove the $decode parameter in Drupal 8, and always assume an HTML
1708
  //   string that needs decoding.
1709
  if ($decode) {
1710
    if (!function_exists('decode_entities')) {
1711
      require_once DRUPAL_ROOT . '/includes/unicode.inc';
1712
    }
1713

    
1714
    $string = decode_entities($string);
1715
  }
1716
  return check_plain(drupal_strip_dangerous_protocols($string));
1717
}
1718

    
1719
/**
1720
 * @} End of "defgroup sanitization".
1721
 */
1722

    
1723
/**
1724
 * @defgroup format Formatting
1725
 * @{
1726
 * Functions to format numbers, strings, dates, etc.
1727
 */
1728

    
1729
/**
1730
 * Formats an RSS channel.
1731
 *
1732
 * Arbitrary elements may be added using the $args associative array.
1733
 */
1734
function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
1735
  global $language_content;
1736
  $langcode = $langcode ? $langcode : $language_content->language;
1737

    
1738
  $output = "<channel>\n";
1739
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1740
  $output .= ' <link>' . check_url($link) . "</link>\n";
1741

    
1742
  // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
1743
  // We strip all HTML tags, but need to prevent double encoding from properly
1744
  // escaped source data (such as &amp becoming &amp;amp;).
1745
  $output .= ' <description>' . check_plain(decode_entities(strip_tags($description))) . "</description>\n";
1746
  $output .= ' <language>' . check_plain($langcode) . "</language>\n";
1747
  $output .= format_xml_elements($args);
1748
  $output .= $items;
1749
  $output .= "</channel>\n";
1750

    
1751
  return $output;
1752
}
1753

    
1754
/**
1755
 * Formats a single RSS item.
1756
 *
1757
 * Arbitrary elements may be added using the $args associative array.
1758
 */
1759
function format_rss_item($title, $link, $description, $args = array()) {
1760
  $output = "<item>\n";
1761
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1762
  $output .= ' <link>' . check_url($link) . "</link>\n";
1763
  $output .= ' <description>' . check_plain($description) . "</description>\n";
1764
  $output .= format_xml_elements($args);
1765
  $output .= "</item>\n";
1766

    
1767
  return $output;
1768
}
1769

    
1770
/**
1771
 * Formats XML elements.
1772
 *
1773
 * @param $array
1774
 *   An array where each item represents an element and is either a:
1775
 *   - (key => value) pair (<key>value</key>)
1776
 *   - Associative array with fields:
1777
 *     - 'key': element name
1778
 *     - 'value': element contents
1779
 *     - 'attributes': associative array of element attributes
1780
 *     - 'encoded': TRUE if 'value' is already encoded
1781
 *
1782
 * In both cases, 'value' can be a simple string, or it can be another array
1783
 * with the same format as $array itself for nesting.
1784
 *
1785
 * If 'encoded' is TRUE it is up to the caller to ensure that 'value' is either
1786
 * entity-encoded or CDATA-escaped. Using this option is not recommended when
1787
 * working with untrusted user input, since failing to escape the data
1788
 * correctly has security implications.
1789
 */
1790
function format_xml_elements($array) {
1791
  $output = '';
1792
  foreach ($array as $key => $value) {
1793
    if (is_numeric($key)) {
1794
      if ($value['key']) {
1795
        $output .= ' <' . $value['key'];
1796
        if (isset($value['attributes']) && is_array($value['attributes'])) {
1797
          $output .= drupal_attributes($value['attributes']);
1798
        }
1799

    
1800
        if (isset($value['value']) && $value['value'] != '') {
1801
          $output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : (!empty($value['encoded']) ? $value['value'] : check_plain($value['value']))) . '</' . $value['key'] . ">\n";
1802
        }
1803
        else {
1804
          $output .= " />\n";
1805
        }
1806
      }
1807
    }
1808
    else {
1809
      $output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</$key>\n";
1810
    }
1811
  }
1812
  return $output;
1813
}
1814

    
1815
/**
1816
 * Formats a string containing a count of items.
1817
 *
1818
 * This function ensures that the string is pluralized correctly. Since t() is
1819
 * called by this function, make sure not to pass already-localized strings to
1820
 * it.
1821
 *
1822
 * For example:
1823
 * @code
1824
 *   $output = format_plural($node->comment_count, '1 comment', '@count comments');
1825
 * @endcode
1826
 *
1827
 * Example with additional replacements:
1828
 * @code
1829
 *   $output = format_plural($update_count,
1830
 *     'Changed the content type of 1 post from %old-type to %new-type.',
1831
 *     'Changed the content type of @count posts from %old-type to %new-type.',
1832
 *     array('%old-type' => $info->old_type, '%new-type' => $info->new_type));
1833
 * @endcode
1834
 *
1835
 * @param $count
1836
 *   The item count to display.
1837
 * @param $singular
1838
 *   The string for the singular case. Make sure it is clear this is singular,
1839
 *   to ease translation (e.g. use "1 new comment" instead of "1 new"). Do not
1840
 *   use @count in the singular string.
1841
 * @param $plural
1842
 *   The string for the plural case. Make sure it is clear this is plural, to
1843
 *   ease translation. Use @count in place of the item count, as in
1844
 *   "@count new comments".
1845
 * @param $args
1846
 *   An associative array of replacements to make after translation. Instances
1847
 *   of any key in this array are replaced with the corresponding value.
1848
 *   Based on the first character of the key, the value is escaped and/or
1849
 *   themed. See format_string(). Note that you do not need to include @count
1850
 *   in this array; this replacement is done automatically for the plural case.
1851
 * @param $options
1852
 *   An associative array of additional options. See t() for allowed keys.
1853
 *
1854
 * @return
1855
 *   A translated string.
1856
 *
1857
 * @see t()
1858
 * @see format_string()
1859
 */
1860
function format_plural($count, $singular, $plural, array $args = array(), array $options = array()) {
1861
  $args['@count'] = $count;
1862
  if ($count == 1) {
1863
    return t($singular, $args, $options);
1864
  }
1865

    
1866
  // Get the plural index through the gettext formula.
1867
  $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, isset($options['langcode']) ? $options['langcode'] : NULL) : -1;
1868
  // If the index cannot be computed, use the plural as a fallback (which
1869
  // allows for most flexiblity with the replaceable @count value).
1870
  if ($index < 0) {
1871
    return t($plural, $args, $options);
1872
  }
1873
  else {
1874
    switch ($index) {
1875
      case "0":
1876
        return t($singular, $args, $options);
1877
      case "1":
1878
        return t($plural, $args, $options);
1879
      default:
1880
        unset($args['@count']);
1881
        $args['@count[' . $index . ']'] = $count;
1882
        return t(strtr($plural, array('@count' => '@count[' . $index . ']')), $args, $options);
1883
    }
1884
  }
1885
}
1886

    
1887
/**
1888
 * Parses a given byte count.
1889
 *
1890
 * @param $size
1891
 *   A size expressed as a number of bytes with optional SI or IEC binary unit
1892
 *   prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).
1893
 *
1894
 * @return
1895
 *   An integer representation of the size in bytes.
1896
 */
1897
function parse_size($size) {
1898
  $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size.
1899
  $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size.
1900
  if ($unit) {
1901
    // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by.
1902
    return round($size * pow(DRUPAL_KILOBYTE, stripos('bkmgtpezy', $unit[0])));
1903
  }
1904
  else {
1905
    return round($size);
1906
  }
1907
}
1908

    
1909
/**
1910
 * Generates a string representation for the given byte count.
1911
 *
1912
 * @param $size
1913
 *   A size in bytes.
1914
 * @param $langcode
1915
 *   Optional language code to translate to a language other than what is used
1916
 *   to display the page.
1917
 *
1918
 * @return
1919
 *   A translated string representation of the size.
1920
 */
1921
function format_size($size, $langcode = NULL) {
1922
  if ($size < DRUPAL_KILOBYTE) {
1923
    return format_plural($size, '1 byte', '@count bytes', array(), array('langcode' => $langcode));
1924
  }
1925
  else {
1926
    $size = $size / DRUPAL_KILOBYTE; // Convert bytes to kilobytes.
1927
    $units = array(
1928
      t('@size KB', array(), array('langcode' => $langcode)),
1929
      t('@size MB', array(), array('langcode' => $langcode)),
1930
      t('@size GB', array(), array('langcode' => $langcode)),
1931
      t('@size TB', array(), array('langcode' => $langcode)),
1932
      t('@size PB', array(), array('langcode' => $langcode)),
1933
      t('@size EB', array(), array('langcode' => $langcode)),
1934
      t('@size ZB', array(), array('langcode' => $langcode)),
1935
      t('@size YB', array(), array('langcode' => $langcode)),
1936
    );
1937
    foreach ($units as $unit) {
1938
      if (round($size, 2) >= DRUPAL_KILOBYTE) {
1939
        $size = $size / DRUPAL_KILOBYTE;
1940
      }
1941
      else {
1942
        break;
1943
      }
1944
    }
1945
    return str_replace('@size', round($size, 2), $unit);
1946
  }
1947
}
1948

    
1949
/**
1950
 * Formats a time interval with the requested granularity.
1951
 *
1952
 * @param $interval
1953
 *   The length of the interval in seconds.
1954
 * @param $granularity
1955
 *   How many different units to display in the string.
1956
 * @param $langcode
1957
 *   Optional language code to translate to a language other than
1958
 *   what is used to display the page.
1959
 *
1960
 * @return
1961
 *   A translated string representation of the interval.
1962
 */
1963
function format_interval($interval, $granularity = 2, $langcode = NULL) {
1964
  $units = array(
1965
    '1 year|@count years' => 31536000,
1966
    '1 month|@count months' => 2592000,
1967
    '1 week|@count weeks' => 604800,
1968
    '1 day|@count days' => 86400,
1969
    '1 hour|@count hours' => 3600,
1970
    '1 min|@count min' => 60,
1971
    '1 sec|@count sec' => 1
1972
  );
1973
  $output = '';
1974
  foreach ($units as $key => $value) {
1975
    $key = explode('|', $key);
1976
    if ($interval >= $value) {
1977
      $output .= ($output ? ' ' : '') . format_plural(floor($interval / $value), $key[0], $key[1], array(), array('langcode' => $langcode));
1978
      $interval %= $value;
1979
      $granularity--;
1980
    }
1981

    
1982
    if ($granularity == 0) {
1983
      break;
1984
    }
1985
  }
1986
  return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
1987
}
1988

    
1989
/**
1990
 * Formats a date, using a date type or a custom date format string.
1991
 *
1992
 * @param $timestamp
1993
 *   A UNIX timestamp to format.
1994
 * @param $type
1995
 *   (optional) The format to use, one of:
1996
 *   - 'short', 'medium', or 'long' (the corresponding built-in date formats).
1997
 *   - The name of a date type defined by a module in hook_date_format_types(),
1998
 *     if it's been assigned a format.
1999
 *   - The machine name of an administrator-defined date format.
2000
 *   - 'custom', to use $format.
2001
 *   Defaults to 'medium'.
2002
 * @param $format
2003
 *   (optional) If $type is 'custom', a PHP date format string suitable for
2004
 *   input to date(). Use a backslash to escape ordinary text, so it does not
2005
 *   get interpreted as date format characters.
2006
 * @param $timezone
2007
 *   (optional) Time zone identifier, as described at
2008
 *   http://php.net/manual/timezones.php Defaults to the time zone used to
2009
 *   display the page.
2010
 * @param $langcode
2011
 *   (optional) Language code to translate to. Defaults to the language used to
2012
 *   display the page.
2013
 *
2014
 * @return
2015
 *   A translated date string in the requested format.
2016
 */
2017
function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
2018
  // Use the advanced drupal_static() pattern, since this is called very often.
2019
  static $drupal_static_fast;
2020
  if (!isset($drupal_static_fast)) {
2021
    $drupal_static_fast['timezones'] = &drupal_static(__FUNCTION__);
2022
  }
2023
  $timezones = &$drupal_static_fast['timezones'];
2024

    
2025
  if (!isset($timezone)) {
2026
    $timezone = date_default_timezone_get();
2027
  }
2028
  // Store DateTimeZone objects in an array rather than repeatedly
2029
  // constructing identical objects over the life of a request.
2030
  if (!isset($timezones[$timezone])) {
2031
    $timezones[$timezone] = timezone_open($timezone);
2032
  }
2033

    
2034
  // Use the default langcode if none is set.
2035
  global $language;
2036
  if (empty($langcode)) {
2037
    $langcode = isset($language->language) ? $language->language : 'en';
2038
  }
2039

    
2040
  switch ($type) {
2041
    case 'short':
2042
      $format = variable_get('date_format_short', 'm/d/Y - H:i');
2043
      break;
2044

    
2045
    case 'long':
2046
      $format = variable_get('date_format_long', 'l, F j, Y - H:i');
2047
      break;
2048

    
2049
    case 'custom':
2050
      // No change to format.
2051
      break;
2052

    
2053
    case 'medium':
2054
    default:
2055
      // Retrieve the format of the custom $type passed.
2056
      if ($type != 'medium') {
2057
        $format = variable_get('date_format_' . $type, '');
2058
      }
2059
      // Fall back to 'medium'.
2060
      if ($format === '') {
2061
        $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
2062
      }
2063
      break;
2064
  }
2065

    
2066
  // Create a DateTime object from the timestamp.
2067
  $date_time = date_create('@' . $timestamp);
2068
  // Set the time zone for the DateTime object.
2069
  date_timezone_set($date_time, $timezones[$timezone]);
2070

    
2071
  // Encode markers that should be translated. 'A' becomes '\xEF\AA\xFF'.
2072
  // xEF and xFF are invalid UTF-8 sequences, and we assume they are not in the
2073
  // input string.
2074
  // Paired backslashes are isolated to prevent errors in read-ahead evaluation.
2075
  // The read-ahead expression ensures that A matches, but not \A.
2076
  $format = preg_replace(array('/\\\\\\\\/', '/(?<!\\\\)([AaeDlMTF])/'), array("\xEF\\\\\\\\\xFF", "\xEF\\\\\$1\$1\xFF"), $format);
2077

    
2078
  // Call date_format().
2079
  $format = date_format($date_time, $format);
2080

    
2081
  // Pass the langcode to _format_date_callback().
2082
  _format_date_callback(NULL, $langcode);
2083

    
2084
  // Translate the marked sequences.
2085
  return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);
2086
}
2087

    
2088
/**
2089
 * Returns an ISO8601 formatted date based on the given date.
2090
 *
2091
 * Callback for use within hook_rdf_mapping() implementations.
2092
 *
2093
 * @param $date
2094
 *   A UNIX timestamp.
2095
 *
2096
 * @return string
2097
 *   An ISO8601 formatted date.
2098
 */
2099
function date_iso8601($date) {
2100
  // The DATE_ISO8601 constant cannot be used here because it does not match
2101
  // date('c') and produces invalid RDF markup.
2102
  return date('c', $date);
2103
}
2104

    
2105
/**
2106
 * Translates a formatted date string.
2107
 *
2108
 * Callback for preg_replace_callback() within format_date().
2109
 */
2110
function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
2111
  // We cache translations to avoid redundant and rather costly calls to t().
2112
  static $cache, $langcode;
2113

    
2114
  if (!isset($matches)) {
2115
    $langcode = $new_langcode;
2116
    return;
2117
  }
2118

    
2119
  $code = $matches[1];
2120
  $string = $matches[2];
2121

    
2122
  if (!isset($cache[$langcode][$code][$string])) {
2123
    $options = array(
2124
      'langcode' => $langcode,
2125
    );
2126

    
2127
    if ($code == 'F') {
2128
      $options['context'] = 'Long month name';
2129
    }
2130

    
2131
    if ($code == '') {
2132
      $cache[$langcode][$code][$string] = $string;
2133
    }
2134
    else {
2135
      $cache[$langcode][$code][$string] = t($string, array(), $options);
2136
    }
2137
  }
2138
  return $cache[$langcode][$code][$string];
2139
}
2140

    
2141
/**
2142
 * Format a username.
2143
 *
2144
 * This is also the label callback implementation of
2145
 * callback_entity_info_label() for user_entity_info().
2146
 *
2147
 * By default, the passed-in object's 'name' property is used if it exists, or
2148
 * else, the site-defined value for the 'anonymous' variable. However, a module
2149
 * may override this by implementing hook_username_alter(&$name, $account).
2150
 *
2151
 * @see hook_username_alter()
2152
 *
2153
 * @param $account
2154
 *   The account object for the user whose name is to be formatted.
2155
 *
2156
 * @return
2157
 *   An unsanitized string with the username to display. The code receiving
2158
 *   this result must ensure that check_plain() is called on it before it is
2159
 *   printed to the page.
2160
 */
2161
function format_username($account) {
2162
  $name = !empty($account->name) ? $account->name : variable_get('anonymous', t('Anonymous'));
2163
  drupal_alter('username', $name, $account);
2164
  return $name;
2165
}
2166

    
2167
/**
2168
 * @} End of "defgroup format".
2169
 */
2170

    
2171
/**
2172
 * Generates an internal or external URL.
2173
 *
2174
 * When creating links in modules, consider whether l() could be a better
2175
 * alternative than url().
2176
 *
2177
 * @param $path
2178
 *   (optional) The internal path or external URL being linked to, such as
2179
 *   "node/34" or "http://example.com/foo". The default value is equivalent to
2180
 *   passing in '<front>'. A few notes:
2181
 *   - If you provide a full URL, it will be considered an external URL.
2182
 *   - If you provide only the path (e.g. "node/34"), it will be
2183
 *     considered an internal link. In this case, it should be a system URL,
2184
 *     and it will be replaced with the alias, if one exists. Additional query
2185
 *     arguments for internal paths must be supplied in $options['query'], not
2186
 *     included in $path.
2187
 *   - If you provide an internal path and $options['alias'] is set to TRUE, the
2188
 *     path is assumed already to be the correct path alias, and the alias is
2189
 *     not looked up.
2190
 *   - The special string '<front>' generates a link to the site's base URL.
2191
 *   - If your external URL contains a query (e.g. http://example.com/foo?a=b),
2192
 *     then you can either URL encode the query keys and values yourself and
2193
 *     include them in $path, or use $options['query'] to let this function
2194
 *     URL encode them.
2195
 * @param $options
2196
 *   (optional) An associative array of additional options, with the following
2197
 *   elements:
2198
 *   - 'query': An array of query key/value-pairs (without any URL-encoding) to
2199
 *     append to the URL.
2200
 *   - 'fragment': A fragment identifier (named anchor) to append to the URL.
2201
 *     Do not include the leading '#' character.
2202
 *   - 'absolute': Defaults to FALSE. Whether to force the output to be an
2203
 *     absolute link (beginning with http:). Useful for links that will be
2204
 *     displayed outside the site, such as in an RSS feed.
2205
 *   - 'alias': Defaults to FALSE. Whether the given path is a URL alias
2206
 *     already.
2207
 *   - 'external': Whether the given path is an external URL.
2208
 *   - 'language': An optional language object. If the path being linked to is
2209
 *     internal to the site, $options['language'] is used to look up the alias
2210
 *     for the URL. If $options['language'] is omitted, the global $language_url
2211
 *     will be used.
2212
 *   - 'https': Whether this URL should point to a secure location. If not
2213
 *     defined, the current scheme is used, so the user stays on HTTP or HTTPS
2214
 *     respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but HTTPS can
2215
 *     only be enforced when the variable 'https' is set to TRUE.
2216
 *   - 'base_url': Only used internally, to modify the base URL when a language
2217
 *     dependent URL requires so.
2218
 *   - 'prefix': Only used internally, to modify the path when a language
2219
 *     dependent URL requires so.
2220
 *   - 'script': The script filename in Drupal's root directory to use when
2221
 *     clean URLs are disabled, such as 'index.php'. Defaults to an empty
2222
 *     string, as most modern web servers automatically find 'index.php'. If
2223
 *     clean URLs are disabled, the value of $path is appended as query
2224
 *     parameter 'q' to $options['script'] in the returned URL. When deploying
2225
 *     Drupal on a web server that cannot be configured to automatically find
2226
 *     index.php, then hook_url_outbound_alter() can be implemented to force
2227
 *     this value to 'index.php'.
2228
 *   - 'entity_type': The entity type of the object that called url(). Only
2229
 *     set if url() is invoked by entity_uri().
2230
 *   - 'entity': The entity object (such as a node) for which the URL is being
2231
 *     generated. Only set if url() is invoked by entity_uri().
2232
 *
2233
 * @return
2234
 *   A string containing a URL to the given path.
2235
 */
2236
function url($path = NULL, array $options = array()) {
2237
  // Merge in defaults.
2238
  $options += array(
2239
    'fragment' => '',
2240
    'query' => array(),
2241
    'absolute' => FALSE,
2242
    'alias' => FALSE,
2243
    'prefix' => ''
2244
  );
2245

    
2246
  // Determine whether this is an external link, but ensure that the current
2247
  // path is always treated as internal by default (to prevent external link
2248
  // injection vulnerabilities).
2249
  if (!isset($options['external'])) {
2250
    $options['external'] = $path === $_GET['q'] ? FALSE : url_is_external($path);
2251
  }
2252

    
2253
  // Preserve the original path before altering or aliasing.
2254
  $original_path = $path;
2255

    
2256
  // Allow other modules to alter the outbound URL and options.
2257
  drupal_alter('url_outbound', $path, $options, $original_path);
2258

    
2259
  if (isset($options['fragment']) && $options['fragment'] !== '') {
2260
    $options['fragment'] = '#' . $options['fragment'];
2261
  }
2262

    
2263
  if ($options['external']) {
2264
    // Split off the fragment.
2265
    if (strpos($path, '#') !== FALSE) {
2266
      list($path, $old_fragment) = explode('#', $path, 2);
2267
      // If $options contains no fragment, take it over from the path.
2268
      if (isset($old_fragment) && !$options['fragment']) {
2269
        $options['fragment'] = '#' . $old_fragment;
2270
      }
2271
    }
2272
    // Append the query.
2273
    if ($options['query']) {
2274
      $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($options['query']);
2275
    }
2276
    if (isset($options['https']) && variable_get('https', FALSE)) {
2277
      if ($options['https'] === TRUE) {
2278
        $path = str_replace('http://', 'https://', $path);
2279
      }
2280
      elseif ($options['https'] === FALSE) {
2281
        $path = str_replace('https://', 'http://', $path);
2282
      }
2283
    }
2284
    // Reassemble.
2285
    return $path . $options['fragment'];
2286
  }
2287

    
2288
  // Strip leading slashes from internal paths to prevent them becoming external
2289
  // URLs without protocol. /example.com should not be turned into
2290
  // //example.com.
2291
  $path = ltrim($path, '/');
2292

    
2293
  global $base_url, $base_secure_url, $base_insecure_url;
2294

    
2295
  // The base_url might be rewritten from the language rewrite in domain mode.
2296
  if (!isset($options['base_url'])) {
2297
    if (isset($options['https']) && variable_get('https', FALSE)) {
2298
      if ($options['https'] === TRUE) {
2299
        $options['base_url'] = $base_secure_url;
2300
        $options['absolute'] = TRUE;
2301
      }
2302
      elseif ($options['https'] === FALSE) {
2303
        $options['base_url'] = $base_insecure_url;
2304
        $options['absolute'] = TRUE;
2305
      }
2306
    }
2307
    else {
2308
      $options['base_url'] = $base_url;
2309
    }
2310
  }
2311

    
2312
  // The special path '<front>' links to the default front page.
2313
  if ($path == '<front>') {
2314
    $path = '';
2315
  }
2316
  elseif (!empty($path) && !$options['alias']) {
2317
    $language = isset($options['language']) && isset($options['language']->language) ? $options['language']->language : '';
2318
    $alias = drupal_get_path_alias($original_path, $language);
2319
    if ($alias != $original_path) {
2320
      // Strip leading slashes from internal path aliases to prevent them
2321
      // becoming external URLs without protocol. /example.com should not be
2322
      // turned into //example.com.
2323
      $path = ltrim($alias, '/');
2324
    }
2325
  }
2326

    
2327
  $base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
2328
  $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
2329

    
2330
  // With Clean URLs.
2331
  if (!empty($GLOBALS['conf']['clean_url'])) {
2332
    $path = drupal_encode_path($prefix . $path);
2333
    if ($options['query']) {
2334
      return $base . $path . '?' . drupal_http_build_query($options['query']) . $options['fragment'];
2335
    }
2336
    else {
2337
      return $base . $path . $options['fragment'];
2338
    }
2339
  }
2340
  // Without Clean URLs.
2341
  else {
2342
    $path = $prefix . $path;
2343
    $query = array();
2344
    if (!empty($path)) {
2345
      $query['q'] = $path;
2346
    }
2347
    if ($options['query']) {
2348
      // We do not use array_merge() here to prevent overriding $path via query
2349
      // parameters.
2350
      $query += $options['query'];
2351
    }
2352
    $query = $query ? ('?' . drupal_http_build_query($query)) : '';
2353
    $script = isset($options['script']) ? $options['script'] : '';
2354
    return $base . $script . $query . $options['fragment'];
2355
  }
2356
}
2357

    
2358
/**
2359
 * Returns TRUE if a path is external to Drupal (e.g. http://example.com).
2360
 *
2361
 * If a path cannot be assessed by Drupal's menu handler, then we must
2362
 * treat it as potentially insecure.
2363
 *
2364
 * @param $path
2365
 *   The internal path or external URL being linked to, such as "node/34" or
2366
 *   "http://example.com/foo".
2367
 *
2368
 * @return
2369
 *   Boolean TRUE or FALSE, where TRUE indicates an external path.
2370
 */
2371
function url_is_external($path) {
2372
  $colonpos = strpos($path, ':');
2373
  // Some browsers treat \ as / so normalize to forward slashes.
2374
  $path = str_replace('\\', '/', $path);
2375
  // If the path starts with 2 slashes then it is always considered an external
2376
  // URL without an explicit protocol part.
2377
  return (strpos($path, '//') === 0)
2378
    // Leading control characters may be ignored or mishandled by browsers, so
2379
    // assume such a path may lead to an external location. The \p{C} character
2380
    // class matches all UTF-8 control, unassigned, and private characters.
2381
    || (preg_match('/^\p{C}/u', $path) !== 0)
2382
    // Avoid calling drupal_strip_dangerous_protocols() if there is any slash
2383
    // (/), hash (#) or question_mark (?) before the colon (:) occurrence - if
2384
    // any - as this would clearly mean it is not a URL.
2385
    || ($colonpos !== FALSE
2386
      && !preg_match('![/?#]!', substr($path, 0, $colonpos))
2387
      && drupal_strip_dangerous_protocols($path) == $path);
2388
}
2389

    
2390
/**
2391
 * Formats an attribute string for an HTTP header.
2392
 *
2393
 * @param $attributes
2394
 *   An associative array of attributes such as 'rel'.
2395
 *
2396
 * @return
2397
 *   A ; separated string ready for insertion in a HTTP header. No escaping is
2398
 *   performed for HTML entities, so this string is not safe to be printed.
2399
 *
2400
 * @see drupal_add_http_header()
2401
 */
2402
function drupal_http_header_attributes(array $attributes = array()) {
2403
  foreach ($attributes as $attribute => &$data) {
2404
    if (is_array($data)) {
2405
      $data = implode(' ', $data);
2406
    }
2407
    $data = $attribute . '="' . $data . '"';
2408
  }
2409
  return $attributes ? ' ' . implode('; ', $attributes) : '';
2410
}
2411

    
2412
/**
2413
 * Converts an associative array to an XML/HTML tag attribute string.
2414
 *
2415
 * Each array key and its value will be formatted into an attribute string.
2416
 * If a value is itself an array, then its elements are concatenated to a single
2417
 * space-delimited string (for example, a class attribute with multiple values).
2418
 *
2419
 * Attribute values are sanitized by running them through check_plain().
2420
 * Attribute names are not automatically sanitized. When using user-supplied
2421
 * attribute names, it is strongly recommended to allow only white-listed names,
2422
 * since certain attributes carry security risks and can be abused.
2423
 *
2424
 * Examples of security aspects when using drupal_attributes:
2425
 * @code
2426
 *   // By running the value in the following statement through check_plain,
2427
 *   // the malicious script is neutralized.
2428
 *   drupal_attributes(array('title' => t('<script>steal_cookie();</script>')));
2429
 *
2430
 *   // The statement below demonstrates dangerous use of drupal_attributes, and
2431
 *   // will return an onmouseout attribute with JavaScript code that, when used
2432
 *   // as attribute in a tag, will cause users to be redirected to another site.
2433
 *   //
2434
 *   // In this case, the 'onmouseout' attribute should not be whitelisted --
2435
 *   // you don't want users to have the ability to add this attribute or others
2436
 *   // that take JavaScript commands.
2437
 *   drupal_attributes(array('onmouseout' => 'window.location="http://malicious.com/";')));
2438
 * @endcode
2439
 *
2440
 * @param $attributes
2441
 *   An associative array of key-value pairs to be converted to attributes.
2442
 *
2443
 * @return
2444
 *   A string ready for insertion in a tag (starts with a space).
2445
 *
2446
 * @ingroup sanitization
2447
 */
2448
function drupal_attributes(array $attributes = array()) {
2449
  foreach ($attributes as $attribute => &$data) {
2450
    $data = implode(' ', (array) $data);
2451
    $data = $attribute . '="' . check_plain($data) . '"';
2452
  }
2453
  return $attributes ? ' ' . implode(' ', $attributes) : '';
2454
}
2455

    
2456
/**
2457
 * Formats an internal or external URL link as an HTML anchor tag.
2458
 *
2459
 * This function correctly handles aliased paths and adds an 'active' class
2460
 * attribute to links that point to the current page (for theming), so all
2461
 * internal links output by modules should be generated by this function if
2462
 * possible.
2463
 *
2464
 * However, for links enclosed in translatable text you should use t() and
2465
 * embed the HTML anchor tag directly in the translated string. For example:
2466
 * @code
2467
 * t('Visit the <a href="@url">settings</a> page', array('@url' => url('admin')));
2468
 * @endcode
2469
 * This keeps the context of the link title ('settings' in the example) for
2470
 * translators.
2471
 *
2472
 * @param string $text
2473
 *   The translated link text for the anchor tag.
2474
 * @param string $path
2475
 *   The internal path or external URL being linked to, such as "node/34" or
2476
 *   "http://example.com/foo". After the url() function is called to construct
2477
 *   the URL from $path and $options, the resulting URL is passed through
2478
 *   check_plain() before it is inserted into the HTML anchor tag, to ensure
2479
 *   well-formed HTML. See url() for more information and notes.
2480
 * @param array $options
2481
 *   An associative array of additional options. Defaults to an empty array. It
2482
 *   may contain the following elements.
2483
 *   - 'attributes': An associative array of HTML attributes to apply to the
2484
 *     anchor tag. If element 'class' is included, it must be an array; 'title'
2485
 *     must be a string; other elements are more flexible, as they just need
2486
 *     to work in a call to drupal_attributes($options['attributes']).
2487
 *   - 'html' (default FALSE): Whether $text is HTML or just plain-text. For
2488
 *     example, to make an image tag into a link, this must be set to TRUE, or
2489
 *     you will see the escaped HTML image tag. $text is not sanitized if
2490
 *     'html' is TRUE. The calling function must ensure that $text is already
2491
 *     safe.
2492
 *   - 'language': An optional language object. If the path being linked to is
2493
 *     internal to the site, $options['language'] is used to determine whether
2494
 *     the link is "active", or pointing to the current page (the language as
2495
 *     well as the path must match). This element is also used by url().
2496
 *   - Additional $options elements used by the url() function.
2497
 *
2498
 * @return string
2499
 *   An HTML string containing a link to the given path.
2500
 *
2501
 * @see url()
2502
 */
2503
function l($text, $path, array $options = array()) {
2504
  global $language_url;
2505
  static $use_theme = NULL;
2506

    
2507
  // Merge in defaults.
2508
  $options += array(
2509
    'attributes' => array(),
2510
    'html' => FALSE,
2511
  );
2512

    
2513
  // Append active class.
2514
  if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
2515
      (empty($options['language']) || $options['language']->language == $language_url->language)) {
2516
    $options['attributes']['class'][] = 'active';
2517
  }
2518

    
2519
  // Remove all HTML and PHP tags from a tooltip. For best performance, we act only
2520
  // if a quick strpos() pre-check gave a suspicion (because strip_tags() is expensive).
2521
  if (isset($options['attributes']['title']) && strpos($options['attributes']['title'], '<') !== FALSE) {
2522
    $options['attributes']['title'] = strip_tags($options['attributes']['title']);
2523
  }
2524

    
2525
  // Determine if rendering of the link is to be done with a theme function
2526
  // or the inline default. Inline is faster, but if the theme system has been
2527
  // loaded and a module or theme implements a preprocess or process function
2528
  // or overrides the theme_link() function, then invoke theme(). Preliminary
2529
  // benchmarks indicate that invoking theme() can slow down the l() function
2530
  // by 20% or more, and that some of the link-heavy Drupal pages spend more
2531
  // than 10% of the total page request time in the l() function.
2532
  if (!isset($use_theme) && function_exists('theme')) {
2533
    // Allow edge cases to prevent theme initialization and force inline link
2534
    // rendering.
2535
    if (variable_get('theme_link', TRUE)) {
2536
      drupal_theme_initialize();
2537
      $registry = theme_get_registry(FALSE);
2538
      // We don't want to duplicate functionality that's in theme(), so any
2539
      // hint of a module or theme doing anything at all special with the 'link'
2540
      // theme hook should simply result in theme() being called. This includes
2541
      // the overriding of theme_link() with an alternate function or template,
2542
      // the presence of preprocess or process functions, or the presence of
2543
      // include files.
2544
      $use_theme = !isset($registry['link']['function']) || ($registry['link']['function'] != 'theme_link');
2545
      $use_theme = $use_theme || !empty($registry['link']['preprocess functions']) || !empty($registry['link']['process functions']) || !empty($registry['link']['includes']);
2546
    }
2547
    else {
2548
      $use_theme = FALSE;
2549
    }
2550
  }
2551
  if ($use_theme) {
2552
    return theme('link', array('text' => $text, 'path' => $path, 'options' => $options));
2553
  }
2554
  // The result of url() is a plain-text URL. Because we are using it here
2555
  // in an HTML argument context, we need to encode it properly.
2556
  return '<a href="' . check_plain(url($path, $options)) . '"' . drupal_attributes($options['attributes']) . '>' . ($options['html'] ? $text : check_plain($text)) . '</a>';
2557
}
2558

    
2559
/**
2560
 * Delivers a page callback result to the browser in the appropriate format.
2561
 *
2562
 * This function is most commonly called by menu_execute_active_handler(), but
2563
 * can also be called by error conditions such as drupal_not_found(),
2564
 * drupal_access_denied(), and drupal_site_offline().
2565
 *
2566
 * When a user requests a page, index.php calls menu_execute_active_handler(),
2567
 * which calls the 'page callback' function registered in hook_menu(). The page
2568
 * callback function can return one of:
2569
 * - NULL: to indicate no content.
2570
 * - An integer menu status constant: to indicate an error condition.
2571
 * - A string of HTML content.
2572
 * - A renderable array of content.
2573
 * Returning a renderable array rather than a string of HTML is preferred,
2574
 * because that provides modules with more flexibility in customizing the final
2575
 * result.
2576
 *
2577
 * When the page callback returns its constructed content to
2578
 * menu_execute_active_handler(), this function gets called. The purpose of
2579
 * this function is to determine the most appropriate 'delivery callback'
2580
 * function to route the content to. The delivery callback function then
2581
 * sends the content to the browser in the needed format. The default delivery
2582
 * callback is drupal_deliver_html_page(), which delivers the content as an HTML
2583
 * page, complete with blocks in addition to the content. This default can be
2584
 * overridden on a per menu router item basis by setting 'delivery callback' in
2585
 * hook_menu() or hook_menu_alter(), and can also be overridden on a per request
2586
 * basis in hook_page_delivery_callback_alter().
2587
 *
2588
 * For example, the same page callback function can be used for an HTML
2589
 * version of the page and an Ajax version of the page. The page callback
2590
 * function just needs to decide what content is to be returned and the
2591
 * delivery callback function will send it as an HTML page or an Ajax
2592
 * response, as appropriate.
2593
 *
2594
 * In order for page callbacks to be reusable in different delivery formats,
2595
 * they should not issue any "print" or "echo" statements, but instead just
2596
 * return content.
2597
 *
2598
 * Also note that this function does not perform access checks. The delivery
2599
 * callback function specified in hook_menu(), hook_menu_alter(), or
2600
 * hook_page_delivery_callback_alter() will be called even if the router item
2601
 * access checks fail. This is intentional (it is needed for JSON and other
2602
 * purposes), but it has security implications. Do not call this function
2603
 * directly unless you understand the security implications, and be careful in
2604
 * writing delivery callbacks, so that they do not violate security. See
2605
 * drupal_deliver_html_page() for an example of a delivery callback that
2606
 * respects security.
2607
 *
2608
 * @param $page_callback_result
2609
 *   The result of a page callback. Can be one of:
2610
 *   - NULL: to indicate no content.
2611
 *   - An integer menu status constant: to indicate an error condition.
2612
 *   - A string of HTML content.
2613
 *   - A renderable array of content.
2614
 * @param $default_delivery_callback
2615
 *   (Optional) If given, it is the name of a delivery function most likely
2616
 *   to be appropriate for the page request as determined by the calling
2617
 *   function (e.g., menu_execute_active_handler()). If not given, it is
2618
 *   determined from the menu router information of the current page.
2619
 *
2620
 * @see menu_execute_active_handler()
2621
 * @see hook_menu()
2622
 * @see hook_menu_alter()
2623
 * @see hook_page_delivery_callback_alter()
2624
 */
2625
function drupal_deliver_page($page_callback_result, $default_delivery_callback = NULL) {
2626
  if (!isset($default_delivery_callback) && ($router_item = menu_get_item())) {
2627
    $default_delivery_callback = $router_item['delivery_callback'];
2628
  }
2629
  $delivery_callback = !empty($default_delivery_callback) ? $default_delivery_callback : 'drupal_deliver_html_page';
2630
  // Give modules a chance to alter the delivery callback used, based on
2631
  // request-time context (e.g., HTTP request headers).
2632
  drupal_alter('page_delivery_callback', $delivery_callback);
2633
  if (function_exists($delivery_callback)) {
2634
    $delivery_callback($page_callback_result);
2635
  }
2636
  else {
2637
    // If a delivery callback is specified, but doesn't exist as a function,
2638
    // something is wrong, but don't print anything, since it's not known
2639
    // what format the response needs to be in.
2640
    watchdog('delivery callback not found', 'callback %callback not found: %q.', array('%callback' => $delivery_callback, '%q' => $_GET['q']), WATCHDOG_ERROR);
2641
  }
2642
}
2643

    
2644
/**
2645
 * Packages and sends the result of a page callback to the browser as HTML.
2646
 *
2647
 * @param $page_callback_result
2648
 *   The result of a page callback. Can be one of:
2649
 *   - NULL: to indicate no content.
2650
 *   - An integer menu status constant: to indicate an error condition.
2651
 *   - A string of HTML content.
2652
 *   - A renderable array of content.
2653
 *
2654
 * @see drupal_deliver_page()
2655
 */
2656
function drupal_deliver_html_page($page_callback_result) {
2657
  // Emit the correct charset HTTP header, but not if the page callback
2658
  // result is NULL, since that likely indicates that it printed something
2659
  // in which case, no further headers may be sent, and not if code running
2660
  // for this page request has already set the content type header.
2661
  if (isset($page_callback_result) && is_null(drupal_get_http_header('Content-Type'))) {
2662
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
2663
  }
2664

    
2665
  // Send appropriate HTTP-Header for browsers and search engines.
2666
  global $language;
2667
  drupal_add_http_header('Content-Language', $language->language);
2668

    
2669
  // By default, do not allow the site to be rendered in an iframe on another
2670
  // domain, but provide a variable to override this. If the code running for
2671
  // this page request already set the X-Frame-Options header earlier, don't
2672
  // overwrite it here.
2673
  $frame_options = variable_get('x_frame_options', 'SAMEORIGIN');
2674
  if ($frame_options && is_null(drupal_get_http_header('X-Frame-Options'))) {
2675
    drupal_add_http_header('X-Frame-Options', $frame_options);
2676
  }
2677

    
2678
  // Menu status constants are integers; page content is a string or array.
2679
  if (is_int($page_callback_result)) {
2680
    // @todo: Break these up into separate functions?
2681
    switch ($page_callback_result) {
2682
      case MENU_NOT_FOUND:
2683
        // Print a 404 page.
2684
        drupal_add_http_header('Status', '404 Not Found');
2685

    
2686
        watchdog('page not found', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
2687

    
2688
        // Check for and return a fast 404 page if configured.
2689
        drupal_fast_404();
2690

    
2691
        // Keep old path for reference, and to allow forms to redirect to it.
2692
        if (!isset($_GET['destination'])) {
2693
          // Make sure that the current path is not interpreted as external URL.
2694
          if (!url_is_external($_GET['q'])) {
2695
            $_GET['destination'] = $_GET['q'];
2696
          }
2697
        }
2698

    
2699
        $path = drupal_get_normal_path(variable_get('site_404', ''));
2700
        if ($path && $path != $_GET['q']) {
2701
          // Custom 404 handler. Set the active item in case there are tabs to
2702
          // display, or other dependencies on the path.
2703
          menu_set_active_item($path);
2704
          $return = menu_execute_active_handler($path, FALSE);
2705
        }
2706

    
2707
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2708
          // Standard 404 handler.
2709
          drupal_set_title(t('Page not found'));
2710
          $return = t('The requested page "@path" could not be found.', array('@path' => request_uri()));
2711
        }
2712

    
2713
        drupal_set_page_content($return);
2714
        $page = element_info('page');
2715
        print drupal_render_page($page);
2716
        break;
2717

    
2718
      case MENU_ACCESS_DENIED:
2719
        // Print a 403 page.
2720
        drupal_add_http_header('Status', '403 Forbidden');
2721
        watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
2722

    
2723
        // Keep old path for reference, and to allow forms to redirect to it.
2724
        if (!isset($_GET['destination'])) {
2725
          // Make sure that the current path is not interpreted as external URL.
2726
          if (!url_is_external($_GET['q'])) {
2727
            $_GET['destination'] = $_GET['q'];
2728
          }
2729
        }
2730

    
2731
        $path = drupal_get_normal_path(variable_get('site_403', ''));
2732
        if ($path && $path != $_GET['q']) {
2733
          // Custom 403 handler. Set the active item in case there are tabs to
2734
          // display or other dependencies on the path.
2735
          menu_set_active_item($path);
2736
          $return = menu_execute_active_handler($path, FALSE);
2737
        }
2738

    
2739
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2740
          // Standard 403 handler.
2741
          drupal_set_title(t('Access denied'));
2742
          $return = t('You are not authorized to access this page.');
2743
        }
2744

    
2745
        print drupal_render_page($return);
2746
        break;
2747

    
2748
      case MENU_SITE_OFFLINE:
2749
        // Print a 503 page.
2750
        drupal_maintenance_theme();
2751
        drupal_add_http_header('Status', '503 Service unavailable');
2752
        drupal_set_title(t('Site under maintenance'));
2753
        print theme('maintenance_page', array('content' => filter_xss_admin(variable_get('maintenance_mode_message',
2754
          t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))))));
2755
        break;
2756
    }
2757
  }
2758
  elseif (isset($page_callback_result)) {
2759
    // Print anything besides a menu constant, assuming it's not NULL or
2760
    // undefined.
2761
    print drupal_render_page($page_callback_result);
2762
  }
2763

    
2764
  // Perform end-of-request tasks.
2765
  drupal_page_footer();
2766
}
2767

    
2768
/**
2769
 * Performs end-of-request tasks.
2770
 *
2771
 * This function sets the page cache if appropriate, and allows modules to
2772
 * react to the closing of the page by calling hook_exit().
2773
 */
2774
function drupal_page_footer() {
2775
  global $user;
2776

    
2777
  module_invoke_all('exit');
2778

    
2779
  // Commit the user session, if needed.
2780
  drupal_session_commit();
2781

    
2782
  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
2783
    drupal_serve_page_from_cache($cache);
2784
  }
2785
  else {
2786
    ob_flush();
2787
  }
2788

    
2789
  _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
2790
  drupal_cache_system_paths();
2791
  module_implements_write_cache();
2792
  drupal_file_scan_write_cache();
2793
  system_run_automated_cron();
2794
}
2795

    
2796
/**
2797
 * Performs end-of-request tasks.
2798
 *
2799
 * In some cases page requests need to end without calling drupal_page_footer().
2800
 * In these cases, call drupal_exit() instead. There should rarely be a reason
2801
 * to call exit instead of drupal_exit();
2802
 *
2803
 * @param $destination
2804
 *   If this function is called from drupal_goto(), then this argument
2805
 *   will be a fully-qualified URL that is the destination of the redirect.
2806
 *   This should be passed along to hook_exit() implementations.
2807
 */
2808
function drupal_exit($destination = NULL) {
2809
  if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL) {
2810
    if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
2811
      module_invoke_all('exit', $destination);
2812
    }
2813
    drupal_session_commit();
2814
  }
2815
  exit;
2816
}
2817

    
2818
/**
2819
 * Forms an associative array from a linear array.
2820
 *
2821
 * This function walks through the provided array and constructs an associative
2822
 * array out of it. The keys of the resulting array will be the values of the
2823
 * input array. The values will be the same as the keys unless a function is
2824
 * specified, in which case the output of the function is used for the values
2825
 * instead.
2826
 *
2827
 * @param $array
2828
 *   A linear array.
2829
 * @param $function
2830
 *   A name of a function to apply to all values before output.
2831
 *
2832
 * @return
2833
 *   An associative array.
2834
 */
2835
function drupal_map_assoc($array, $function = NULL) {
2836
  // array_combine() fails with empty arrays:
2837
  // http://bugs.php.net/bug.php?id=34857.
2838
  $array = !empty($array) ? array_combine($array, $array) : array();
2839
  if (is_callable($function)) {
2840
    $array = array_map($function, $array);
2841
  }
2842
  return $array;
2843
}
2844

    
2845
/**
2846
 * Attempts to set the PHP maximum execution time.
2847
 *
2848
 * This function is a wrapper around the PHP function set_time_limit().
2849
 * When called, set_time_limit() restarts the timeout counter from zero.
2850
 * In other words, if the timeout is the default 30 seconds, and 25 seconds
2851
 * into script execution a call such as set_time_limit(20) is made, the
2852
 * script will run for a total of 45 seconds before timing out.
2853
 *
2854
 * If the current time limit is not unlimited it is possible to decrease the
2855
 * total time limit if the sum of the new time limit and the current time spent
2856
 * running the script is inferior to the original time limit. It is inherent to
2857
 * the way set_time_limit() works, it should rather be called with an
2858
 * appropriate value every time you need to allocate a certain amount of time
2859
 * to execute a task than only once at the beginning of the script.
2860
 *
2861
 * Before calling set_time_limit(), we check if this function is available
2862
 * because it could be disabled by the server administrator. We also hide all
2863
 * the errors that could occur when calling set_time_limit(), because it is
2864
 * not possible to reliably ensure that PHP or a security extension will
2865
 * not issue a warning/error if they prevent the use of this function.
2866
 *
2867
 * @param $time_limit
2868
 *   An integer specifying the new time limit, in seconds. A value of 0
2869
 *   indicates unlimited execution time.
2870
 *
2871
 * @ingroup php_wrappers
2872
 */
2873
function drupal_set_time_limit($time_limit) {
2874
  if (function_exists('set_time_limit')) {
2875
    $current = ini_get('max_execution_time');
2876
    // Do not set time limit if it is currently unlimited.
2877
    if ($current != 0) {
2878
      @set_time_limit($time_limit);
2879
    }
2880
  }
2881
}
2882

    
2883
/**
2884
 * Returns the path to a system item (module, theme, etc.).
2885
 *
2886
 * @param $type
2887
 *   The type of the item (i.e. theme, theme_engine, module, profile).
2888
 * @param $name
2889
 *   The name of the item for which the path is requested.
2890
 *
2891
 * @return
2892
 *   The path to the requested item or an empty string if the item is not found.
2893
 */
2894
function drupal_get_path($type, $name) {
2895
  return dirname(drupal_get_filename($type, $name));
2896
}
2897

    
2898
/**
2899
 * Returns the base URL path (i.e., directory) of the Drupal installation.
2900
 *
2901
 * base_path() adds a "/" to the beginning and end of the returned path if the
2902
 * path is not empty. At the very least, this will return "/".
2903
 *
2904
 * Examples:
2905
 * - http://example.com returns "/" because the path is empty.
2906
 * - http://example.com/drupal/folder returns "/drupal/folder/".
2907
 */
2908
function base_path() {
2909
  return $GLOBALS['base_path'];
2910
}
2911

    
2912
/**
2913
 * Adds a LINK tag with a distinct 'rel' attribute to the page's HEAD.
2914
 *
2915
 * This function can be called as long the HTML header hasn't been sent, which
2916
 * on normal pages is up through the preprocess step of theme('html'). Adding
2917
 * a link will overwrite a prior link with the exact same 'rel' and 'href'
2918
 * attributes.
2919
 *
2920
 * @param $attributes
2921
 *   Associative array of element attributes including 'href' and 'rel'.
2922
 * @param $header
2923
 *   Optional flag to determine if a HTTP 'Link:' header should be sent.
2924
 */
2925
function drupal_add_html_head_link($attributes, $header = FALSE) {
2926
  $element = array(
2927
    '#tag' => 'link',
2928
    '#attributes' => $attributes,
2929
  );
2930
  $href = $attributes['href'];
2931

    
2932
  if ($header) {
2933
    // Also add a HTTP header "Link:".
2934
    $href = '<' . check_plain($attributes['href']) . '>;';
2935
    unset($attributes['href']);
2936
    $element['#attached']['drupal_add_http_header'][] = array('Link',  $href . drupal_http_header_attributes($attributes), TRUE);
2937
  }
2938

    
2939
  drupal_add_html_head($element, 'drupal_add_html_head_link:' . $attributes['rel'] . ':' . $href);
2940
}
2941

    
2942
/**
2943
 * Adds a cascading stylesheet to the stylesheet queue.
2944
 *
2945
 * Calling drupal_static_reset('drupal_add_css') will clear all cascading
2946
 * stylesheets added so far.
2947
 *
2948
 * If CSS aggregation/compression is enabled, all cascading style sheets added
2949
 * with $options['preprocess'] set to TRUE will be merged into one aggregate
2950
 * file and compressed by removing all extraneous white space.
2951
 * Preprocessed inline stylesheets will not be aggregated into this single file;
2952
 * instead, they are just compressed upon output on the page. Externally hosted
2953
 * stylesheets are never aggregated or compressed.
2954
 *
2955
 * The reason for aggregating the files is outlined quite thoroughly here:
2956
 * http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
2957
 * to request overhead, one bigger file just loads faster than two smaller ones
2958
 * half its size."
2959
 *
2960
 * $options['preprocess'] should be only set to TRUE when a file is required for
2961
 * all typical visitors and most pages of a site. It is critical that all
2962
 * preprocessed files are added unconditionally on every page, even if the
2963
 * files do not happen to be needed on a page. This is normally done by calling
2964
 * drupal_add_css() in a hook_init() implementation.
2965
 *
2966
 * Non-preprocessed files should only be added to the page when they are
2967
 * actually needed.
2968
 *
2969
 * @param $data
2970
 *   (optional) The stylesheet data to be added, depending on what is passed
2971
 *   through to the $options['type'] parameter:
2972
 *   - 'file': The path to the CSS file relative to the base_path(), or a
2973
 *     stream wrapper URI. For example: "modules/devel/devel.css" or
2974
 *     "public://generated_css/stylesheet_1.css". Note that Modules should
2975
 *     always prefix the names of their CSS files with the module name; for
2976
 *     example, system-menus.css rather than simply menus.css. Themes can
2977
 *     override module-supplied CSS files based on their filenames, and this
2978
 *     prefixing helps prevent confusing name collisions for theme developers.
2979
 *     See drupal_get_css() where the overrides are performed. Also, if the
2980
 *     direction of the current language is right-to-left (Hebrew, Arabic,
2981
 *     etc.), the function will also look for an RTL CSS file and append it to
2982
 *     the list. The name of this file should have an '-rtl.css' suffix. For
2983
 *     example, a CSS file called 'mymodule-name.css' will have a
2984
 *     'mymodule-name-rtl.css' file added to the list, if exists in the same
2985
 *     directory. This CSS file should contain overrides for properties which
2986
 *     should be reversed or otherwise different in a right-to-left display.
2987
 *   - 'inline': A string of CSS that should be placed in the given scope. Note
2988
 *     that it is better practice to use 'file' stylesheets, rather than
2989
 *     'inline', as the CSS would then be aggregated and cached.
2990
 *   - 'external': The absolute path to an external CSS file that is not hosted
2991
 *     on the local server. These files will not be aggregated if CSS
2992
 *     aggregation is enabled.
2993
 * @param $options
2994
 *   (optional) A string defining the 'type' of CSS that is being added in the
2995
 *   $data parameter ('file', 'inline', or 'external'), or an array which can
2996
 *   have any or all of the following keys:
2997
 *   - 'type': The type of stylesheet being added. Available options are 'file',
2998
 *     'inline' or 'external'. Defaults to 'file'.
2999
 *   - 'basename': Force a basename for the file being added. Modules are
3000
 *     expected to use stylesheets with unique filenames, but integration of
3001
 *     external libraries may make this impossible. The basename of
3002
 *     'modules/node/node.css' is 'node.css'. If the external library "node.js"
3003
 *     ships with a 'node.css', then a different, unique basename would be
3004
 *     'node.js.css'.
3005
 *   - 'group': A number identifying the group in which to add the stylesheet.
3006
 *     Available constants are:
3007
 *     - CSS_SYSTEM: Any system-layer CSS.
3008
 *     - CSS_DEFAULT: (default) Any module-layer CSS.
3009
 *     - CSS_THEME: Any theme-layer CSS.
3010
 *     The group number serves as a weight: the markup for loading a stylesheet
3011
 *     within a lower weight group is output to the page before the markup for
3012
 *     loading a stylesheet within a higher weight group, so CSS within higher
3013
 *     weight groups take precendence over CSS within lower weight groups.
3014
 *   - 'every_page': For optimal front-end performance when aggregation is
3015
 *     enabled, this should be set to TRUE if the stylesheet is present on every
3016
 *     page of the website for users for whom it is present at all. This
3017
 *     defaults to FALSE. It is set to TRUE for stylesheets added via module and
3018
 *     theme .info files. Modules that add stylesheets within hook_init()
3019
 *     implementations, or from other code that ensures that the stylesheet is
3020
 *     added to all website pages, should also set this flag to TRUE. All
3021
 *     stylesheets within the same group that have the 'every_page' flag set to
3022
 *     TRUE and do not have 'preprocess' set to FALSE are aggregated together
3023
 *     into a single aggregate file, and that aggregate file can be reused
3024
 *     across a user's entire site visit, leading to faster navigation between
3025
 *     pages. However, stylesheets that are only needed on pages less frequently
3026
 *     visited, can be added by code that only runs for those particular pages,
3027
 *     and that code should not set the 'every_page' flag. This minimizes the
3028
 *     size of the aggregate file that the user needs to download when first
3029
 *     visiting the website. Stylesheets without the 'every_page' flag are
3030
 *     aggregated into a separate aggregate file. This other aggregate file is
3031
 *     likely to change from page to page, and each new aggregate file needs to
3032
 *     be downloaded when first encountered, so it should be kept relatively
3033
 *     small by ensuring that most commonly needed stylesheets are added to
3034
 *     every page.
3035
 *   - 'weight': The weight of the stylesheet specifies the order in which the
3036
 *     CSS will appear relative to other stylesheets with the same group and
3037
 *     'every_page' flag. The exact ordering of stylesheets is as follows:
3038
 *     - First by group.
3039
 *     - Then by the 'every_page' flag, with TRUE coming before FALSE.
3040
 *     - Then by weight.
3041
 *     - Then by the order in which the CSS was added. For example, all else
3042
 *       being the same, a stylesheet added by a call to drupal_add_css() that
3043
 *       happened later in the page request gets added to the page after one for
3044
 *       which drupal_add_css() happened earlier in the page request.
3045
 *   - 'media': The media type for the stylesheet, e.g., all, print, screen.
3046
 *     Defaults to 'all'.
3047
 *   - 'preprocess': If TRUE and CSS aggregation/compression is enabled, the
3048
 *     styles will be aggregated and compressed. Defaults to TRUE.
3049
 *   - 'browsers': An array containing information specifying which browsers
3050
 *     should load the CSS item. See drupal_pre_render_conditional_comments()
3051
 *     for details.
3052
 *
3053
 * @return
3054
 *   An array of queued cascading stylesheets.
3055
 *
3056
 * @see drupal_get_css()
3057
 */
3058
function drupal_add_css($data = NULL, $options = NULL) {
3059
  $css = &drupal_static(__FUNCTION__, array());
3060
  $count = &drupal_static(__FUNCTION__ . '_count', 0);
3061

    
3062
  // If the $css variable has been reset with drupal_static_reset(), there is
3063
  // no longer any CSS being tracked, so set the counter back to 0 also.
3064
  if (count($css) === 0) {
3065
    $count = 0;
3066
  }
3067

    
3068
  // Construct the options, taking the defaults into consideration.
3069
  if (isset($options)) {
3070
    if (!is_array($options)) {
3071
      $options = array('type' => $options);
3072
    }
3073
  }
3074
  else {
3075
    $options = array();
3076
  }
3077

    
3078
  // Create an array of CSS files for each media type first, since each type needs to be served
3079
  // to the browser differently.
3080
  if (isset($data)) {
3081
    $options += array(
3082
      'type' => 'file',
3083
      'group' => CSS_DEFAULT,
3084
      'weight' => 0,
3085
      'every_page' => FALSE,
3086
      'media' => 'all',
3087
      'preprocess' => TRUE,
3088
      'data' => $data,
3089
      'browsers' => array(),
3090
    );
3091
    $options['browsers'] += array(
3092
      'IE' => TRUE,
3093
      '!IE' => TRUE,
3094
    );
3095

    
3096
    // Files with a query string cannot be preprocessed.
3097
    if ($options['type'] === 'file' && $options['preprocess'] && strpos($options['data'], '?') !== FALSE) {
3098
      $options['preprocess'] = FALSE;
3099
    }
3100

    
3101
    // Always add a tiny value to the weight, to conserve the insertion order.
3102
    $options['weight'] += $count / 1000;
3103
    $count++;
3104

    
3105
    // Add the data to the CSS array depending on the type.
3106
    switch ($options['type']) {
3107
      case 'inline':
3108
        // For inline stylesheets, we don't want to use the $data as the array
3109
        // key as $data could be a very long string of CSS.
3110
        $css[] = $options;
3111
        break;
3112
      default:
3113
        // Local and external files must keep their name as the associative key
3114
        // so the same CSS file is not be added twice.
3115
        $css[$data] = $options;
3116
    }
3117
  }
3118

    
3119
  return $css;
3120
}
3121

    
3122
/**
3123
 * Returns a themed representation of all stylesheets to attach to the page.
3124
 *
3125
 * It loads the CSS in order, with 'module' first, then 'theme' afterwards.
3126
 * This ensures proper cascading of styles so themes can easily override
3127
 * module styles through CSS selectors.
3128
 *
3129
 * Themes may replace module-defined CSS files by adding a stylesheet with the
3130
 * same filename. For example, themes/bartik/system-menus.css would replace
3131
 * modules/system/system-menus.css. This allows themes to override complete
3132
 * CSS files, rather than specific selectors, when necessary.
3133
 *
3134
 * If the original CSS file is being overridden by a theme, the theme is
3135
 * responsible for supplying an accompanying RTL CSS file to replace the
3136
 * module's.
3137
 *
3138
 * @param $css
3139
 *   (optional) An array of CSS files. If no array is provided, the default
3140
 *   stylesheets array is used instead.
3141
 * @param $skip_alter
3142
 *   (optional) If set to TRUE, this function skips calling drupal_alter() on
3143
 *   $css, useful when the calling function passes a $css array that has already
3144
 *   been altered.
3145
 *
3146
 * @return
3147
 *   A string of XHTML CSS tags.
3148
 *
3149
 * @see drupal_add_css()
3150
 */
3151
function drupal_get_css($css = NULL, $skip_alter = FALSE) {
3152
  if (!isset($css)) {
3153
    $css = drupal_add_css();
3154
  }
3155

    
3156
  // Allow modules and themes to alter the CSS items.
3157
  if (!$skip_alter) {
3158
    drupal_alter('css', $css);
3159
  }
3160

    
3161
  // Sort CSS items, so that they appear in the correct order.
3162
  uasort($css, 'drupal_sort_css_js');
3163

    
3164
  // Provide the page with information about the individual CSS files used,
3165
  // information not otherwise available when CSS aggregation is enabled. The
3166
  // setting is attached later in this function, but is set here, so that CSS
3167
  // files removed below are still considered "used" and prevented from being
3168
  // added in a later AJAX request.
3169
  // Skip if no files were added to the page or jQuery.extend() will overwrite
3170
  // the Drupal.settings.ajaxPageState.css object with an empty array.
3171
  if (!empty($css)) {
3172
    // Cast the array to an object to be on the safe side even if not empty.
3173
    $setting['ajaxPageState']['css'] = (object) array_fill_keys(array_keys($css), 1);
3174
  }
3175

    
3176
  // Remove the overridden CSS files. Later CSS files override former ones.
3177
  $previous_item = array();
3178
  foreach ($css as $key => $item) {
3179
    if ($item['type'] == 'file') {
3180
      // If defined, force a unique basename for this file.
3181
      $basename = isset($item['basename']) ? $item['basename'] : drupal_basename($item['data']);
3182
      if (isset($previous_item[$basename])) {
3183
        // Remove the previous item that shared the same base name.
3184
        unset($css[$previous_item[$basename]]);
3185
      }
3186
      $previous_item[$basename] = $key;
3187
    }
3188
  }
3189

    
3190
  // Render the HTML needed to load the CSS.
3191
  $styles = array(
3192
    '#type' => 'styles',
3193
    '#items' => $css,
3194
  );
3195

    
3196
  if (!empty($setting)) {
3197
    $styles['#attached']['js'][] = array('type' => 'setting', 'data' => $setting);
3198
  }
3199

    
3200
  return drupal_render($styles);
3201
}
3202

    
3203
/**
3204
 * Sorts CSS and JavaScript resources.
3205
 *
3206
 * Callback for uasort() within:
3207
 * - drupal_get_css()
3208
 * - drupal_get_js()
3209
 *
3210
 * This sort order helps optimize front-end performance while providing modules
3211
 * and themes with the necessary control for ordering the CSS and JavaScript
3212
 * appearing on a page.
3213
 *
3214
 * @param $a
3215
 *   First item for comparison. The compared items should be associative arrays
3216
 *   of member items from drupal_add_css() or drupal_add_js().
3217
 * @param $b
3218
 *   Second item for comparison.
3219
 *
3220
 * @see drupal_add_css()
3221
 * @see drupal_add_js()
3222
 */
3223
function drupal_sort_css_js($a, $b) {
3224
  // First order by group, so that, for example, all items in the CSS_SYSTEM
3225
  // group appear before items in the CSS_DEFAULT group, which appear before
3226
  // all items in the CSS_THEME group. Modules may create additional groups by
3227
  // defining their own constants.
3228
  if ($a['group'] < $b['group']) {
3229
    return -1;
3230
  }
3231
  elseif ($a['group'] > $b['group']) {
3232
    return 1;
3233
  }
3234
  // Within a group, order all infrequently needed, page-specific files after
3235
  // common files needed throughout the website. Separating this way allows for
3236
  // the aggregate file generated for all of the common files to be reused
3237
  // across a site visit without being cut by a page using a less common file.
3238
  elseif ($a['every_page'] && !$b['every_page']) {
3239
    return -1;
3240
  }
3241
  elseif (!$a['every_page'] && $b['every_page']) {
3242
    return 1;
3243
  }
3244
  // Finally, order by weight.
3245
  elseif ($a['weight'] < $b['weight']) {
3246
    return -1;
3247
  }
3248
  elseif ($a['weight'] > $b['weight']) {
3249
    return 1;
3250
  }
3251
  else {
3252
    return 0;
3253
  }
3254
}
3255

    
3256
/**
3257
 * Default callback to group CSS items.
3258
 *
3259
 * This function arranges the CSS items that are in the #items property of the
3260
 * styles element into groups. Arranging the CSS items into groups serves two
3261
 * purposes. When aggregation is enabled, files within a group are aggregated
3262
 * into a single file, significantly improving page loading performance by
3263
 * minimizing network traffic overhead. When aggregation is disabled, grouping
3264
 * allows multiple files to be loaded from a single STYLE tag, enabling sites
3265
 * with many modules enabled or a complex theme being used to stay within IE's
3266
 * 31 CSS inclusion tag limit: http://drupal.org/node/228818.
3267
 *
3268
 * This function puts multiple items into the same group if they are groupable
3269
 * and if they are for the same 'media' and 'browsers'. Items of the 'file' type
3270
 * are groupable if their 'preprocess' flag is TRUE, items of the 'inline' type
3271
 * are always groupable, and items of the 'external' type are never groupable.
3272
 * This function also ensures that the process of grouping items does not change
3273
 * their relative order. This requirement may result in multiple groups for the
3274
 * same type, media, and browsers, if needed to accommodate other items in
3275
 * between.
3276
 *
3277
 * @param $css
3278
 *   An array of CSS items, as returned by drupal_add_css(), but after
3279
 *   alteration performed by drupal_get_css().
3280
 *
3281
 * @return
3282
 *   An array of CSS groups. Each group contains the same keys (e.g., 'media',
3283
 *   'data', etc.) as a CSS item from the $css parameter, with the value of
3284
 *   each key applying to the group as a whole. Each group also contains an
3285
 *   'items' key, which is the subset of items from $css that are in the group.
3286
 *
3287
 * @see drupal_pre_render_styles()
3288
 * @see system_element_info()
3289
 */
3290
function drupal_group_css($css) {
3291
  $groups = array();
3292
  // If a group can contain multiple items, we track the information that must
3293
  // be the same for each item in the group, so that when we iterate the next
3294
  // item, we can determine if it can be put into the current group, or if a
3295
  // new group needs to be made for it.
3296
  $current_group_keys = NULL;
3297
  // When creating a new group, we pre-increment $i, so by initializing it to
3298
  // -1, the first group will have index 0.
3299
  $i = -1;
3300
  foreach ($css as $item) {
3301
    // The browsers for which the CSS item needs to be loaded is part of the
3302
    // information that determines when a new group is needed, but the order of
3303
    // keys in the array doesn't matter, and we don't want a new group if all
3304
    // that's different is that order.
3305
    ksort($item['browsers']);
3306

    
3307
    // If the item can be grouped with other items, set $group_keys to an array
3308
    // of information that must be the same for all items in its group. If the
3309
    // item can't be grouped with other items, set $group_keys to FALSE. We
3310
    // put items into a group that can be aggregated together: whether they will
3311
    // be aggregated is up to the _drupal_css_aggregate() function or an
3312
    // override of that function specified in hook_css_alter(), but regardless
3313
    // of the details of that function, a group represents items that can be
3314
    // aggregated. Since a group may be rendered with a single HTML tag, all
3315
    // items in the group must share the same information that would need to be
3316
    // part of that HTML tag.
3317
    switch ($item['type']) {
3318
      case 'file':
3319
        // Group file items if their 'preprocess' flag is TRUE.
3320
        // Help ensure maximum reuse of aggregate files by only grouping
3321
        // together items that share the same 'group' value and 'every_page'
3322
        // flag. See drupal_add_css() for details about that.
3323
        $group_keys = $item['preprocess'] ? array($item['type'], $item['group'], $item['every_page'], $item['media'], $item['browsers']) : FALSE;
3324
        break;
3325
      case 'inline':
3326
        // Always group inline items.
3327
        $group_keys = array($item['type'], $item['media'], $item['browsers']);
3328
        break;
3329
      case 'external':
3330
        // Do not group external items.
3331
        $group_keys = FALSE;
3332
        break;
3333
    }
3334

    
3335
    // If the group keys don't match the most recent group we're working with,
3336
    // then a new group must be made.
3337
    if ($group_keys !== $current_group_keys) {
3338
      $i++;
3339
      // Initialize the new group with the same properties as the first item
3340
      // being placed into it. The item's 'data' and 'weight' properties are
3341
      // unique to the item and should not be carried over to the group.
3342
      $groups[$i] = $item;
3343
      unset($groups[$i]['data'], $groups[$i]['weight']);
3344
      $groups[$i]['items'] = array();
3345
      $current_group_keys = $group_keys ? $group_keys : NULL;
3346
    }
3347

    
3348
    // Add the item to the current group.
3349
    $groups[$i]['items'][] = $item;
3350
  }
3351
  return $groups;
3352
}
3353

    
3354
/**
3355
 * Default callback to aggregate CSS files and inline content.
3356
 *
3357
 * Having the browser load fewer CSS files results in much faster page loads
3358
 * than when it loads many small files. This function aggregates files within
3359
 * the same group into a single file unless the site-wide setting to do so is
3360
 * disabled (commonly the case during site development). To optimize download,
3361
 * it also compresses the aggregate files by removing comments, whitespace, and
3362
 * other unnecessary content. Additionally, this functions aggregates inline
3363
 * content together, regardless of the site-wide aggregation setting.
3364
 *
3365
 * @param $css_groups
3366
 *   An array of CSS groups as returned by drupal_group_css(). This function
3367
 *   modifies the group's 'data' property for each group that is aggregated.
3368
 *
3369
 * @see drupal_group_css()
3370
 * @see drupal_pre_render_styles()
3371
 * @see system_element_info()
3372
 */
3373
function drupal_aggregate_css(&$css_groups) {
3374
  $preprocess_css = (variable_get('preprocess_css', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
3375

    
3376
  // For each group that needs aggregation, aggregate its items.
3377
  foreach ($css_groups as $key => $group) {
3378
    switch ($group['type']) {
3379
      // If a file group can be aggregated into a single file, do so, and set
3380
      // the group's data property to the file path of the aggregate file.
3381
      case 'file':
3382
        if ($group['preprocess'] && $preprocess_css) {
3383
          $css_groups[$key]['data'] = drupal_build_css_cache($group['items']);
3384
        }
3385
        break;
3386
      // Aggregate all inline CSS content into the group's data property.
3387
      case 'inline':
3388
        $css_groups[$key]['data'] = '';
3389
        foreach ($group['items'] as $item) {
3390
          $css_groups[$key]['data'] .= drupal_load_stylesheet_content($item['data'], $item['preprocess']);
3391
        }
3392
        break;
3393
    }
3394
  }
3395
}
3396

    
3397
/**
3398
 * #pre_render callback to add the elements needed for CSS tags to be rendered.
3399
 *
3400
 * For production websites, LINK tags are preferable to STYLE tags with @import
3401
 * statements, because:
3402
 * - They are the standard tag intended for linking to a resource.
3403
 * - On Firefox 2 and perhaps other browsers, CSS files included with @import
3404
 *   statements don't get saved when saving the complete web page for offline
3405
 *   use: http://drupal.org/node/145218.
3406
 * - On IE, if only LINK tags and no @import statements are used, all the CSS
3407
 *   files are downloaded in parallel, resulting in faster page load, but if
3408
 *   @import statements are used and span across multiple STYLE tags, all the
3409
 *   ones from one STYLE tag must be downloaded before downloading begins for
3410
 *   the next STYLE tag. Furthermore, IE7 does not support media declaration on
3411
 *   the @import statement, so multiple STYLE tags must be used when different
3412
 *   files are for different media types. Non-IE browsers always download in
3413
 *   parallel, so this is an IE-specific performance quirk:
3414
 *   http://www.stevesouders.com/blog/2009/04/09/dont-use-import/.
3415
 *
3416
 * However, IE has an annoying limit of 31 total CSS inclusion tags
3417
 * (http://drupal.org/node/228818) and LINK tags are limited to one file per
3418
 * tag, whereas STYLE tags can contain multiple @import statements allowing
3419
 * multiple files to be loaded per tag. When CSS aggregation is disabled, a
3420
 * Drupal site can easily have more than 31 CSS files that need to be loaded, so
3421
 * using LINK tags exclusively would result in a site that would display
3422
 * incorrectly in IE. Depending on different needs, different strategies can be
3423
 * employed to decide when to use LINK tags and when to use STYLE tags.
3424
 *
3425
 * The strategy employed by this function is to use LINK tags for all aggregate
3426
 * files and for all files that cannot be aggregated (e.g., if 'preprocess' is
3427
 * set to FALSE or the type is 'external'), and to use STYLE tags for groups
3428
 * of files that could be aggregated together but aren't (e.g., if the site-wide
3429
 * aggregation setting is disabled). This results in all LINK tags when
3430
 * aggregation is enabled, a guarantee that as many or only slightly more tags
3431
 * are used with aggregation disabled than enabled (so that if the limit were to
3432
 * be crossed with aggregation enabled, the site developer would also notice the
3433
 * problem while aggregation is disabled), and an easy way for a developer to
3434
 * view HTML source while aggregation is disabled and know what files will be
3435
 * aggregated together when aggregation becomes enabled.
3436
 *
3437
 * This function evaluates the aggregation enabled/disabled condition on a group
3438
 * by group basis by testing whether an aggregate file has been made for the
3439
 * group rather than by testing the site-wide aggregation setting. This allows
3440
 * this function to work correctly even if modules have implemented custom
3441
 * logic for grouping and aggregating files.
3442
 *
3443
 * @param $element
3444
 *   A render array containing:
3445
 *   - '#items': The CSS items as returned by drupal_add_css() and altered by
3446
 *     drupal_get_css().
3447
 *   - '#group_callback': A function to call to group #items to enable the use
3448
 *     of fewer tags by aggregating files and/or using multiple @import
3449
 *     statements within a single tag.
3450
 *   - '#aggregate_callback': A function to call to aggregate the items within
3451
 *     the groups arranged by the #group_callback function.
3452
 *
3453
 * @return
3454
 *   A render array that will render to a string of XHTML CSS tags.
3455
 *
3456
 * @see drupal_get_css()
3457
 */
3458
function drupal_pre_render_styles($elements) {
3459
  // Group and aggregate the items.
3460
  if (isset($elements['#group_callback'])) {
3461
    $elements['#groups'] = $elements['#group_callback']($elements['#items']);
3462
  }
3463
  if (isset($elements['#aggregate_callback'])) {
3464
    $elements['#aggregate_callback']($elements['#groups']);
3465
  }
3466

    
3467
  // A dummy query-string is added to filenames, to gain control over
3468
  // browser-caching. The string changes on every update or full cache
3469
  // flush, forcing browsers to load a new copy of the files, as the
3470
  // URL changed.
3471
  $query_string = variable_get('css_js_query_string', '0');
3472

    
3473
  // For inline CSS to validate as XHTML, all CSS containing XHTML needs to be
3474
  // wrapped in CDATA. To make that backwards compatible with HTML 4, we need to
3475
  // comment out the CDATA-tag.
3476
  $embed_prefix = "\n<!--/*--><![CDATA[/*><!--*/\n";
3477
  $embed_suffix = "\n/*]]>*/-->\n";
3478

    
3479
  // Defaults for LINK and STYLE elements.
3480
  $link_element_defaults = array(
3481
    '#type' => 'html_tag',
3482
    '#tag' => 'link',
3483
    '#attributes' => array(
3484
      'type' => 'text/css',
3485
      'rel' => 'stylesheet',
3486
    ),
3487
  );
3488
  $style_element_defaults = array(
3489
    '#type' => 'html_tag',
3490
    '#tag' => 'style',
3491
    '#attributes' => array(
3492
      'type' => 'text/css',
3493
    ),
3494
  );
3495

    
3496
  // Loop through each group.
3497
  foreach ($elements['#groups'] as $group) {
3498
    switch ($group['type']) {
3499
      // For file items, there are three possibilites.
3500
      // - The group has been aggregated: in this case, output a LINK tag for
3501
      //   the aggregate file.
3502
      // - The group can be aggregated but has not been (most likely because
3503
      //   the site administrator disabled the site-wide setting): in this case,
3504
      //   output as few STYLE tags for the group as possible, using @import
3505
      //   statement for each file in the group. This enables us to stay within
3506
      //   IE's limit of 31 total CSS inclusion tags.
3507
      // - The group contains items not eligible for aggregation (their
3508
      //   'preprocess' flag has been set to FALSE): in this case, output a LINK
3509
      //   tag for each file.
3510
      case 'file':
3511
        // The group has been aggregated into a single file: output a LINK tag
3512
        // for the aggregate file.
3513
        if (isset($group['data'])) {
3514
          $element = $link_element_defaults;
3515
          $element['#attributes']['href'] = file_create_url($group['data']);
3516
          $element['#attributes']['media'] = $group['media'];
3517
          $element['#browsers'] = $group['browsers'];
3518
          $elements[] = $element;
3519
        }
3520
        // The group can be aggregated, but hasn't been: combine multiple items
3521
        // into as few STYLE tags as possible.
3522
        elseif ($group['preprocess']) {
3523
          $import = array();
3524
          foreach ($group['items'] as $item) {
3525
            // A theme's .info file may have an entry for a file that doesn't
3526
            // exist as a way of overriding a module or base theme CSS file from
3527
            // being added to the page. Normally, file_exists() calls that need
3528
            // to run for every page request should be minimized, but this one
3529
            // is okay, because it only runs when CSS aggregation is disabled.
3530
            // On a server under heavy enough load that file_exists() calls need
3531
            // to be minimized, CSS aggregation should be enabled, in which case
3532
            // this code is not run. When aggregation is enabled,
3533
            // drupal_load_stylesheet() checks file_exists(), but only when
3534
            // building the aggregate file, which is then reused for many page
3535
            // requests.
3536
            if (file_exists($item['data'])) {
3537
              // The dummy query string needs to be added to the URL to control
3538
              // browser-caching. IE7 does not support a media type on the
3539
              // @import statement, so we instead specify the media for the
3540
              // group on the STYLE tag.
3541
              $import[] = '@import url("' . check_plain(file_create_url($item['data']) . '?' . $query_string) . '");';
3542
            }
3543
          }
3544
          // In addition to IE's limit of 31 total CSS inclusion tags, it also
3545
          // has a limit of 31 @import statements per STYLE tag.
3546
          while (!empty($import)) {
3547
            $import_batch = array_slice($import, 0, 31);
3548
            $import = array_slice($import, 31);
3549
            $element = $style_element_defaults;
3550
            // This simplifies the JavaScript regex, allowing each line
3551
            // (separated by \n) to be treated as a completely different string.
3552
            // This means that we can use ^ and $ on one line at a time, and not
3553
            // worry about style tags since they'll never match the regex.
3554
            $element['#value'] = "\n" . implode("\n", $import_batch) . "\n";
3555
            $element['#attributes']['media'] = $group['media'];
3556
            $element['#browsers'] = $group['browsers'];
3557
            $elements[] = $element;
3558
          }
3559
        }
3560
        // The group contains items ineligible for aggregation: output a LINK
3561
        // tag for each file.
3562
        else {
3563
          foreach ($group['items'] as $item) {
3564
            $element = $link_element_defaults;
3565
            // We do not check file_exists() here, because this code runs for
3566
            // files whose 'preprocess' is set to FALSE, and therefore, even
3567
            // when aggregation is enabled, and we want to avoid needlessly
3568
            // taxing a server that may be under heavy load. The file_exists()
3569
            // performed above for files whose 'preprocess' is TRUE is done for
3570
            // the benefit of theme .info files, but code that deals with files
3571
            // whose 'preprocess' is FALSE is responsible for ensuring the file
3572
            // exists.
3573
            // The dummy query string needs to be added to the URL to control
3574
            // browser-caching.
3575
            $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
3576
            $element['#attributes']['href'] = file_create_url($item['data']) . $query_string_separator . $query_string;
3577
            $element['#attributes']['media'] = $item['media'];
3578
            $element['#browsers'] = $group['browsers'];
3579
            $elements[] = $element;
3580
          }
3581
        }
3582
        break;
3583
      // For inline content, the 'data' property contains the CSS content. If
3584
      // the group's 'data' property is set, then output it in a single STYLE
3585
      // tag. Otherwise, output a separate STYLE tag for each item.
3586
      case 'inline':
3587
        if (isset($group['data'])) {
3588
          $element = $style_element_defaults;
3589
          $element['#value'] = $group['data'];
3590
          $element['#value_prefix'] = $embed_prefix;
3591
          $element['#value_suffix'] = $embed_suffix;
3592
          $element['#attributes']['media'] = $group['media'];
3593
          $element['#browsers'] = $group['browsers'];
3594
          $elements[] = $element;
3595
        }
3596
        else {
3597
          foreach ($group['items'] as $item) {
3598
            $element = $style_element_defaults;
3599
            $element['#value'] = $item['data'];
3600
            $element['#value_prefix'] = $embed_prefix;
3601
            $element['#value_suffix'] = $embed_suffix;
3602
            $element['#attributes']['media'] = $item['media'];
3603
            $element['#browsers'] = $group['browsers'];
3604
            $elements[] = $element;
3605
          }
3606
        }
3607
        break;
3608
      // Output a LINK tag for each external item. The item's 'data' property
3609
      // contains the full URL.
3610
      case 'external':
3611
        foreach ($group['items'] as $item) {
3612
          $element = $link_element_defaults;
3613
          $element['#attributes']['href'] = $item['data'];
3614
          $element['#attributes']['media'] = $item['media'];
3615
          $element['#browsers'] = $group['browsers'];
3616
          $elements[] = $element;
3617
        }
3618
        break;
3619
    }
3620
  }
3621

    
3622
  return $elements;
3623
}
3624

    
3625
/**
3626
 * Aggregates and optimizes CSS files into a cache file in the files directory.
3627
 *
3628
 * The file name for the CSS cache file is generated from the hash of the
3629
 * aggregated contents of the files in $css. This forces proxies and browsers
3630
 * to download new CSS when the CSS changes.
3631
 *
3632
 * The cache file name is retrieved on a page load via a lookup variable that
3633
 * contains an associative array. The array key is the hash of the file names
3634
 * in $css while the value is the cache file name. The cache file is generated
3635
 * in two cases. First, if there is no file name value for the key, which will
3636
 * happen if a new file name has been added to $css or after the lookup
3637
 * variable is emptied to force a rebuild of the cache. Second, the cache file
3638
 * is generated if it is missing on disk. Old cache files are not deleted
3639
 * immediately when the lookup variable is emptied, but are deleted after a set
3640
 * period by drupal_delete_file_if_stale(). This ensures that files referenced
3641
 * by a cached page will still be available.
3642
 *
3643
 * @param $css
3644
 *   An array of CSS files to aggregate and compress into one file.
3645
 *
3646
 * @return
3647
 *   The URI of the CSS cache file, or FALSE if the file could not be saved.
3648
 */
3649
function drupal_build_css_cache($css) {
3650
  $data = '';
3651
  $uri = '';
3652
  $map = variable_get('drupal_css_cache_files', array());
3653
  // Create a new array so that only the file names are used to create the hash.
3654
  // This prevents new aggregates from being created unnecessarily.
3655
  $css_data = array();
3656
  foreach ($css as $css_file) {
3657
    $css_data[] = $css_file['data'];
3658
  }
3659
  $key = hash('sha256', serialize($css_data));
3660
  if (isset($map[$key])) {
3661
    $uri = $map[$key];
3662
  }
3663

    
3664
  if (empty($uri) || !file_exists($uri)) {
3665
    // Build aggregate CSS file.
3666
    foreach ($css as $stylesheet) {
3667
      // Only 'file' stylesheets can be aggregated.
3668
      if ($stylesheet['type'] == 'file') {
3669
        $contents = drupal_load_stylesheet($stylesheet['data'], TRUE);
3670

    
3671
        // Build the base URL of this CSS file: start with the full URL.
3672
        $css_base_url = file_create_url($stylesheet['data']);
3673
        // Move to the parent.
3674
        $css_base_url = substr($css_base_url, 0, strrpos($css_base_url, '/'));
3675
        // Simplify to a relative URL if the stylesheet URL starts with the
3676
        // base URL of the website.
3677
        if (substr($css_base_url, 0, strlen($GLOBALS['base_root'])) == $GLOBALS['base_root']) {
3678
          $css_base_url = substr($css_base_url, strlen($GLOBALS['base_root']));
3679
        }
3680

    
3681
        _drupal_build_css_path(NULL, $css_base_url . '/');
3682
        // Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
3683
        $data .= preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);
3684
      }
3685
    }
3686

    
3687
    // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
3688
    // @import rules must proceed any other style, so we move those to the top.
3689
    $regexp = '/@import[^;]+;/i';
3690
    preg_match_all($regexp, $data, $matches);
3691
    $data = preg_replace($regexp, '', $data);
3692
    $data = implode('', $matches[0]) . $data;
3693

    
3694
    // Prefix filename to prevent blocking by firewalls which reject files
3695
    // starting with "ad*".
3696
    $filename = 'css_' . drupal_hash_base64($data) . '.css';
3697
    // Create the css/ within the files folder.
3698
    $csspath = 'public://css';
3699
    $uri = $csspath . '/' . $filename;
3700
    // Create the CSS file.
3701
    file_prepare_directory($csspath, FILE_CREATE_DIRECTORY);
3702
    if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
3703
      return FALSE;
3704
    }
3705
    // If CSS gzip compression is enabled, clean URLs are enabled (which means
3706
    // that rewrite rules are working) and the zlib extension is available then
3707
    // create a gzipped version of this file. This file is served conditionally
3708
    // to browsers that accept gzip using .htaccess rules.
3709
    if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
3710
      if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
3711
        return FALSE;
3712
      }
3713
    }
3714
    // Save the updated map.
3715
    $map[$key] = $uri;
3716
    variable_set('drupal_css_cache_files', $map);
3717
  }
3718
  return $uri;
3719
}
3720

    
3721
/**
3722
 * Prefixes all paths within a CSS file for drupal_build_css_cache().
3723
 */
3724
function _drupal_build_css_path($matches, $base = NULL) {
3725
  $_base = &drupal_static(__FUNCTION__);
3726
  // Store base path for preg_replace_callback.
3727
  if (isset($base)) {
3728
    $_base = $base;
3729
  }
3730

    
3731
  // Prefix with base and remove '../' segments where possible.
3732
  $path = $_base . $matches[1];
3733
  $last = '';
3734
  while ($path != $last) {
3735
    $last = $path;
3736
    $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
3737
  }
3738
  return 'url(' . $path . ')';
3739
}
3740

    
3741
/**
3742
 * Loads the stylesheet and resolves all @import commands.
3743
 *
3744
 * Loads a stylesheet and replaces @import commands with the contents of the
3745
 * imported file. Use this instead of file_get_contents when processing
3746
 * stylesheets.
3747
 *
3748
 * The returned contents are compressed removing white space and comments only
3749
 * when CSS aggregation is enabled. This optimization will not apply for
3750
 * color.module enabled themes with CSS aggregation turned off.
3751
 *
3752
 * @param $file
3753
 *   Name of the stylesheet to be processed.
3754
 * @param $optimize
3755
 *   Defines if CSS contents should be compressed or not.
3756
 * @param $reset_basepath
3757
 *   Used internally to facilitate recursive resolution of @import commands.
3758
 *
3759
 * @return
3760
 *   Contents of the stylesheet, including any resolved @import commands.
3761
 */
3762
function drupal_load_stylesheet($file, $optimize = NULL, $reset_basepath = TRUE) {
3763
  // These statics are not cache variables, so we don't use drupal_static().
3764
  static $_optimize, $basepath;
3765
  if ($reset_basepath) {
3766
    $basepath = '';
3767
  }
3768
  // Store the value of $optimize for preg_replace_callback with nested
3769
  // @import loops.
3770
  if (isset($optimize)) {
3771
    $_optimize = $optimize;
3772
  }
3773

    
3774
  // Stylesheets are relative one to each other. Start by adding a base path
3775
  // prefix provided by the parent stylesheet (if necessary).
3776
  if ($basepath && !file_uri_scheme($file)) {
3777
    $file = $basepath . '/' . $file;
3778
  }
3779
  // Store the parent base path to restore it later.
3780
  $parent_base_path = $basepath;
3781
  // Set the current base path to process possible child imports.
3782
  $basepath = dirname($file);
3783

    
3784
  // Load the CSS stylesheet. We suppress errors because themes may specify
3785
  // stylesheets in their .info file that don't exist in the theme's path,
3786
  // but are merely there to disable certain module CSS files.
3787
  $content = '';
3788
  if ($contents = @file_get_contents($file)) {
3789
    // Return the processed stylesheet.
3790
    $content = drupal_load_stylesheet_content($contents, $_optimize);
3791
  }
3792

    
3793
  // Restore the parent base path as the file and its childen are processed.
3794
  $basepath = $parent_base_path;
3795
  return $content;
3796
}
3797

    
3798
/**
3799
 * Processes the contents of a stylesheet for aggregation.
3800
 *
3801
 * @param $contents
3802
 *   The contents of the stylesheet.
3803
 * @param $optimize
3804
 *   (optional) Boolean whether CSS contents should be minified. Defaults to
3805
 *   FALSE.
3806
 *
3807
 * @return
3808
 *   Contents of the stylesheet including the imported stylesheets.
3809
 */
3810
function drupal_load_stylesheet_content($contents, $optimize = FALSE) {
3811
  // Remove multiple charset declarations for standards compliance (and fixing Safari problems).
3812
  $contents = preg_replace('/^@charset\s+[\'"](\S*?)\b[\'"];/i', '', $contents);
3813

    
3814
  if ($optimize) {
3815
    // Perform some safe CSS optimizations.
3816
    // Regexp to match comment blocks.
3817
    $comment     = '/\*[^*]*\*+(?:[^/*][^*]*\*+)*/';
3818
    // Regexp to match double quoted strings.
3819
    $double_quot = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
3820
    // Regexp to match single quoted strings.
3821
    $single_quot = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'";
3822
    // Strip all comment blocks, but keep double/single quoted strings.
3823
    $contents = preg_replace(
3824
      "<($double_quot|$single_quot)|$comment>Ss",
3825
      "$1",
3826
      $contents
3827
    );
3828
    // Remove certain whitespace.
3829
    // There are different conditions for removing leading and trailing
3830
    // whitespace.
3831
    // @see http://php.net/manual/regexp.reference.subpatterns.php
3832
    $contents = preg_replace('<
3833
      # Strip leading and trailing whitespace.
3834
        \s*([@{};,])\s*
3835
      # Strip only leading whitespace from:
3836
      # - Closing parenthesis: Retain "@media (bar) and foo".
3837
      | \s+([\)])
3838
      # Strip only trailing whitespace from:
3839
      # - Opening parenthesis: Retain "@media (bar) and foo".
3840
      # - Colon: Retain :pseudo-selectors.
3841
      | ([\(:])\s+
3842
    >xS',
3843
      // Only one of the three capturing groups will match, so its reference
3844
      // will contain the wanted value and the references for the
3845
      // two non-matching groups will be replaced with empty strings.
3846
      '$1$2$3',
3847
      $contents
3848
    );
3849
    // End the file with a new line.
3850
    $contents = trim($contents);
3851
    $contents .= "\n";
3852
  }
3853

    
3854
  // Replaces @import commands with the actual stylesheet content.
3855
  // This happens recursively but omits external files.
3856
  $contents = preg_replace_callback('/@import\s*(?:url\(\s*)?[\'"]?(?![a-z]+:)(?!\/\/)([^\'"\()]+)[\'"]?\s*\)?\s*;/', '_drupal_load_stylesheet', $contents);
3857
  return $contents;
3858
}
3859

    
3860
/**
3861
 * Loads stylesheets recursively and returns contents with corrected paths.
3862
 *
3863
 * This function is used for recursive loading of stylesheets and
3864
 * returns the stylesheet content with all url() paths corrected.
3865
 */
3866
function _drupal_load_stylesheet($matches) {
3867
  $filename = $matches[1];
3868
  // Load the imported stylesheet and replace @import commands in there as well.
3869
  $file = drupal_load_stylesheet($filename, NULL, FALSE);
3870

    
3871
  // Determine the file's directory.
3872
  $directory = dirname($filename);
3873
  // If the file is in the current directory, make sure '.' doesn't appear in
3874
  // the url() path.
3875
  $directory = $directory == '.' ? '' : $directory .'/';
3876

    
3877
  // Alter all internal url() paths. Leave external paths alone. We don't need
3878
  // to normalize absolute paths here (i.e. remove folder/... segments) because
3879
  // that will be done later.
3880
  return preg_replace('/url\(\s*([\'"]?)(?![a-z]+:|\/+)([^\'")]+)([\'"]?)\s*\)/i', 'url(\1' . $directory . '\2\3)', $file);
3881
}
3882

    
3883
/**
3884
 * Deletes old cached CSS files.
3885
 */
3886
function drupal_clear_css_cache() {
3887
  variable_del('drupal_css_cache_files');
3888
  file_scan_directory('public://css', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
3889
}
3890

    
3891
/**
3892
 * Callback to delete files modified more than a set time ago.
3893
 */
3894
function drupal_delete_file_if_stale($uri) {
3895
  // Default stale file threshold is 30 days.
3896
  if (REQUEST_TIME - filemtime($uri) > variable_get('drupal_stale_file_threshold', 2592000)) {
3897
    file_unmanaged_delete($uri);
3898
  }
3899
}
3900

    
3901
/**
3902
 * Prepares a string for use as a CSS identifier (element, class, or ID name).
3903
 *
3904
 * http://www.w3.org/TR/CSS21/syndata.html#characters shows the syntax for valid
3905
 * CSS identifiers (including element names, classes, and IDs in selectors.)
3906
 *
3907
 * @param $identifier
3908
 *   The identifier to clean.
3909
 * @param $filter
3910
 *   An array of string replacements to use on the identifier.
3911
 *
3912
 * @return
3913
 *   The cleaned identifier.
3914
 */
3915
function drupal_clean_css_identifier($identifier, $filter = array(' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '')) {
3916
  // Use the advanced drupal_static() pattern, since this is called very often.
3917
  static $drupal_static_fast;
3918
  if (!isset($drupal_static_fast)) {
3919
    $drupal_static_fast['allow_css_double_underscores'] = &drupal_static(__FUNCTION__ . ':allow_css_double_underscores');
3920
  }
3921
  $allow_css_double_underscores = &$drupal_static_fast['allow_css_double_underscores'];
3922
  if (!isset($allow_css_double_underscores)) {
3923
    $allow_css_double_underscores = variable_get('allow_css_double_underscores', FALSE);
3924
  }
3925

    
3926
  // Preserve BEM-style double-underscores depending on custom setting.
3927
  if ($allow_css_double_underscores) {
3928
    $filter['__'] = '__';
3929
  }
3930

    
3931
  // By default, we filter using Drupal's coding standards.
3932
  $identifier = strtr($identifier, $filter);
3933

    
3934
  // Valid characters in a CSS identifier are:
3935
  // - the hyphen (U+002D)
3936
  // - a-z (U+0030 - U+0039)
3937
  // - A-Z (U+0041 - U+005A)
3938
  // - the underscore (U+005F)
3939
  // - 0-9 (U+0061 - U+007A)
3940
  // - ISO 10646 characters U+00A1 and higher
3941
  // We strip out any character not in the above list.
3942
  $identifier = preg_replace('/[^\x{002D}\x{0030}-\x{0039}\x{0041}-\x{005A}\x{005F}\x{0061}-\x{007A}\x{00A1}-\x{FFFF}]/u', '', $identifier);
3943

    
3944
  return $identifier;
3945
}
3946

    
3947
/**
3948
 * Prepares a string for use as a valid class name.
3949
 *
3950
 * Do not pass one string containing multiple classes as they will be
3951
 * incorrectly concatenated with dashes, i.e. "one two" will become "one-two".
3952
 *
3953
 * @param $class
3954
 *   The class name to clean.
3955
 *
3956
 * @return
3957
 *   The cleaned class name.
3958
 */
3959
function drupal_html_class($class) {
3960
  // The output of this function will never change, so this uses a normal
3961
  // static instead of drupal_static().
3962
  static $classes = array();
3963

    
3964
  if (!isset($classes[$class])) {
3965
    $classes[$class] = drupal_clean_css_identifier(drupal_strtolower($class));
3966
  }
3967
  return $classes[$class];
3968
}
3969

    
3970
/**
3971
 * Prepares a string for use as a valid HTML ID and guarantees uniqueness.
3972
 *
3973
 * This function ensures that each passed HTML ID value only exists once on the
3974
 * page. By tracking the already returned ids, this function enables forms,
3975
 * blocks, and other content to be output multiple times on the same page,
3976
 * without breaking (X)HTML validation.
3977
 *
3978
 * For already existing IDs, a counter is appended to the ID string. Therefore,
3979
 * JavaScript and CSS code should not rely on any value that was generated by
3980
 * this function and instead should rely on manually added CSS classes or
3981
 * similarly reliable constructs.
3982
 *
3983
 * Two consecutive hyphens separate the counter from the original ID. To manage
3984
 * uniqueness across multiple Ajax requests on the same page, Ajax requests
3985
 * POST an array of all IDs currently present on the page, which are used to
3986
 * prime this function's cache upon first invocation.
3987
 *
3988
 * To allow reverse-parsing of IDs submitted via Ajax, any multiple consecutive
3989
 * hyphens in the originally passed $id are replaced with a single hyphen.
3990
 *
3991
 * @param $id
3992
 *   The ID to clean.
3993
 *
3994
 * @return
3995
 *   The cleaned ID.
3996
 */
3997
function drupal_html_id($id) {
3998
  // If this is an Ajax request, then content returned by this page request will
3999
  // be merged with content already on the base page. The HTML IDs must be
4000
  // unique for the fully merged content. Therefore, initialize $seen_ids to
4001
  // take into account IDs that are already in use on the base page.
4002
  static $drupal_static_fast;
4003
  if (!isset($drupal_static_fast['seen_ids_init'])) {
4004
    $drupal_static_fast['seen_ids_init'] = &drupal_static(__FUNCTION__ . ':init');
4005
  }
4006
  $seen_ids_init = &$drupal_static_fast['seen_ids_init'];
4007
  if (!isset($seen_ids_init)) {
4008
    // Ideally, Drupal would provide an API to persist state information about
4009
    // prior page requests in the database, and we'd be able to add this
4010
    // function's $seen_ids static variable to that state information in order
4011
    // to have it properly initialized for this page request. However, no such
4012
    // page state API exists, so instead, ajax.js adds all of the in-use HTML
4013
    // IDs to the POST data of Ajax submissions. Direct use of $_POST is
4014
    // normally not recommended as it could open up security risks, but because
4015
    // the raw POST data is cast to a number before being returned by this
4016
    // function, this usage is safe.
4017
    if (empty($_POST['ajax_html_ids'])) {
4018
      $seen_ids_init = array();
4019
    }
4020
    else {
4021
      // This function ensures uniqueness by appending a counter to the base id
4022
      // requested by the calling function after the first occurrence of that
4023
      // requested id. $_POST['ajax_html_ids'] contains the ids as they were
4024
      // returned by this function, potentially with the appended counter, so
4025
      // we parse that to reconstruct the $seen_ids array.
4026
      if (isset($_POST['ajax_html_ids'][0]) && strpos($_POST['ajax_html_ids'][0], ',') === FALSE) {
4027
        $ajax_html_ids = $_POST['ajax_html_ids'];
4028
      }
4029
      else {
4030
        // jquery.form.js may send the server a comma-separated string as the
4031
        // first element of an array (see http://drupal.org/node/1575060), so
4032
        // we need to convert it to an array in that case.
4033
        $ajax_html_ids = explode(',', $_POST['ajax_html_ids'][0]);
4034
      }
4035
      foreach ($ajax_html_ids as $seen_id) {
4036
        // We rely on '--' being used solely for separating a base id from the
4037
        // counter, which this function ensures when returning an id.
4038
        $parts = explode('--', $seen_id, 2);
4039
        if (!empty($parts[1]) && is_numeric($parts[1])) {
4040
          list($seen_id, $i) = $parts;
4041
        }
4042
        else {
4043
          $i = 1;
4044
        }
4045
        if (!isset($seen_ids_init[$seen_id]) || ($i > $seen_ids_init[$seen_id])) {
4046
          $seen_ids_init[$seen_id] = $i;
4047
        }
4048
      }
4049
    }
4050
  }
4051
  if (!isset($drupal_static_fast['seen_ids'])) {
4052
    $drupal_static_fast['seen_ids'] = &drupal_static(__FUNCTION__, $seen_ids_init);
4053
  }
4054
  $seen_ids = &$drupal_static_fast['seen_ids'];
4055

    
4056
  $id = strtr(drupal_strtolower($id), array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
4057

    
4058
  // As defined in http://www.w3.org/TR/html4/types.html#type-name, HTML IDs can
4059
  // only contain letters, digits ([0-9]), hyphens ("-"), underscores ("_"),
4060
  // colons (":"), and periods ("."). We strip out any character not in that
4061
  // list. Note that the CSS spec doesn't allow colons or periods in identifiers
4062
  // (http://www.w3.org/TR/CSS21/syndata.html#characters), so we strip those two
4063
  // characters as well.
4064
  $id = preg_replace('/[^A-Za-z0-9\-_]/', '', $id);
4065

    
4066
  // Removing multiple consecutive hyphens.
4067
  $id = preg_replace('/\-+/', '-', $id);
4068
  // Ensure IDs are unique by appending a counter after the first occurrence.
4069
  // The counter needs to be appended with a delimiter that does not exist in
4070
  // the base ID. Requiring a unique delimiter helps ensure that we really do
4071
  // return unique IDs and also helps us re-create the $seen_ids array during
4072
  // Ajax requests.
4073
  if (isset($seen_ids[$id])) {
4074
    $id = $id . '--' . ++$seen_ids[$id];
4075
  }
4076
  else {
4077
    $seen_ids[$id] = 1;
4078
  }
4079

    
4080
  return $id;
4081
}
4082

    
4083
/**
4084
 * Provides a standard HTML class name that identifies a page region.
4085
 *
4086
 * It is recommended that template preprocess functions apply this class to any
4087
 * page region that is output by the theme (Drupal core already handles this in
4088
 * the standard template preprocess implementation). Standardizing the class
4089
 * names in this way allows modules to implement certain features, such as
4090
 * drag-and-drop or dynamic Ajax loading, in a theme-independent way.
4091
 *
4092
 * @param $region
4093
 *   The name of the page region (for example, 'page_top' or 'content').
4094
 *
4095
 * @return
4096
 *   An HTML class that identifies the region (for example, 'region-page-top'
4097
 *   or 'region-content').
4098
 *
4099
 * @see template_preprocess_region()
4100
 */
4101
function drupal_region_class($region) {
4102
  return drupal_html_class("region-$region");
4103
}
4104

    
4105
/**
4106
 * Adds a JavaScript file, setting, or inline code to the page.
4107
 *
4108
 * The behavior of this function depends on the parameters it is called with.
4109
 * Generally, it handles the addition of JavaScript to the page, either as
4110
 * reference to an existing file or as inline code. The following actions can be
4111
 * performed using this function:
4112
 * - Add a file ('file'): Adds a reference to a JavaScript file to the page.
4113
 * - Add inline JavaScript code ('inline'): Executes a piece of JavaScript code
4114
 *   on the current page by placing the code directly in the page (for example,
4115
 *   to tell the user that a new message arrived, by opening a pop up, alert
4116
 *   box, etc.). This should only be used for JavaScript that cannot be executed
4117
 *   from a file. When adding inline code, make sure that you are not relying on
4118
 *   $() being the jQuery function. Wrap your code in
4119
 *   @code (function ($) {... })(jQuery); @endcode
4120
 *   or use jQuery() instead of $().
4121
 * - Add external JavaScript ('external'): Allows the inclusion of external
4122
 *   JavaScript files that are not hosted on the local server. Note that these
4123
 *   external JavaScript references do not get aggregated when preprocessing is
4124
 *   on.
4125
 * - Add settings ('setting'): Adds settings to Drupal's global storage of
4126
 *   JavaScript settings. Per-page settings are required by some modules to
4127
 *   function properly. All settings will be accessible at Drupal.settings.
4128
 *
4129
 * Examples:
4130
 * @code
4131
 *   drupal_add_js('misc/collapse.js');
4132
 *   drupal_add_js('misc/collapse.js', 'file');
4133
 *   drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
4134
 *   drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
4135
 *     array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
4136
 *   );
4137
 *   drupal_add_js('http://example.com/example.js', 'external');
4138
 *   drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');
4139
 * @endcode
4140
 *
4141
 * Calling drupal_static_reset('drupal_add_js') will clear all JavaScript added
4142
 * so far.
4143
 *
4144
 * If JavaScript aggregation is enabled, all JavaScript files added with
4145
 * $options['preprocess'] set to TRUE will be merged into one aggregate file.
4146
 * Preprocessed inline JavaScript will not be aggregated into this single file.
4147
 * Externally hosted JavaScripts are never aggregated.
4148
 *
4149
 * The reason for aggregating the files is outlined quite thoroughly here:
4150
 * http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
4151
 * to request overhead, one bigger file just loads faster than two smaller ones
4152
 * half its size."
4153
 *
4154
 * $options['preprocess'] should be only set to TRUE when a file is required for
4155
 * all typical visitors and most pages of a site. It is critical that all
4156
 * preprocessed files are added unconditionally on every page, even if the
4157
 * files are not needed on a page. This is normally done by calling
4158
 * drupal_add_js() in a hook_init() implementation.
4159
 *
4160
 * Non-preprocessed files should only be added to the page when they are
4161
 * actually needed.
4162
 *
4163
 * @param $data
4164
 *   (optional) If given, the value depends on the $options parameter, or
4165
 *   $options['type'] if $options is passed as an associative array:
4166
 *   - 'file': Path to the file relative to base_path().
4167
 *   - 'inline': The JavaScript code that should be placed in the given scope.
4168
 *   - 'external': The absolute path to an external JavaScript file that is not
4169
 *     hosted on the local server. These files will not be aggregated if
4170
 *     JavaScript aggregation is enabled.
4171
 *   - 'setting': An associative array with configuration options. The array is
4172
 *     merged directly into Drupal.settings. All modules should wrap their
4173
 *     actual configuration settings in another variable to prevent conflicts in
4174
 *     the Drupal.settings namespace. Items added with a string key will replace
4175
 *     existing settings with that key; items with numeric array keys will be
4176
 *     added to the existing settings array.
4177
 * @param $options
4178
 *   (optional) A string defining the type of JavaScript that is being added in
4179
 *   the $data parameter ('file'/'setting'/'inline'/'external'), or an
4180
 *   associative array. JavaScript settings should always pass the string
4181
 *   'setting' only. Other types can have the following elements in the array:
4182
 *   - type: The type of JavaScript that is to be added to the page. Allowed
4183
 *     values are 'file', 'inline', 'external' or 'setting'. Defaults
4184
 *     to 'file'.
4185
 *   - scope: The location in which you want to place the script. Possible
4186
 *     values are 'header' or 'footer'. If your theme implements different
4187
 *     regions, you can also use these. Defaults to 'header'.
4188
 *   - group: A number identifying the group in which to add the JavaScript.
4189
 *     Available constants are:
4190
 *     - JS_LIBRARY: Any libraries, settings, or jQuery plugins.
4191
 *     - JS_DEFAULT: Any module-layer JavaScript.
4192
 *     - JS_THEME: Any theme-layer JavaScript.
4193
 *     The group number serves as a weight: JavaScript within a lower weight
4194
 *     group is presented on the page before JavaScript within a higher weight
4195
 *     group.
4196
 *   - every_page: For optimal front-end performance when aggregation is
4197
 *     enabled, this should be set to TRUE if the JavaScript is present on every
4198
 *     page of the website for users for whom it is present at all. This
4199
 *     defaults to FALSE. It is set to TRUE for JavaScript files that are added
4200
 *     via module and theme .info files. Modules that add JavaScript within
4201
 *     hook_init() implementations, or from other code that ensures that the
4202
 *     JavaScript is added to all website pages, should also set this flag to
4203
 *     TRUE. All JavaScript files within the same group and that have the
4204
 *     'every_page' flag set to TRUE and do not have 'preprocess' set to FALSE
4205
 *     are aggregated together into a single aggregate file, and that aggregate
4206
 *     file can be reused across a user's entire site visit, leading to faster
4207
 *     navigation between pages. However, JavaScript that is only needed on
4208
 *     pages less frequently visited, can be added by code that only runs for
4209
 *     those particular pages, and that code should not set the 'every_page'
4210
 *     flag. This minimizes the size of the aggregate file that the user needs
4211
 *     to download when first visiting the website. JavaScript without the
4212
 *     'every_page' flag is aggregated into a separate aggregate file. This
4213
 *     other aggregate file is likely to change from page to page, and each new
4214
 *     aggregate file needs to be downloaded when first encountered, so it
4215
 *     should be kept relatively small by ensuring that most commonly needed
4216
 *     JavaScript is added to every page.
4217
 *   - weight: A number defining the order in which the JavaScript is added to
4218
 *     the page relative to other JavaScript with the same 'scope', 'group',
4219
 *     and 'every_page' value. In some cases, the order in which the JavaScript
4220
 *     is presented on the page is very important. jQuery, for example, must be
4221
 *     added to the page before any jQuery code is run, so jquery.js uses the
4222
 *     JS_LIBRARY group and a weight of -20, jquery.once.js (a library drupal.js
4223
 *     depends on) uses the JS_LIBRARY group and a weight of -19, drupal.js uses
4224
 *     the JS_LIBRARY group and a weight of -1, other libraries use the
4225
 *     JS_LIBRARY group and a weight of 0 or higher, and all other scripts use
4226
 *     one of the other group constants. The exact ordering of JavaScript is as
4227
 *     follows:
4228
 *     - First by scope, with 'header' first, 'footer' last, and any other
4229
 *       scopes provided by a custom theme coming in between, as determined by
4230
 *       the theme.
4231
 *     - Then by group.
4232
 *     - Then by the 'every_page' flag, with TRUE coming before FALSE.
4233
 *     - Then by weight.
4234
 *     - Then by the order in which the JavaScript was added. For example, all
4235
 *       else being the same, JavaScript added by a call to drupal_add_js() that
4236
 *       happened later in the page request gets added to the page after one for
4237
 *       which drupal_add_js() happened earlier in the page request.
4238
 *   - requires_jquery: Set this to FALSE if the JavaScript you are adding does
4239
 *     not have a dependency on jQuery. Defaults to TRUE, except for JavaScript
4240
 *     settings where it defaults to FALSE. This is used on sites that have the
4241
 *     'javascript_always_use_jquery' variable set to FALSE; on those sites, if
4242
 *     all the JavaScript added to the page by drupal_add_js() does not have a
4243
 *     dependency on jQuery, then for improved front-end performance Drupal
4244
 *     will not add jQuery and related libraries and settings to the page.
4245
 *   - defer: If set to TRUE, the defer attribute is set on the <script>
4246
 *     tag. Defaults to FALSE.
4247
 *   - cache: If set to FALSE, the JavaScript file is loaded anew on every page
4248
 *     call; in other words, it is not cached. Used only when 'type' references
4249
 *     a JavaScript file. Defaults to TRUE.
4250
 *   - preprocess: If TRUE and JavaScript aggregation is enabled, the script
4251
 *     file will be aggregated. Defaults to TRUE.
4252
 *
4253
 * @return
4254
 *   The current array of JavaScript files, settings, and in-line code,
4255
 *   including Drupal defaults, anything previously added with calls to
4256
 *   drupal_add_js(), and this function call's additions.
4257
 *
4258
 * @see drupal_get_js()
4259
 */
4260
function drupal_add_js($data = NULL, $options = NULL) {
4261
  $javascript = &drupal_static(__FUNCTION__, array());
4262
  $jquery_added = &drupal_static(__FUNCTION__ . ':jquery_added', FALSE);
4263

    
4264
  // If the $javascript variable has been reset with drupal_static_reset(),
4265
  // jQuery and related files will have been removed from the list, so set the
4266
  // variable back to FALSE to indicate they have not yet been added.
4267
  if (empty($javascript)) {
4268
    $jquery_added = FALSE;
4269
  }
4270

    
4271
  // Construct the options, taking the defaults into consideration.
4272
  if (isset($options)) {
4273
    if (!is_array($options)) {
4274
      $options = array('type' => $options);
4275
    }
4276
  }
4277
  else {
4278
    $options = array();
4279
  }
4280
  if (isset($options['type']) && $options['type'] == 'setting') {
4281
    $options += array('requires_jquery' => FALSE);
4282
  }
4283
  $options += drupal_js_defaults($data);
4284

    
4285
  // Preprocess can only be set if caching is enabled.
4286
  $options['preprocess'] = $options['cache'] ? $options['preprocess'] : FALSE;
4287

    
4288
  // Tweak the weight so that files of the same weight are included in the
4289
  // order of the calls to drupal_add_js().
4290
  $options['weight'] += count($javascript) / 1000;
4291

    
4292
  if (isset($data)) {
4293
    // Add jquery.js, drupal.js, and related files and settings if they have
4294
    // not been added yet. However, if the 'javascript_always_use_jquery'
4295
    // variable is set to FALSE (indicating that the site does not want jQuery
4296
    // automatically added on all pages) then only add it if a file or setting
4297
    // that requires jQuery is being added also.
4298
    if (!$jquery_added && (variable_get('javascript_always_use_jquery', TRUE) || $options['requires_jquery'])) {
4299
      $jquery_added = TRUE;
4300
      // url() generates the prefix using hook_url_outbound_alter(). Instead of
4301
      // running the hook_url_outbound_alter() again here, extract the prefix
4302
      // from url().
4303
      url('', array('prefix' => &$prefix));
4304
      $default_javascript = array(
4305
        'settings' => array(
4306
          'data' => array(
4307
            array('basePath' => base_path()),
4308
            array('pathPrefix' => empty($prefix) ? '' : $prefix),
4309
          ),
4310
          'type' => 'setting',
4311
          'scope' => 'header',
4312
          'group' => JS_LIBRARY,
4313
          'every_page' => TRUE,
4314
          'weight' => 0,
4315
        ),
4316
        'misc/drupal.js' => array(
4317
          'data' => 'misc/drupal.js',
4318
          'type' => 'file',
4319
          'scope' => 'header',
4320
          'group' => JS_LIBRARY,
4321
          'every_page' => TRUE,
4322
          'weight' => -1,
4323
          'requires_jquery' => TRUE,
4324
          'preprocess' => TRUE,
4325
          'cache' => TRUE,
4326
          'defer' => FALSE,
4327
        ),
4328
      );
4329
      $javascript = drupal_array_merge_deep($javascript, $default_javascript);
4330
      // Register all required libraries.
4331
      drupal_add_library('system', 'jquery', TRUE);
4332
      drupal_add_library('system', 'jquery.once', TRUE);
4333
    }
4334

    
4335
    switch ($options['type']) {
4336
      case 'setting':
4337
        // All JavaScript settings are placed in the header of the page with
4338
        // the library weight so that inline scripts appear afterwards.
4339
        $javascript['settings']['data'][] = $data;
4340
        break;
4341

    
4342
      case 'inline':
4343
        $javascript[] = $options;
4344
        break;
4345

    
4346
      default: // 'file' and 'external'
4347
        // Local and external files must keep their name as the associative key
4348
        // so the same JavaScript file is not added twice.
4349
        $javascript[$options['data']] = $options;
4350
    }
4351
  }
4352
  return $javascript;
4353
}
4354

    
4355
/**
4356
 * Constructs an array of the defaults that are used for JavaScript items.
4357
 *
4358
 * @param $data
4359
 *   (optional) The default data parameter for the JavaScript item array.
4360
 *
4361
 * @see drupal_get_js()
4362
 * @see drupal_add_js()
4363
 */
4364
function drupal_js_defaults($data = NULL) {
4365
  return array(
4366
    'type' => 'file',
4367
    'group' => JS_DEFAULT,
4368
    'every_page' => FALSE,
4369
    'weight' => 0,
4370
    'requires_jquery' => TRUE,
4371
    'scope' => 'header',
4372
    'cache' => TRUE,
4373
    'defer' => FALSE,
4374
    'preprocess' => TRUE,
4375
    'version' => NULL,
4376
    'data' => $data,
4377
  );
4378
}
4379

    
4380
/**
4381
 * Returns a themed presentation of all JavaScript code for the current page.
4382
 *
4383
 * References to JavaScript files are placed in a certain order: first, all
4384
 * 'core' files, then all 'module' and finally all 'theme' JavaScript files
4385
 * are added to the page. Then, all settings are output, followed by 'inline'
4386
 * JavaScript code. If running update.php, all preprocessing is disabled.
4387
 *
4388
 * Note that hook_js_alter(&$javascript) is called during this function call
4389
 * to allow alterations of the JavaScript during its presentation. Calls to
4390
 * drupal_add_js() from hook_js_alter() will not be added to the output
4391
 * presentation. The correct way to add JavaScript during hook_js_alter()
4392
 * is to add another element to the $javascript array, deriving from
4393
 * drupal_js_defaults(). See locale_js_alter() for an example of this.
4394
 *
4395
 * @param $scope
4396
 *   (optional) The scope for which the JavaScript rules should be returned.
4397
 *   Defaults to 'header'.
4398
 * @param $javascript
4399
 *   (optional) An array with all JavaScript code. Defaults to the default
4400
 *   JavaScript array for the given scope.
4401
 * @param $skip_alter
4402
 *   (optional) If set to TRUE, this function skips calling drupal_alter() on
4403
 *   $javascript, useful when the calling function passes a $javascript array
4404
 *   that has already been altered.
4405
 *
4406
 * @return
4407
 *   All JavaScript code segments and includes for the scope as HTML tags.
4408
 *
4409
 * @see drupal_add_js()
4410
 * @see locale_js_alter()
4411
 * @see drupal_js_defaults()
4412
 */
4413
function drupal_get_js($scope = 'header', $javascript = NULL, $skip_alter = FALSE) {
4414
  if (!isset($javascript)) {
4415
    $javascript = drupal_add_js();
4416
  }
4417

    
4418
  // If no JavaScript items have been added, or if the only JavaScript items
4419
  // that have been added are JavaScript settings (which don't do anything
4420
  // without any JavaScript code to use them), then no JavaScript code should
4421
  // be added to the page.
4422
  if (empty($javascript) || (isset($javascript['settings']) && count($javascript) == 1)) {
4423
    return '';
4424
  }
4425

    
4426
  // Allow modules to alter the JavaScript.
4427
  if (!$skip_alter) {
4428
    drupal_alter('js', $javascript);
4429
  }
4430

    
4431
  // Filter out elements of the given scope.
4432
  $items = array();
4433
  foreach ($javascript as $key => $item) {
4434
    if ($item['scope'] == $scope) {
4435
      $items[$key] = $item;
4436
    }
4437
  }
4438

    
4439
  $output = '';
4440
  // The index counter is used to keep aggregated and non-aggregated files in
4441
  // order by weight.
4442
  $index = 1;
4443
  $processed = array();
4444
  $files = array();
4445
  $preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
4446

    
4447
  // A dummy query-string is added to filenames, to gain control over
4448
  // browser-caching. The string changes on every update or full cache
4449
  // flush, forcing browsers to load a new copy of the files, as the
4450
  // URL changed. Files that should not be cached (see drupal_add_js())
4451
  // get REQUEST_TIME as query-string instead, to enforce reload on every
4452
  // page request.
4453
  $default_query_string = variable_get('css_js_query_string', '0');
4454

    
4455
  // For inline JavaScript to validate as XHTML, all JavaScript containing
4456
  // XHTML needs to be wrapped in CDATA. To make that backwards compatible
4457
  // with HTML 4, we need to comment out the CDATA-tag.
4458
  $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
4459
  $embed_suffix = "\n//--><!]]>\n";
4460

    
4461
  // Since JavaScript may look for arguments in the URL and act on them, some
4462
  // third-party code might require the use of a different query string.
4463
  $js_version_string = variable_get('drupal_js_version_query_string', 'v=');
4464

    
4465
  // Sort the JavaScript so that it appears in the correct order.
4466
  uasort($items, 'drupal_sort_css_js');
4467

    
4468
  // Provide the page with information about the individual JavaScript files
4469
  // used, information not otherwise available when aggregation is enabled.
4470
  $setting['ajaxPageState']['js'] = array_fill_keys(array_keys($items), 1);
4471
  unset($setting['ajaxPageState']['js']['settings']);
4472
  drupal_add_js($setting, 'setting');
4473

    
4474
  // If we're outputting the header scope, then this might be the final time
4475
  // that drupal_get_js() is running, so add the setting to this output as well
4476
  // as to the drupal_add_js() cache. If $items['settings'] doesn't exist, it's
4477
  // because drupal_get_js() was intentionally passed a $javascript argument
4478
  // stripped off settings, potentially in order to override how settings get
4479
  // output, so in this case, do not add the setting to this output.
4480
  if ($scope == 'header' && isset($items['settings'])) {
4481
    $items['settings']['data'][] = $setting;
4482
  }
4483

    
4484
  // Loop through the JavaScript to construct the rendered output.
4485
  $element = array(
4486
    '#tag' => 'script',
4487
    '#value' => '',
4488
    '#attributes' => array(
4489
      'type' => 'text/javascript',
4490
    ),
4491
  );
4492
  foreach ($items as $item) {
4493
    $query_string =  empty($item['version']) ? $default_query_string : $js_version_string . $item['version'];
4494

    
4495
    switch ($item['type']) {
4496
      case 'setting':
4497
        $js_element = $element;
4498
        $js_element['#value_prefix'] = $embed_prefix;
4499
        $js_element['#value'] = 'jQuery.extend(Drupal.settings, ' . drupal_json_encode(drupal_array_merge_deep_array($item['data'])) . ");";
4500
        $js_element['#value_suffix'] = $embed_suffix;
4501
        $output .= theme('html_tag', array('element' => $js_element));
4502
        break;
4503

    
4504
      case 'inline':
4505
        $js_element = $element;
4506
        if ($item['defer']) {
4507
          $js_element['#attributes']['defer'] = 'defer';
4508
        }
4509
        $js_element['#value_prefix'] = $embed_prefix;
4510
        $js_element['#value'] = $item['data'];
4511
        $js_element['#value_suffix'] = $embed_suffix;
4512
        $processed[$index++] = theme('html_tag', array('element' => $js_element));
4513
        break;
4514

    
4515
      case 'file':
4516
        $js_element = $element;
4517
        if (!$item['preprocess'] || !$preprocess_js) {
4518
          if ($item['defer']) {
4519
            $js_element['#attributes']['defer'] = 'defer';
4520
          }
4521
          $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
4522
          $js_element['#attributes']['src'] = file_create_url($item['data']) . $query_string_separator . ($item['cache'] ? $query_string : REQUEST_TIME);
4523
          $processed[$index++] = theme('html_tag', array('element' => $js_element));
4524
        }
4525
        else {
4526
          // By increasing the index for each aggregated file, we maintain
4527
          // the relative ordering of JS by weight. We also set the key such
4528
          // that groups are split by items sharing the same 'group' value and
4529
          // 'every_page' flag. While this potentially results in more aggregate
4530
          // files, it helps make each one more reusable across a site visit,
4531
          // leading to better front-end performance of a website as a whole.
4532
          // See drupal_add_js() for details.
4533
          $key = 'aggregate_' . $item['group'] . '_' . $item['every_page'] . '_' . $index;
4534
          $processed[$key] = '';
4535
          $files[$key][$item['data']] = $item;
4536
        }
4537
        break;
4538

    
4539
      case 'external':
4540
        $js_element = $element;
4541
        // Preprocessing for external JavaScript files is ignored.
4542
        if ($item['defer']) {
4543
          $js_element['#attributes']['defer'] = 'defer';
4544
        }
4545
        $js_element['#attributes']['src'] = $item['data'];
4546
        $processed[$index++] = theme('html_tag', array('element' => $js_element));
4547
        break;
4548
    }
4549
  }
4550

    
4551
  // Aggregate any remaining JS files that haven't already been output.
4552
  if ($preprocess_js && count($files) > 0) {
4553
    foreach ($files as $key => $file_set) {
4554
      $uri = drupal_build_js_cache($file_set);
4555
      // Only include the file if was written successfully. Errors are logged
4556
      // using watchdog.
4557
      if ($uri) {
4558
        $preprocess_file = file_create_url($uri);
4559
        $js_element = $element;
4560
        $js_element['#attributes']['src'] = $preprocess_file;
4561
        $processed[$key] = theme('html_tag', array('element' => $js_element));
4562
      }
4563
    }
4564
  }
4565

    
4566
  // Keep the order of JS files consistent as some are preprocessed and others are not.
4567
  // Make sure any inline or JS setting variables appear last after libraries have loaded.
4568
  return implode('', $processed) . $output;
4569
}
4570

    
4571
/**
4572
 * Adds attachments to a render() structure.
4573
 *
4574
 * Libraries, JavaScript, CSS and other types of custom structures are attached
4575
 * to elements using the #attached property. The #attached property is an
4576
 * associative array, where the keys are the attachment types and the values are
4577
 * the attached data. For example:
4578
 * @code
4579
 * $build['#attached'] = array(
4580
 *   'js' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.js'),
4581
 *   'css' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.css'),
4582
 * );
4583
 * @endcode
4584
 *
4585
 * 'js', 'css', and 'library' are types that get special handling. For any
4586
 * other kind of attached data, the array key must be the full name of the
4587
 * callback function and each value an array of arguments. For example:
4588
 * @code
4589
 * $build['#attached']['drupal_add_http_header'] = array(
4590
 *   array('Content-Type', 'application/rss+xml; charset=utf-8'),
4591
 * );
4592
 * @endcode
4593
 *
4594
 * External 'js' and 'css' files can also be loaded. For example:
4595
 * @code
4596
 * $build['#attached']['js'] = array(
4597
 *   'http://code.jquery.com/jquery-1.4.2.min.js' => array(
4598
 *     'type' => 'external',
4599
 *   ),
4600
 * );
4601
 * @endcode
4602
 *
4603
 * @param $elements
4604
 *   The structured array describing the data being rendered.
4605
 * @param $group
4606
 *   The default group of JavaScript and CSS being added. This is only applied
4607
 *   to the stylesheets and JavaScript items that don't have an explicit group
4608
 *   assigned to them.
4609
 * @param $dependency_check
4610
 *   When TRUE, will exit if a given library's dependencies are missing. When
4611
 *   set to FALSE, will continue to add the libraries, even though one or more
4612
 *   dependencies are missing. Defaults to FALSE.
4613
 * @param $every_page
4614
 *   Set to TRUE to indicate that the attachments are added to every page on the
4615
 *   site. Only attachments with the every_page flag set to TRUE can participate
4616
 *   in JavaScript/CSS aggregation.
4617
 *
4618
 * @return
4619
 *   FALSE if there were any missing library dependencies; TRUE if all library
4620
 *   dependencies were met.
4621
 *
4622
 * @see drupal_add_library()
4623
 * @see drupal_add_js()
4624
 * @see drupal_add_css()
4625
 * @see drupal_render()
4626
 */
4627
function drupal_process_attached($elements, $group = JS_DEFAULT, $dependency_check = FALSE, $every_page = NULL) {
4628
  // Add defaults to the special attached structures that should be processed differently.
4629
  $elements['#attached'] += array(
4630
    'library' => array(),
4631
    'js' => array(),
4632
    'css' => array(),
4633
  );
4634

    
4635
  // Add the libraries first.
4636
  $success = TRUE;
4637
  foreach ($elements['#attached']['library'] as $library) {
4638
    if (drupal_add_library($library[0], $library[1], $every_page) === FALSE) {
4639
      $success = FALSE;
4640
      // Exit if the dependency is missing.
4641
      if ($dependency_check) {
4642
        return $success;
4643
      }
4644
    }
4645
  }
4646
  unset($elements['#attached']['library']);
4647

    
4648
  // Add both the JavaScript and the CSS.
4649
  // The parameters for drupal_add_js() and drupal_add_css() require special
4650
  // handling.
4651
  foreach (array('js', 'css') as $type) {
4652
    foreach ($elements['#attached'][$type] as $data => $options) {
4653
      // If the value is not an array, it's a filename and passed as first
4654
      // (and only) argument.
4655
      if (!is_array($options)) {
4656
        $data = $options;
4657
        $options = NULL;
4658
      }
4659
      // In some cases, the first parameter ($data) is an array. Arrays can't be
4660
      // passed as keys in PHP, so we have to get $data from the value array.
4661
      if (is_numeric($data)) {
4662
        $data = $options['data'];
4663
        unset($options['data']);
4664
      }
4665
      // Apply the default group if it isn't explicitly given.
4666
      if (!isset($options['group'])) {
4667
        $options['group'] = $group;
4668
      }
4669
      // Set the every_page flag if one was passed.
4670
      if (isset($every_page)) {
4671
        $options['every_page'] = $every_page;
4672
      }
4673
      call_user_func('drupal_add_' . $type, $data, $options);
4674
    }
4675
    unset($elements['#attached'][$type]);
4676
  }
4677

    
4678
  // Add additional types of attachments specified in the render() structure.
4679
  // Libraries, JavaScript and CSS have been added already, as they require
4680
  // special handling.
4681
  foreach ($elements['#attached'] as $callback => $options) {
4682
    if (function_exists($callback)) {
4683
      foreach ($elements['#attached'][$callback] as $args) {
4684
        call_user_func_array($callback, $args);
4685
      }
4686
    }
4687
  }
4688

    
4689
  return $success;
4690
}
4691

    
4692
/**
4693
 * Adds JavaScript to change the state of an element based on another element.
4694
 *
4695
 * A "state" means a certain property on a DOM element, such as "visible" or
4696
 * "checked". A state can be applied to an element, depending on the state of
4697
 * another element on the page. In general, states depend on HTML attributes and
4698
 * DOM element properties, which change due to user interaction.
4699
 *
4700
 * Since states are driven by JavaScript only, it is important to understand
4701
 * that all states are applied on presentation only, none of the states force
4702
 * any server-side logic, and that they will not be applied for site visitors
4703
 * without JavaScript support. All modules implementing states have to make
4704
 * sure that the intended logic also works without JavaScript being enabled.
4705
 *
4706
 * #states is an associative array in the form of:
4707
 * @code
4708
 * array(
4709
 *   STATE1 => CONDITIONS_ARRAY1,
4710
 *   STATE2 => CONDITIONS_ARRAY2,
4711
 *   ...
4712
 * )
4713
 * @endcode
4714
 * Each key is the name of a state to apply to the element, such as 'visible'.
4715
 * Each value is a list of conditions that denote when the state should be
4716
 * applied.
4717
 *
4718
 * Multiple different states may be specified to act on complex conditions:
4719
 * @code
4720
 * array(
4721
 *   'visible' => CONDITIONS,
4722
 *   'checked' => OTHER_CONDITIONS,
4723
 * )
4724
 * @endcode
4725
 *
4726
 * Every condition is a key/value pair, whose key is a jQuery selector that
4727
 * denotes another element on the page, and whose value is an array of
4728
 * conditions, which must bet met on that element:
4729
 * @code
4730
 * array(
4731
 *   'visible' => array(
4732
 *     JQUERY_SELECTOR => REMOTE_CONDITIONS,
4733
 *     JQUERY_SELECTOR => REMOTE_CONDITIONS,
4734
 *     ...
4735
 *   ),
4736
 * )
4737
 * @endcode
4738
 * All conditions must be met for the state to be applied.
4739
 *
4740
 * Each remote condition is a key/value pair specifying conditions on the other
4741
 * element that need to be met to apply the state to the element:
4742
 * @code
4743
 * array(
4744
 *   'visible' => array(
4745
 *     ':input[name="remote_checkbox"]' => array('checked' => TRUE),
4746
 *   ),
4747
 * )
4748
 * @endcode
4749
 *
4750
 * For example, to show a textfield only when a checkbox is checked:
4751
 * @code
4752
 * $form['toggle_me'] = array(
4753
 *   '#type' => 'checkbox',
4754
 *   '#title' => t('Tick this box to type'),
4755
 * );
4756
 * $form['settings'] = array(
4757
 *   '#type' => 'textfield',
4758
 *   '#states' => array(
4759
 *     // Only show this field when the 'toggle_me' checkbox is enabled.
4760
 *     'visible' => array(
4761
 *       ':input[name="toggle_me"]' => array('checked' => TRUE),
4762
 *     ),
4763
 *   ),
4764
 * );
4765
 * @endcode
4766
 *
4767
 * The following states may be applied to an element:
4768
 * - enabled
4769
 * - disabled
4770
 * - required
4771
 * - optional
4772
 * - visible
4773
 * - invisible
4774
 * - checked
4775
 * - unchecked
4776
 * - expanded
4777
 * - collapsed
4778
 *
4779
 * The following states may be used in remote conditions:
4780
 * - empty
4781
 * - filled
4782
 * - checked
4783
 * - unchecked
4784
 * - expanded
4785
 * - collapsed
4786
 * - value
4787
 *
4788
 * The following states exist for both elements and remote conditions, but are
4789
 * not fully implemented and may not change anything on the element:
4790
 * - relevant
4791
 * - irrelevant
4792
 * - valid
4793
 * - invalid
4794
 * - touched
4795
 * - untouched
4796
 * - readwrite
4797
 * - readonly
4798
 *
4799
 * When referencing select lists and radio buttons in remote conditions, a
4800
 * 'value' condition must be used:
4801
 * @code
4802
 *   '#states' => array(
4803
 *     // Show the settings if 'bar' has been selected for 'foo'.
4804
 *     'visible' => array(
4805
 *       ':input[name="foo"]' => array('value' => 'bar'),
4806
 *     ),
4807
 *   ),
4808
 * @endcode
4809
 *
4810
 * @param $elements
4811
 *   A renderable array element having a #states property as described above.
4812
 *
4813
 * @see form_example_states_form()
4814
 */
4815
function drupal_process_states(&$elements) {
4816
  $elements['#attached']['library'][] = array('system', 'drupal.states');
4817
  $elements['#attached']['js'][] = array(
4818
    'type' => 'setting',
4819
    'data' => array('states' => array('#' . $elements['#id'] => $elements['#states'])),
4820
  );
4821
}
4822

    
4823
/**
4824
 * Adds multiple JavaScript or CSS files at the same time.
4825
 *
4826
 * A library defines a set of JavaScript and/or CSS files, optionally using
4827
 * settings, and optionally requiring another library. For example, a library
4828
 * can be a jQuery plugin, a JavaScript framework, or a CSS framework. This
4829
 * function allows modules to load a library defined/shipped by itself or a
4830
 * depending module, without having to add all files of the library separately.
4831
 * Each library is only loaded once.
4832
 *
4833
 * @param $module
4834
 *   The name of the module that registered the library.
4835
 * @param $name
4836
 *   The name of the library to add.
4837
 * @param $every_page
4838
 *   Set to TRUE if this library is added to every page on the site. Only items
4839
 *   with the every_page flag set to TRUE can participate in aggregation.
4840
 *
4841
 * @return
4842
 *   TRUE if the library was successfully added; FALSE if the library or one of
4843
 *   its dependencies could not be added.
4844
 *
4845
 * @see drupal_get_library()
4846
 * @see hook_library()
4847
 * @see hook_library_alter()
4848
 */
4849
function drupal_add_library($module, $name, $every_page = NULL) {
4850
  $added = &drupal_static(__FUNCTION__, array());
4851

    
4852
  // Only process the library if it exists and it was not added already.
4853
  if (!isset($added[$module][$name])) {
4854
    if ($library = drupal_get_library($module, $name)) {
4855
      // Add all components within the library.
4856
      $elements['#attached'] = array(
4857
        'library' => $library['dependencies'],
4858
        'js' => $library['js'],
4859
        'css' => $library['css'],
4860
      );
4861
      $added[$module][$name] = drupal_process_attached($elements, JS_LIBRARY, TRUE, $every_page);
4862
    }
4863
    else {
4864
      // Requested library does not exist.
4865
      $added[$module][$name] = FALSE;
4866
    }
4867
  }
4868

    
4869
  return $added[$module][$name];
4870
}
4871

    
4872
/**
4873
 * Retrieves information for a JavaScript/CSS library.
4874
 *
4875
 * Library information is statically cached. Libraries are keyed by module for
4876
 * several reasons:
4877
 * - Libraries are not unique. Multiple modules might ship with the same library
4878
 *   in a different version or variant. This registry cannot (and does not
4879
 *   attempt to) prevent library conflicts.
4880
 * - Modules implementing and thereby depending on a library that is registered
4881
 *   by another module can only rely on that module's library.
4882
 * - Two (or more) modules can still register the same library and use it
4883
 *   without conflicts in case the libraries are loaded on certain pages only.
4884
 *
4885
 * @param $module
4886
 *   The name of a module that registered a library.
4887
 * @param $name
4888
 *   (optional) The name of a registered library to retrieve. By default, all
4889
 *   libraries registered by $module are returned.
4890
 *
4891
 * @return
4892
 *   The definition of the requested library, if $name was passed and it exists,
4893
 *   or FALSE if it does not exist. If no $name was passed, an associative array
4894
 *   of libraries registered by $module is returned (which may be empty).
4895
 *
4896
 * @see drupal_add_library()
4897
 * @see hook_library()
4898
 * @see hook_library_alter()
4899
 *
4900
 * @todo The purpose of drupal_get_*() is completely different to other page
4901
 *   requisite API functions; find and use a different name.
4902
 */
4903
function drupal_get_library($module, $name = NULL) {
4904
  $libraries = &drupal_static(__FUNCTION__, array());
4905

    
4906
  if (!isset($libraries[$module])) {
4907
    // Retrieve all libraries associated with the module.
4908
    $module_libraries = module_invoke($module, 'library');
4909
    if (empty($module_libraries)) {
4910
      $module_libraries = array();
4911
    }
4912
    // Allow modules to alter the module's registered libraries.
4913
    drupal_alter('library', $module_libraries, $module);
4914

    
4915
    foreach ($module_libraries as $key => $data) {
4916
      if (is_array($data)) {
4917
        // Add default elements to allow for easier processing.
4918
        $module_libraries[$key] += array('dependencies' => array(), 'js' => array(), 'css' => array());
4919
        foreach ($module_libraries[$key]['js'] as $file => $options) {
4920
          $module_libraries[$key]['js'][$file]['version'] = $module_libraries[$key]['version'];
4921
        }
4922
      }
4923
    }
4924
    $libraries[$module] = $module_libraries;
4925
  }
4926
  if (isset($name)) {
4927
    if (!isset($libraries[$module][$name])) {
4928
      $libraries[$module][$name] = FALSE;
4929
    }
4930
    return $libraries[$module][$name];
4931
  }
4932
  return $libraries[$module];
4933
}
4934

    
4935
/**
4936
 * Assists in adding the tableDrag JavaScript behavior to a themed table.
4937
 *
4938
 * Draggable tables should be used wherever an outline or list of sortable items
4939
 * needs to be arranged by an end-user. Draggable tables are very flexible and
4940
 * can manipulate the value of form elements placed within individual columns.
4941
 *
4942
 * To set up a table to use drag and drop in place of weight select-lists or in
4943
 * place of a form that contains parent relationships, the form must be themed
4944
 * into a table. The table must have an ID attribute set. If using
4945
 * theme_table(), the ID may be set as follows:
4946
 * @code
4947
 * $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'my-module-table')));
4948
 * return $output;
4949
 * @endcode
4950
 *
4951
 * In the theme function for the form, a special class must be added to each
4952
 * form element within the same column, "grouping" them together.
4953
 *
4954
 * In a situation where a single weight column is being sorted in the table, the
4955
 * classes could be added like this (in the theme function):
4956
 * @code
4957
 * $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
4958
 * @endcode
4959
 *
4960
 * Each row of the table must also have a class of "draggable" in order to
4961
 * enable the drag handles:
4962
 * @code
4963
 * $row = array(...);
4964
 * $rows[] = array(
4965
 *   'data' => $row,
4966
 *   'class' => array('draggable'),
4967
 * );
4968
 * @endcode
4969
 *
4970
 * When tree relationships are present, the two additional classes
4971
 * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
4972
 * - Rows with the 'tabledrag-leaf' class cannot have child rows.
4973
 * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
4974
 *
4975
 * Calling drupal_add_tabledrag() would then be written as such:
4976
 * @code
4977
 * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
4978
 * @endcode
4979
 *
4980
 * In a more complex case where there are several groups in one column (such as
4981
 * the block regions on the admin/structure/block page), a separate subgroup
4982
 * class must also be added to differentiate the groups.
4983
 * @code
4984
 * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
4985
 * @endcode
4986
 *
4987
 * $group is still 'my-element-weight', and the additional $subgroup variable
4988
 * will be passed in as 'my-elements-weight-' . $region. This also means that
4989
 * you'll need to call drupal_add_tabledrag() once for every region added.
4990
 *
4991
 * @code
4992
 * foreach ($regions as $region) {
4993
 *   drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight', 'my-elements-weight-' . $region);
4994
 * }
4995
 * @endcode
4996
 *
4997
 * In a situation where tree relationships are present, adding multiple
4998
 * subgroups is not necessary, because the table will contain indentations that
4999
 * provide enough information about the sibling and parent relationships. See
5000
 * theme_menu_overview_form() for an example creating a table containing parent
5001
 * relationships.
5002
 *
5003
 * Note that this function should be called from the theme layer, such as in a
5004
 * .tpl.php file, theme_ function, or in a template_preprocess function, not in
5005
 * a form declaration. Though the same JavaScript could be added to the page
5006
 * using drupal_add_js() directly, this function helps keep template files
5007
 * clean and readable. It also prevents tabledrag.js from being added twice
5008
 * accidentally.
5009
 *
5010
 * @param $table_id
5011
 *   String containing the target table's id attribute. If the table does not
5012
 *   have an id, one will need to be set, such as <table id="my-module-table">.
5013
 * @param $action
5014
 *   String describing the action to be done on the form item. Either 'match'
5015
 *   'depth', or 'order'. Match is typically used for parent relationships.
5016
 *   Order is typically used to set weights on other form elements with the same
5017
 *   group. Depth updates the target element with the current indentation.
5018
 * @param $relationship
5019
 *   String describing where the $action variable should be performed. Either
5020
 *   'parent', 'sibling', 'group', or 'self'. Parent will only look for fields
5021
 *   up the tree. Sibling will look for fields in the same group in rows above
5022
 *   and below it. Self affects the dragged row itself. Group affects the
5023
 *   dragged row, plus any children below it (the entire dragged group).
5024
 * @param $group
5025
 *   A class name applied on all related form elements for this action.
5026
 * @param $subgroup
5027
 *   (optional) If the group has several subgroups within it, this string should
5028
 *   contain the class name identifying fields in the same subgroup.
5029
 * @param $source
5030
 *   (optional) If the $action is 'match', this string should contain the class
5031
 *   name identifying what field will be used as the source value when matching
5032
 *   the value in $subgroup.
5033
 * @param $hidden
5034
 *   (optional) The column containing the field elements may be entirely hidden
5035
 *   from view dynamically when the JavaScript is loaded. Set to FALSE if the
5036
 *   column should not be hidden.
5037
 * @param $limit
5038
 *   (optional) Limit the maximum amount of parenting in this table.
5039
 * @see block-admin-display-form.tpl.php
5040
 * @see theme_menu_overview_form()
5041
 */
5042
function drupal_add_tabledrag($table_id, $action, $relationship, $group, $subgroup = NULL, $source = NULL, $hidden = TRUE, $limit = 0) {
5043
  $js_added = &drupal_static(__FUNCTION__, FALSE);
5044
  if (!$js_added) {
5045
    // Add the table drag JavaScript to the page before the module JavaScript
5046
    // to ensure that table drag behaviors are registered before any module
5047
    // uses it.
5048
    drupal_add_library('system', 'jquery.cookie');
5049
    drupal_add_js('misc/tabledrag.js', array('weight' => -1));
5050
    $js_added = TRUE;
5051
  }
5052

    
5053
  // If a subgroup or source isn't set, assume it is the same as the group.
5054
  $target = isset($subgroup) ? $subgroup : $group;
5055
  $source = isset($source) ? $source : $target;
5056
  $settings['tableDrag'][$table_id][$group][] = array(
5057
    'target' => $target,
5058
    'source' => $source,
5059
    'relationship' => $relationship,
5060
    'action' => $action,
5061
    'hidden' => $hidden,
5062
    'limit' => $limit,
5063
  );
5064
  drupal_add_js($settings, 'setting');
5065
}
5066

    
5067
/**
5068
 * Aggregates JavaScript files into a cache file in the files directory.
5069
 *
5070
 * The file name for the JavaScript cache file is generated from the hash of
5071
 * the aggregated contents of the files in $files. This forces proxies and
5072
 * browsers to download new JavaScript when the JavaScript changes.
5073
 *
5074
 * The cache file name is retrieved on a page load via a lookup variable that
5075
 * contains an associative array. The array key is the hash of the names in
5076
 * $files while the value is the cache file name. The cache file is generated
5077
 * in two cases. First, if there is no file name value for the key, which will
5078
 * happen if a new file name has been added to $files or after the lookup
5079
 * variable is emptied to force a rebuild of the cache. Second, the cache file
5080
 * is generated if it is missing on disk. Old cache files are not deleted
5081
 * immediately when the lookup variable is emptied, but are deleted after a set
5082
 * period by drupal_delete_file_if_stale(). This ensures that files referenced
5083
 * by a cached page will still be available.
5084
 *
5085
 * @param $files
5086
 *   An array of JavaScript files to aggregate and compress into one file.
5087
 *
5088
 * @return
5089
 *   The URI of the cache file, or FALSE if the file could not be saved.
5090
 */
5091
function drupal_build_js_cache($files) {
5092
  $contents = '';
5093
  $uri = '';
5094
  $map = variable_get('drupal_js_cache_files', array());
5095
  // Create a new array so that only the file names are used to create the hash.
5096
  // This prevents new aggregates from being created unnecessarily.
5097
  $js_data = array();
5098
  foreach ($files as $file) {
5099
    $js_data[] = $file['data'];
5100
  }
5101
  $key = hash('sha256', serialize($js_data));
5102
  if (isset($map[$key])) {
5103
    $uri = $map[$key];
5104
  }
5105

    
5106
  if (empty($uri) || !file_exists($uri)) {
5107
    // Build aggregate JS file.
5108
    foreach ($files as $path => $info) {
5109
      if ($info['preprocess']) {
5110
        // Append a ';' and a newline after each JS file to prevent them from running together.
5111
        $contents .= file_get_contents($path) . ";\n";
5112
      }
5113
    }
5114
    // Prefix filename to prevent blocking by firewalls which reject files
5115
    // starting with "ad*".
5116
    $filename = 'js_' . drupal_hash_base64($contents) . '.js';
5117
    // Create the js/ within the files folder.
5118
    $jspath = 'public://js';
5119
    $uri = $jspath . '/' . $filename;
5120
    // Create the JS file.
5121
    file_prepare_directory($jspath, FILE_CREATE_DIRECTORY);
5122
    if (!file_exists($uri) && !file_unmanaged_save_data($contents, $uri, FILE_EXISTS_REPLACE)) {
5123
      return FALSE;
5124
    }
5125
    // If JS gzip compression is enabled, clean URLs are enabled (which means
5126
    // that rewrite rules are working) and the zlib extension is available then
5127
    // create a gzipped version of this file. This file is served conditionally
5128
    // to browsers that accept gzip using .htaccess rules.
5129
    if (variable_get('js_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
5130
      if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($contents, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
5131
        return FALSE;
5132
      }
5133
    }
5134
    $map[$key] = $uri;
5135
    variable_set('drupal_js_cache_files', $map);
5136
  }
5137
  return $uri;
5138
}
5139

    
5140
/**
5141
 * Deletes old cached JavaScript files and variables.
5142
 */
5143
function drupal_clear_js_cache() {
5144
  variable_del('javascript_parsed');
5145
  variable_del('drupal_js_cache_files');
5146
  file_scan_directory('public://js', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
5147
}
5148

    
5149
/**
5150
 * Converts a PHP variable into its JavaScript equivalent.
5151
 *
5152
 * We use HTML-safe strings, with several characters escaped.
5153
 *
5154
 * @see drupal_json_decode()
5155
 * @see drupal_json_encode_helper()
5156
 * @ingroup php_wrappers
5157
 */
5158
function drupal_json_encode($var) {
5159
  // The PHP version cannot change within a request.
5160
  static $php530;
5161

    
5162
  if (!isset($php530)) {
5163
    $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
5164
  }
5165

    
5166
  if ($php530) {
5167
    // Encode <, >, ', &, and " using the json_encode() options parameter.
5168
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
5169
  }
5170

    
5171
  // json_encode() escapes <, >, ', &, and " using its options parameter, but
5172
  // does not support this parameter prior to PHP 5.3.0.  Use a helper instead.
5173
  include_once DRUPAL_ROOT . '/includes/json-encode.inc';
5174
  return drupal_json_encode_helper($var);
5175
}
5176

    
5177
/**
5178
 * Converts an HTML-safe JSON string into its PHP equivalent.
5179
 *
5180
 * @see drupal_json_encode()
5181
 * @ingroup php_wrappers
5182
 */
5183
function drupal_json_decode($var) {
5184
  return json_decode($var, TRUE);
5185
}
5186

    
5187
/**
5188
 * Returns data in JSON format.
5189
 *
5190
 * This function should be used for JavaScript callback functions returning
5191
 * data in JSON format. It sets the header for JavaScript output.
5192
 *
5193
 * @param $var
5194
 *   (optional) If set, the variable will be converted to JSON and output.
5195
 */
5196
function drupal_json_output($var = NULL) {
5197
  // We are returning JSON, so tell the browser.
5198
  drupal_add_http_header('Content-Type', 'application/json');
5199

    
5200
  if (isset($var)) {
5201
    echo drupal_json_encode($var);
5202
  }
5203
}
5204

    
5205
/**
5206
 * Ensures the private key variable used to generate tokens is set.
5207
 *
5208
 * @return
5209
 *   The private key.
5210
 */
5211
function drupal_get_private_key() {
5212
  if (!($key = variable_get('drupal_private_key', 0))) {
5213
    $key = drupal_random_key();
5214
    variable_set('drupal_private_key', $key);
5215
  }
5216
  return $key;
5217
}
5218

    
5219
/**
5220
 * Generates a token based on $value, the user session, and the private key.
5221
 *
5222
 * @param $value
5223
 *   An additional value to base the token on.
5224
 *
5225
 * The generated token is based on the session ID of the current user. Normally,
5226
 * anonymous users do not have a session, so the generated token will be
5227
 * different on every page request. To generate a token for users without a
5228
 * session, manually start a session prior to calling this function.
5229
 *
5230
 * @return string
5231
 *   A 43-character URL-safe token for validation, based on the user session ID,
5232
 *   the hash salt provided from drupal_get_hash_salt(), and the
5233
 *   'drupal_private_key' configuration variable.
5234
 *
5235
 * @see drupal_get_hash_salt()
5236
 */
5237
function drupal_get_token($value = '') {
5238
  return drupal_hmac_base64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());
5239
}
5240

    
5241
/**
5242
 * Validates a token based on $value, the user session, and the private key.
5243
 *
5244
 * @param $token
5245
 *   The token to be validated.
5246
 * @param $value
5247
 *   An additional value to base the token on.
5248
 * @param $skip_anonymous
5249
 *   Set to true to skip token validation for anonymous users.
5250
 *
5251
 * @return
5252
 *   True for a valid token, false for an invalid token. When $skip_anonymous
5253
 *   is true, the return value will always be true for anonymous users.
5254
 */
5255
function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
5256
  global $user;
5257
  return (($skip_anonymous && $user->uid == 0) || ($token === drupal_get_token($value)));
5258
}
5259

    
5260
function _drupal_bootstrap_full() {
5261
  static $called = FALSE;
5262

    
5263
  if ($called) {
5264
    return;
5265
  }
5266
  $called = TRUE;
5267
  require_once DRUPAL_ROOT . '/' . variable_get('path_inc', 'includes/path.inc');
5268
  require_once DRUPAL_ROOT . '/includes/theme.inc';
5269
  require_once DRUPAL_ROOT . '/includes/pager.inc';
5270
  require_once DRUPAL_ROOT . '/' . variable_get('menu_inc', 'includes/menu.inc');
5271
  require_once DRUPAL_ROOT . '/includes/tablesort.inc';
5272
  require_once DRUPAL_ROOT . '/includes/file.inc';
5273
  require_once DRUPAL_ROOT . '/includes/unicode.inc';
5274
  require_once DRUPAL_ROOT . '/includes/image.inc';
5275
  require_once DRUPAL_ROOT . '/includes/form.inc';
5276
  require_once DRUPAL_ROOT . '/includes/mail.inc';
5277
  require_once DRUPAL_ROOT . '/includes/actions.inc';
5278
  require_once DRUPAL_ROOT . '/includes/ajax.inc';
5279
  require_once DRUPAL_ROOT . '/includes/token.inc';
5280
  require_once DRUPAL_ROOT . '/includes/errors.inc';
5281

    
5282
  // Detect string handling method
5283
  unicode_check();
5284
  // Undo magic quotes
5285
  fix_gpc_magic();
5286
  // Load all enabled modules
5287
  module_load_all();
5288
  // Reset drupal_alter() and module_implements() static caches as these
5289
  // include implementations for vital modules only when called early on
5290
  // in the bootstrap.
5291
  drupal_static_reset('drupal_alter');
5292
  drupal_static_reset('module_implements');
5293
  // Make sure all stream wrappers are registered.
5294
  file_get_stream_wrappers();
5295
  // Ensure mt_rand is reseeded, to prevent random values from one page load
5296
  // being exploited to predict random values in subsequent page loads.
5297
  $seed = unpack("L", drupal_random_bytes(4));
5298
  mt_srand($seed[1]);
5299

    
5300
  $test_info = &$GLOBALS['drupal_test_info'];
5301
  if (!empty($test_info['in_child_site'])) {
5302
    // Running inside the simpletest child site, log fatal errors to test
5303
    // specific file directory.
5304
    ini_set('log_errors', 1);
5305
    ini_set('error_log', 'public://error.log');
5306
  }
5307

    
5308
  // Initialize $_GET['q'] prior to invoking hook_init().
5309
  drupal_path_initialize();
5310

    
5311
  // Let all modules take action before the menu system handles the request.
5312
  // We do not want this while running update.php.
5313
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
5314
    // Prior to invoking hook_init(), initialize the theme (potentially a custom
5315
    // one for this page), so that:
5316
    // - Modules with hook_init() implementations that call theme() or
5317
    //   theme_get_registry() don't initialize the incorrect theme.
5318
    // - The theme can have hook_*_alter() implementations affect page building
5319
    //   (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
5320
    //   ahead of when rendering starts.
5321
    menu_set_custom_theme();
5322
    drupal_theme_initialize();
5323
    module_invoke_all('init');
5324
  }
5325
}
5326

    
5327
/**
5328
 * Stores the current page in the cache.
5329
 *
5330
 * If page_compression is enabled, a gzipped version of the page is stored in
5331
 * the cache to avoid compressing the output on each request. The cache entry
5332
 * is unzipped in the relatively rare event that the page is requested by a
5333
 * client without gzip support.
5334
 *
5335
 * Page compression requires the PHP zlib extension
5336
 * (http://php.net/manual/ref.zlib.php).
5337
 *
5338
 * @see drupal_page_header()
5339
 */
5340
function drupal_page_set_cache() {
5341
  global $base_root;
5342

    
5343
  if (drupal_page_is_cacheable()) {
5344

    
5345
    // Check whether the current page might be compressed.
5346
    $page_compressed = variable_get('page_compression', TRUE) && extension_loaded('zlib');
5347

    
5348
    $cache = (object) array(
5349
      'cid' => $base_root . request_uri(),
5350
      'data' => array(
5351
        'path' => $_GET['q'],
5352
        'body' => ob_get_clean(),
5353
        'title' => drupal_get_title(),
5354
        'headers' => array(),
5355
        // We need to store whether page was compressed or not,
5356
        // because by the time it is read, the configuration might change.
5357
        'page_compressed' => $page_compressed,
5358
      ),
5359
      'expire' => CACHE_TEMPORARY,
5360
      'created' => REQUEST_TIME,
5361
    );
5362

    
5363
    // Restore preferred header names based on the lower-case names returned
5364
    // by drupal_get_http_header().
5365
    $header_names = _drupal_set_preferred_header_name();
5366
    foreach (drupal_get_http_header() as $name_lower => $value) {
5367
      $cache->data['headers'][$header_names[$name_lower]] = $value;
5368
      if ($name_lower == 'expires') {
5369
        // Use the actual timestamp from an Expires header if available.
5370
        $cache->expire = strtotime($value);
5371
      }
5372
    }
5373

    
5374
    if ($cache->data['body']) {
5375
      if ($page_compressed) {
5376
        $cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
5377
      }
5378
      cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire);
5379
    }
5380
    return $cache;
5381
  }
5382
}
5383

    
5384
/**
5385
 * Executes a cron run when called.
5386
 *
5387
 * Do not call this function from a test. Use $this->cronRun() instead.
5388
 *
5389
 * @return bool
5390
 *   TRUE if cron ran successfully and FALSE if cron is already running.
5391
 */
5392
function drupal_cron_run() {
5393
  // Allow execution to continue even if the request gets canceled.
5394
  @ignore_user_abort(TRUE);
5395

    
5396
  // Prevent session information from being saved while cron is running.
5397
  $original_session_saving = drupal_save_session();
5398
  drupal_save_session(FALSE);
5399

    
5400
  // Force the current user to anonymous to ensure consistent permissions on
5401
  // cron runs.
5402
  $original_user = $GLOBALS['user'];
5403
  $GLOBALS['user'] = drupal_anonymous_user();
5404

    
5405
  // Try to allocate enough time to run all the hook_cron implementations.
5406
  drupal_set_time_limit(240);
5407

    
5408
  $return = FALSE;
5409
  // Grab the defined cron queues.
5410
  $queues = module_invoke_all('cron_queue_info');
5411
  drupal_alter('cron_queue_info', $queues);
5412

    
5413
  // Try to acquire cron lock.
5414
  if (!lock_acquire('cron', 240.0)) {
5415
    // Cron is still running normally.
5416
    watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
5417
  }
5418
  else {
5419
    // Make sure every queue exists. There is no harm in trying to recreate an
5420
    // existing queue.
5421
    foreach ($queues as $queue_name => $info) {
5422
      DrupalQueue::get($queue_name)->createQueue();
5423
    }
5424

    
5425
    // Iterate through the modules calling their cron handlers (if any):
5426
    foreach (module_implements('cron') as $module) {
5427
      // Do not let an exception thrown by one module disturb another.
5428
      try {
5429
        module_invoke($module, 'cron');
5430
      }
5431
      catch (Exception $e) {
5432
        watchdog_exception('cron', $e);
5433
      }
5434
    }
5435

    
5436
    // Record cron time.
5437
    variable_set('cron_last', REQUEST_TIME);
5438
    watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
5439

    
5440
    // Release cron lock.
5441
    lock_release('cron');
5442

    
5443
    // Return TRUE so other functions can check if it did run successfully
5444
    $return = TRUE;
5445
  }
5446

    
5447
  foreach ($queues as $queue_name => $info) {
5448
    if (!empty($info['skip on cron'])) {
5449
      // Do not run if queue wants to skip.
5450
      continue;
5451
    }
5452
    $callback = $info['worker callback'];
5453
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
5454
    $queue = DrupalQueue::get($queue_name);
5455
    while (time() < $end && ($item = $queue->claimItem())) {
5456
      try {
5457
        call_user_func($callback, $item->data);
5458
        $queue->deleteItem($item);
5459
      }
5460
      catch (Exception $e) {