Project

General

Profile

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

root / drupal7 / includes / common.inc @ b0dc3a2e

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.
615
  if (isset($options['query']['q'])) {
616
    $options['path'] = $options['query']['q'];
617
    unset($options['query']['q']);
618
  }
619

    
620
  return $options;
621
}
622

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

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

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

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

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

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

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

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

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

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

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

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

    
800
  $result = new stdClass();
801

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

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

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

    
817
  timer_start(__FUNCTION__);
818

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

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

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

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

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

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

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

    
883
    case 'https':
884
      // Note: Only works when PHP is compiled with OpenSSL support.
885
      $port = isset($uri['port']) ? $uri['port'] : 443;
886
      $socket = 'ssl://' . $uri['host'] . ':' . $port;
887
      $options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
888
      break;
889

    
890
    default:
891
      $result->error = 'invalid schema ' . $uri['scheme'];
892
      $result->code = -1003;
893
      return $result;
894
  }
895

    
896
  if (empty($options['context'])) {
897
    $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout']);
898
  }
899
  else {
900
    // Create a stream with context. Allows verification of a SSL certificate.
901
    $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
902
  }
903

    
904
  // Make sure the socket opened properly.
905
  if (!$fp) {
906
    // When a network error occurs, we use a negative number so it does not
907
    // clash with the HTTP status codes.
908
    $result->code = -$errno;
909
    $result->error = trim($errstr) ? trim($errstr) : t('Error opening socket @socket', array('@socket' => $socket));
910

    
911
    // Mark that this request failed. This will trigger a check of the web
912
    // server's ability to make outgoing HTTP requests the next time that
913
    // requirements checking is performed.
914
    // See system_requirements().
915
    variable_set('drupal_http_request_fails', TRUE);
916

    
917
    return $result;
918
  }
919

    
920
  // Construct the path to act on.
921
  $path = isset($uri['path']) ? $uri['path'] : '/';
922
  if (isset($uri['query'])) {
923
    $path .= '?' . $uri['query'];
924
  }
925

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

    
935
  // If the server URL has a user then attempt to use basic authentication.
936
  if (isset($uri['user'])) {
937
    $options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ':'));
938
  }
939

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

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

    
964
  // Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
965
  // and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
966
  // instead must invoke stream_get_meta_data() each iteration.
967
  $info = stream_get_meta_data($fp);
968
  $alive = !$info['eof'] && !$info['timed_out'];
969
  $response = '';
970

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

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

    
997
  // Parse the response status line.
998
  $response_status_array = _drupal_parse_response_status(trim(array_shift($response)));
999
  $result->protocol = $response_status_array['http_version'];
1000
  $result->status_message = $response_status_array['reason_phrase'];
1001
  $code = $response_status_array['response_code'];
1002

    
1003
  $result->headers = array();
1004

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

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

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

    
1101
  return $result;
1102
}
1103

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

    
1135
/**
1136
 * Helper function for determining hosts excluded from needing a proxy.
1137
 *
1138
 * @return
1139
 *   TRUE if a proxy should be used for this host.
1140
 */
1141
function _drupal_http_use_proxy($host) {
1142
  $proxy_exceptions = variable_get('proxy_exceptions', array('localhost', '127.0.0.1'));
1143
  return !in_array(strtolower($host), $proxy_exceptions, TRUE);
1144
}
1145

    
1146
/**
1147
 * @} End of "HTTP handling".
1148
 */
1149

    
1150
/**
1151
 * Strips slashes from a string or array of strings.
1152
 *
1153
 * Callback for array_walk() within fix_gpx_magic().
1154
 *
1155
 * @param $item
1156
 *   An individual string or array of strings from superglobals.
1157
 */
1158
function _fix_gpc_magic(&$item) {
1159
  if (is_array($item)) {
1160
    array_walk($item, '_fix_gpc_magic');
1161
  }
1162
  else {
1163
    $item = stripslashes($item);
1164
  }
1165
}
1166

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

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

    
1211
/**
1212
 * @defgroup validation Input validation
1213
 * @{
1214
 * Functions to validate user input.
1215
 */
1216

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

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

    
1271
/**
1272
 * @} End of "defgroup validation".
1273
 */
1274

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

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

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

    
1353
/**
1354
 * @defgroup sanitization Sanitization functions
1355
 * @{
1356
 * Functions to sanitize values.
1357
 *
1358
 * See http://drupal.org/writing-secure-code for information
1359
 * on writing secure code.
1360
 */
1361

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

    
1386
  if (!isset($allowed_protocols)) {
1387
    $allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal')));
1388
  }
1389

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

    
1411
  return $uri;
1412
}
1413

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

    
1434
/**
1435
 * Applies a very permissive XSS/HTML filter for admin-only use.
1436
 *
1437
 * Use only for fields where it is impractical to use the
1438
 * whole filter system, but where some (mainly inline) mark-up
1439
 * is desired (so check_plain() is not acceptable).
1440
 *
1441
 * Allows all tags that can be used inside an HTML body, save
1442
 * for scripts and styles.
1443
 */
1444
function filter_xss_admin($string) {
1445
  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'));
1446
}
1447

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

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

    
1496
  return preg_replace_callback('%
1497
    (
1498
    <(?=[^a-zA-Z!/])  # a lone <
1499
    |                 # or
1500
    <!--.*?-->        # a comment
1501
    |                 # or
1502
    <[^>]*(>|$)       # a string that starts with a <, up until the > or the end of the string
1503
    |                 # or
1504
    >                 # just a >
1505
    )%x', '_filter_xss_split', $string);
1506
}
1507

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

    
1525
  if ($store) {
1526
    $allowed_html = array_flip($m);
1527
    return;
1528
  }
1529

    
1530
  $string = $m[1];
1531

    
1532
  if (substr($string, 0, 1) != '<') {
1533
    // We matched a lone ">" character.
1534
    return '&gt;';
1535
  }
1536
  elseif (strlen($string) == 1) {
1537
    // We matched a lone "<" character.
1538
    return '&lt;';
1539
  }
1540

    
1541
  if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9\-]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
1542
    // Seriously malformed.
1543
    return '';
1544
  }
1545

    
1546
  $slash = trim($matches[1]);
1547
  $elem = &$matches[2];
1548
  $attrlist = &$matches[3];
1549
  $comment = &$matches[4];
1550

    
1551
  if ($comment) {
1552
    $elem = '!--';
1553
  }
1554

    
1555
  if (!isset($allowed_html[strtolower($elem)])) {
1556
    // Disallowed HTML element.
1557
    return '';
1558
  }
1559

    
1560
  if ($comment) {
1561
    return $comment;
1562
  }
1563

    
1564
  if ($slash != '') {
1565
    return "</$elem>";
1566
  }
1567

    
1568
  // Is there a closing XHTML slash at the end of the attributes?
1569
  $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
1570
  $xhtml_slash = $count ? ' /' : '';
1571

    
1572
  // Clean up attributes.
1573
  $attr2 = implode(' ', _filter_xss_attributes($attrlist));
1574
  $attr2 = preg_replace('/[<>]/', '', $attr2);
1575
  $attr2 = strlen($attr2) ? ' ' . $attr2 : '';
1576

    
1577
  return "<$elem$attr2$xhtml_slash>";
1578
}
1579

    
1580
/**
1581
 * Processes a string of HTML attributes.
1582
 *
1583
 * @return
1584
 *   Cleaned up version of the HTML attributes.
1585
 */
1586
function _filter_xss_attributes($attr) {
1587
  $attrarr = array();
1588
  $mode = 0;
1589
  $attrname = '';
1590

    
1591
  while (strlen($attr) != 0) {
1592
    // Was the last operation successful?
1593
    $working = 0;
1594

    
1595
    switch ($mode) {
1596
      case 0:
1597
        // Attribute name, href for instance.
1598
        if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
1599
          $attrname = strtolower($match[1]);
1600
          $skip = ($attrname == 'style' || substr($attrname, 0, 2) == 'on');
1601
          $working = $mode = 1;
1602
          $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
1603
        }
1604
        break;
1605

    
1606
      case 1:
1607
        // Equals sign or valueless ("selected").
1608
        if (preg_match('/^\s*=\s*/', $attr)) {
1609
          $working = 1; $mode = 2;
1610
          $attr = preg_replace('/^\s*=\s*/', '', $attr);
1611
          break;
1612
        }
1613

    
1614
        if (preg_match('/^\s+/', $attr)) {
1615
          $working = 1; $mode = 0;
1616
          if (!$skip) {
1617
            $attrarr[] = $attrname;
1618
          }
1619
          $attr = preg_replace('/^\s+/', '', $attr);
1620
        }
1621
        break;
1622

    
1623
      case 2:
1624
        // Attribute value, a URL after href= for instance.
1625
        if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
1626
          $thisval = filter_xss_bad_protocol($match[1]);
1627

    
1628
          if (!$skip) {
1629
            $attrarr[] = "$attrname=\"$thisval\"";
1630
          }
1631
          $working = 1;
1632
          $mode = 0;
1633
          $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
1634
          break;
1635
        }
1636

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

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

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

    
1651
          if (!$skip) {
1652
            $attrarr[] = "$attrname=\"$thisval\"";
1653
          }
1654
          $working = 1; $mode = 0;
1655
          $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
1656
        }
1657
        break;
1658
    }
1659

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

    
1677
  // The attribute list ends with a valueless attribute like "selected".
1678
  if ($mode == 1 && !$skip) {
1679
    $attrarr[] = $attrname;
1680
  }
1681
  return $attrarr;
1682
}
1683

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

    
1707
    $string = decode_entities($string);
1708
  }
1709
  return check_plain(drupal_strip_dangerous_protocols($string));
1710
}
1711

    
1712
/**
1713
 * @} End of "defgroup sanitization".
1714
 */
1715

    
1716
/**
1717
 * @defgroup format Formatting
1718
 * @{
1719
 * Functions to format numbers, strings, dates, etc.
1720
 */
1721

    
1722
/**
1723
 * Formats an RSS channel.
1724
 *
1725
 * Arbitrary elements may be added using the $args associative array.
1726
 */
1727
function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
1728
  global $language_content;
1729
  $langcode = $langcode ? $langcode : $language_content->language;
1730

    
1731
  $output = "<channel>\n";
1732
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1733
  $output .= ' <link>' . check_url($link) . "</link>\n";
1734

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

    
1744
  return $output;
1745
}
1746

    
1747
/**
1748
 * Formats a single RSS item.
1749
 *
1750
 * Arbitrary elements may be added using the $args associative array.
1751
 */
1752
function format_rss_item($title, $link, $description, $args = array()) {
1753
  $output = "<item>\n";
1754
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1755
  $output .= ' <link>' . check_url($link) . "</link>\n";
1756
  $output .= ' <description>' . check_plain($description) . "</description>\n";
1757
  $output .= format_xml_elements($args);
1758
  $output .= "</item>\n";
1759

    
1760
  return $output;
1761
}
1762

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

    
1793
        if (isset($value['value']) && $value['value'] != '') {
1794
          $output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : (!empty($value['encoded']) ? $value['value'] : check_plain($value['value']))) . '</' . $value['key'] . ">\n";
1795
        }
1796
        else {
1797
          $output .= " />\n";
1798
        }
1799
      }
1800
    }
1801
    else {
1802
      $output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</$key>\n";
1803
    }
1804
  }
1805
  return $output;
1806
}
1807

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

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

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

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

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

    
1975
    if ($granularity == 0) {
1976
      break;
1977
    }
1978
  }
1979
  return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
1980
}
1981

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

    
2018
  if (!isset($timezone)) {
2019
    $timezone = date_default_timezone_get();
2020
  }
2021
  // Store DateTimeZone objects in an array rather than repeatedly
2022
  // constructing identical objects over the life of a request.
2023
  if (!isset($timezones[$timezone])) {
2024
    $timezones[$timezone] = timezone_open($timezone);
2025
  }
2026

    
2027
  // Use the default langcode if none is set.
2028
  global $language;
2029
  if (empty($langcode)) {
2030
    $langcode = isset($language->language) ? $language->language : 'en';
2031
  }
2032

    
2033
  switch ($type) {
2034
    case 'short':
2035
      $format = variable_get('date_format_short', 'm/d/Y - H:i');
2036
      break;
2037

    
2038
    case 'long':
2039
      $format = variable_get('date_format_long', 'l, F j, Y - H:i');
2040
      break;
2041

    
2042
    case 'custom':
2043
      // No change to format.
2044
      break;
2045

    
2046
    case 'medium':
2047
    default:
2048
      // Retrieve the format of the custom $type passed.
2049
      if ($type != 'medium') {
2050
        $format = variable_get('date_format_' . $type, '');
2051
      }
2052
      // Fall back to 'medium'.
2053
      if ($format === '') {
2054
        $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
2055
      }
2056
      break;
2057
  }
2058

    
2059
  // Create a DateTime object from the timestamp.
2060
  $date_time = date_create('@' . $timestamp);
2061
  // Set the time zone for the DateTime object.
2062
  date_timezone_set($date_time, $timezones[$timezone]);
2063

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

    
2071
  // Call date_format().
2072
  $format = date_format($date_time, $format);
2073

    
2074
  // Pass the langcode to _format_date_callback().
2075
  _format_date_callback(NULL, $langcode);
2076

    
2077
  // Translate the marked sequences.
2078
  return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);
2079
}
2080

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

    
2098
/**
2099
 * Translates a formatted date string.
2100
 *
2101
 * Callback for preg_replace_callback() within format_date().
2102
 */
2103
function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
2104
  // We cache translations to avoid redundant and rather costly calls to t().
2105
  static $cache, $langcode;
2106

    
2107
  if (!isset($matches)) {
2108
    $langcode = $new_langcode;
2109
    return;
2110
  }
2111

    
2112
  $code = $matches[1];
2113
  $string = $matches[2];
2114

    
2115
  if (!isset($cache[$langcode][$code][$string])) {
2116
    $options = array(
2117
      'langcode' => $langcode,
2118
    );
2119

    
2120
    if ($code == 'F') {
2121
      $options['context'] = 'Long month name';
2122
    }
2123

    
2124
    if ($code == '') {
2125
      $cache[$langcode][$code][$string] = $string;
2126
    }
2127
    else {
2128
      $cache[$langcode][$code][$string] = t($string, array(), $options);
2129
    }
2130
  }
2131
  return $cache[$langcode][$code][$string];
2132
}
2133

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

    
2160
/**
2161
 * @} End of "defgroup format".
2162
 */
2163

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

    
2239
  if (!isset($options['external'])) {
2240
    $options['external'] = url_is_external($path);
2241
  }
2242

    
2243
  // Preserve the original path before altering or aliasing.
2244
  $original_path = $path;
2245

    
2246
  // Allow other modules to alter the outbound URL and options.
2247
  drupal_alter('url_outbound', $path, $options, $original_path);
2248

    
2249
  if (isset($options['fragment']) && $options['fragment'] !== '') {
2250
    $options['fragment'] = '#' . $options['fragment'];
2251
  }
2252

    
2253
  if ($options['external']) {
2254
    // Split off the fragment.
2255
    if (strpos($path, '#') !== FALSE) {
2256
      list($path, $old_fragment) = explode('#', $path, 2);
2257
      // If $options contains no fragment, take it over from the path.
2258
      if (isset($old_fragment) && !$options['fragment']) {
2259
        $options['fragment'] = '#' . $old_fragment;
2260
      }
2261
    }
2262
    // Append the query.
2263
    if ($options['query']) {
2264
      $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($options['query']);
2265
    }
2266
    if (isset($options['https']) && variable_get('https', FALSE)) {
2267
      if ($options['https'] === TRUE) {
2268
        $path = str_replace('http://', 'https://', $path);
2269
      }
2270
      elseif ($options['https'] === FALSE) {
2271
        $path = str_replace('https://', 'http://', $path);
2272
      }
2273
    }
2274
    // Reassemble.
2275
    return $path . $options['fragment'];
2276
  }
2277

    
2278
  // Strip leading slashes from internal paths to prevent them becoming external
2279
  // URLs without protocol. /example.com should not be turned into
2280
  // //example.com.
2281
  $path = ltrim($path, '/');
2282

    
2283
  global $base_url, $base_secure_url, $base_insecure_url;
2284

    
2285
  // The base_url might be rewritten from the language rewrite in domain mode.
2286
  if (!isset($options['base_url'])) {
2287
    if (isset($options['https']) && variable_get('https', FALSE)) {
2288
      if ($options['https'] === TRUE) {
2289
        $options['base_url'] = $base_secure_url;
2290
        $options['absolute'] = TRUE;
2291
      }
2292
      elseif ($options['https'] === FALSE) {
2293
        $options['base_url'] = $base_insecure_url;
2294
        $options['absolute'] = TRUE;
2295
      }
2296
    }
2297
    else {
2298
      $options['base_url'] = $base_url;
2299
    }
2300
  }
2301

    
2302
  // The special path '<front>' links to the default front page.
2303
  if ($path == '<front>') {
2304
    $path = '';
2305
  }
2306
  elseif (!empty($path) && !$options['alias']) {
2307
    $language = isset($options['language']) && isset($options['language']->language) ? $options['language']->language : '';
2308
    $alias = drupal_get_path_alias($original_path, $language);
2309
    if ($alias != $original_path) {
2310
      $path = $alias;
2311
    }
2312
  }
2313

    
2314
  $base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
2315
  $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
2316

    
2317
  // With Clean URLs.
2318
  if (!empty($GLOBALS['conf']['clean_url'])) {
2319
    $path = drupal_encode_path($prefix . $path);
2320
    if ($options['query']) {
2321
      return $base . $path . '?' . drupal_http_build_query($options['query']) . $options['fragment'];
2322
    }
2323
    else {
2324
      return $base . $path . $options['fragment'];
2325
    }
2326
  }
2327
  // Without Clean URLs.
2328
  else {
2329
    $path = $prefix . $path;
2330
    $query = array();
2331
    if (!empty($path)) {
2332
      $query['q'] = $path;
2333
    }
2334
    if ($options['query']) {
2335
      // We do not use array_merge() here to prevent overriding $path via query
2336
      // parameters.
2337
      $query += $options['query'];
2338
    }
2339
    $query = $query ? ('?' . drupal_http_build_query($query)) : '';
2340
    $script = isset($options['script']) ? $options['script'] : '';
2341
    return $base . $script . $query . $options['fragment'];
2342
  }
2343
}
2344

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

    
2377
/**
2378
 * Formats an attribute string for an HTTP header.
2379
 *
2380
 * @param $attributes
2381
 *   An associative array of attributes such as 'rel'.
2382
 *
2383
 * @return
2384
 *   A ; separated string ready for insertion in a HTTP header. No escaping is
2385
 *   performed for HTML entities, so this string is not safe to be printed.
2386
 *
2387
 * @see drupal_add_http_header()
2388
 */
2389
function drupal_http_header_attributes(array $attributes = array()) {
2390
  foreach ($attributes as $attribute => &$data) {
2391
    if (is_array($data)) {
2392
      $data = implode(' ', $data);
2393
    }
2394
    $data = $attribute . '="' . $data . '"';
2395
  }
2396
  return $attributes ? ' ' . implode('; ', $attributes) : '';
2397
}
2398

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

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

    
2494
  // Merge in defaults.
2495
  $options += array(
2496
    'attributes' => array(),
2497
    'html' => FALSE,
2498
  );
2499

    
2500
  // Append active class.
2501
  if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
2502
      (empty($options['language']) || $options['language']->language == $language_url->language)) {
2503
    $options['attributes']['class'][] = 'active';
2504
  }
2505

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

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

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

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

    
2652
  // Send appropriate HTTP-Header for browsers and search engines.
2653
  global $language;
2654
  drupal_add_http_header('Content-Language', $language->language);
2655

    
2656
  // By default, do not allow the site to be rendered in an iframe on another
2657
  // domain, but provide a variable to override this. If the code running for
2658
  // this page request already set the X-Frame-Options header earlier, don't
2659
  // overwrite it here.
2660
  $frame_options = variable_get('x_frame_options', 'SAMEORIGIN');
2661
  if ($frame_options && is_null(drupal_get_http_header('X-Frame-Options'))) {
2662
    drupal_add_http_header('X-Frame-Options', $frame_options);
2663
  }
2664

    
2665
  // Menu status constants are integers; page content is a string or array.
2666
  if (is_int($page_callback_result)) {
2667
    // @todo: Break these up into separate functions?
2668
    switch ($page_callback_result) {
2669
      case MENU_NOT_FOUND:
2670
        // Print a 404 page.
2671
        drupal_add_http_header('Status', '404 Not Found');
2672

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

    
2675
        // Check for and return a fast 404 page if configured.
2676
        drupal_fast_404();
2677

    
2678
        // Keep old path for reference, and to allow forms to redirect to it.
2679
        if (!isset($_GET['destination'])) {
2680
          // Make sure that the current path is not interpreted as external URL.
2681
          if (!url_is_external($_GET['q'])) {
2682
            $_GET['destination'] = $_GET['q'];
2683
          }
2684
        }
2685

    
2686
        $path = drupal_get_normal_path(variable_get('site_404', ''));
2687
        if ($path && $path != $_GET['q']) {
2688
          // Custom 404 handler. Set the active item in case there are tabs to
2689
          // display, or other dependencies on the path.
2690
          menu_set_active_item($path);
2691
          $return = menu_execute_active_handler($path, FALSE);
2692
        }
2693

    
2694
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2695
          // Standard 404 handler.
2696
          drupal_set_title(t('Page not found'));
2697
          $return = t('The requested page "@path" could not be found.', array('@path' => request_uri()));
2698
        }
2699

    
2700
        drupal_set_page_content($return);
2701
        $page = element_info('page');
2702
        print drupal_render_page($page);
2703
        break;
2704

    
2705
      case MENU_ACCESS_DENIED:
2706
        // Print a 403 page.
2707
        drupal_add_http_header('Status', '403 Forbidden');
2708
        watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
2709

    
2710
        // Keep old path for reference, and to allow forms to redirect to it.
2711
        if (!isset($_GET['destination'])) {
2712
          // Make sure that the current path is not interpreted as external URL.
2713
          if (!url_is_external($_GET['q'])) {
2714
            $_GET['destination'] = $_GET['q'];
2715
          }
2716
        }
2717

    
2718
        $path = drupal_get_normal_path(variable_get('site_403', ''));
2719
        if ($path && $path != $_GET['q']) {
2720
          // Custom 403 handler. Set the active item in case there are tabs to
2721
          // display or other dependencies on the path.
2722
          menu_set_active_item($path);
2723
          $return = menu_execute_active_handler($path, FALSE);
2724
        }
2725

    
2726
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2727
          // Standard 403 handler.
2728
          drupal_set_title(t('Access denied'));
2729
          $return = t('You are not authorized to access this page.');
2730
        }
2731

    
2732
        print drupal_render_page($return);
2733
        break;
2734

    
2735
      case MENU_SITE_OFFLINE:
2736
        // Print a 503 page.
2737
        drupal_maintenance_theme();
2738
        drupal_add_http_header('Status', '503 Service unavailable');
2739
        drupal_set_title(t('Site under maintenance'));
2740
        print theme('maintenance_page', array('content' => filter_xss_admin(variable_get('maintenance_mode_message',
2741
          t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))))));
2742
        break;
2743
    }
2744
  }
2745
  elseif (isset($page_callback_result)) {
2746
    // Print anything besides a menu constant, assuming it's not NULL or
2747
    // undefined.
2748
    print drupal_render_page($page_callback_result);
2749
  }
2750

    
2751
  // Perform end-of-request tasks.
2752
  drupal_page_footer();
2753
}
2754

    
2755
/**
2756
 * Performs end-of-request tasks.
2757
 *
2758
 * This function sets the page cache if appropriate, and allows modules to
2759
 * react to the closing of the page by calling hook_exit().
2760
 */
2761
function drupal_page_footer() {
2762
  global $user;
2763

    
2764
  module_invoke_all('exit');
2765

    
2766
  // Commit the user session, if needed.
2767
  drupal_session_commit();
2768

    
2769
  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
2770
    drupal_serve_page_from_cache($cache);
2771
  }
2772
  else {
2773
    ob_flush();
2774
  }
2775

    
2776
  _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
2777
  drupal_cache_system_paths();
2778
  module_implements_write_cache();
2779
  drupal_file_scan_write_cache();
2780
  system_run_automated_cron();
2781
}
2782

    
2783
/**
2784
 * Performs end-of-request tasks.
2785
 *
2786
 * In some cases page requests need to end without calling drupal_page_footer().
2787
 * In these cases, call drupal_exit() instead. There should rarely be a reason
2788
 * to call exit instead of drupal_exit();
2789
 *
2790
 * @param $destination
2791
 *   If this function is called from drupal_goto(), then this argument
2792
 *   will be a fully-qualified URL that is the destination of the redirect.
2793
 *   This should be passed along to hook_exit() implementations.
2794
 */
2795
function drupal_exit($destination = NULL) {
2796
  if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL) {
2797
    if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
2798
      module_invoke_all('exit', $destination);
2799
    }
2800
    drupal_session_commit();
2801
  }
2802
  exit;
2803
}
2804

    
2805
/**
2806
 * Forms an associative array from a linear array.
2807
 *
2808
 * This function walks through the provided array and constructs an associative
2809
 * array out of it. The keys of the resulting array will be the values of the
2810
 * input array. The values will be the same as the keys unless a function is
2811
 * specified, in which case the output of the function is used for the values
2812
 * instead.
2813
 *
2814
 * @param $array
2815
 *   A linear array.
2816
 * @param $function
2817
 *   A name of a function to apply to all values before output.
2818
 *
2819
 * @return
2820
 *   An associative array.
2821
 */
2822
function drupal_map_assoc($array, $function = NULL) {
2823
  // array_combine() fails with empty arrays:
2824
  // http://bugs.php.net/bug.php?id=34857.
2825
  $array = !empty($array) ? array_combine($array, $array) : array();
2826
  if (is_callable($function)) {
2827
    $array = array_map($function, $array);
2828
  }
2829
  return $array;
2830
}
2831

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

    
2870
/**
2871
 * Returns the path to a system item (module, theme, etc.).
2872
 *
2873
 * @param $type
2874
 *   The type of the item (i.e. theme, theme_engine, module, profile).
2875
 * @param $name
2876
 *   The name of the item for which the path is requested.
2877
 *
2878
 * @return
2879
 *   The path to the requested item or an empty string if the item is not found.
2880
 */
2881
function drupal_get_path($type, $name) {
2882
  return dirname(drupal_get_filename($type, $name));
2883
}
2884

    
2885
/**
2886
 * Returns the base URL path (i.e., directory) of the Drupal installation.
2887
 *
2888
 * base_path() adds a "/" to the beginning and end of the returned path if the
2889
 * path is not empty. At the very least, this will return "/".
2890
 *
2891
 * Examples:
2892
 * - http://example.com returns "/" because the path is empty.
2893
 * - http://example.com/drupal/folder returns "/drupal/folder/".
2894
 */
2895
function base_path() {
2896
  return $GLOBALS['base_path'];
2897
}
2898

    
2899
/**
2900
 * Adds a LINK tag with a distinct 'rel' attribute to the page's HEAD.
2901
 *
2902
 * This function can be called as long the HTML header hasn't been sent, which
2903
 * on normal pages is up through the preprocess step of theme('html'). Adding
2904
 * a link will overwrite a prior link with the exact same 'rel' and 'href'
2905
 * attributes.
2906
 *
2907
 * @param $attributes
2908
 *   Associative array of element attributes including 'href' and 'rel'.
2909
 * @param $header
2910
 *   Optional flag to determine if a HTTP 'Link:' header should be sent.
2911
 */
2912
function drupal_add_html_head_link($attributes, $header = FALSE) {
2913
  $element = array(
2914
    '#tag' => 'link',
2915
    '#attributes' => $attributes,
2916
  );
2917
  $href = $attributes['href'];
2918

    
2919
  if ($header) {
2920
    // Also add a HTTP header "Link:".
2921
    $href = '<' . check_plain($attributes['href']) . '>;';
2922
    unset($attributes['href']);
2923
    $element['#attached']['drupal_add_http_header'][] = array('Link',  $href . drupal_http_header_attributes($attributes), TRUE);
2924
  }
2925

    
2926
  drupal_add_html_head($element, 'drupal_add_html_head_link:' . $attributes['rel'] . ':' . $href);
2927
}
2928

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

    
3049
  // If the $css variable has been reset with drupal_static_reset(), there is
3050
  // no longer any CSS being tracked, so set the counter back to 0 also.
3051
  if (count($css) === 0) {
3052
    $count = 0;
3053
  }
3054

    
3055
  // Construct the options, taking the defaults into consideration.
3056
  if (isset($options)) {
3057
    if (!is_array($options)) {
3058
      $options = array('type' => $options);
3059
    }
3060
  }
3061
  else {
3062
    $options = array();
3063
  }
3064

    
3065
  // Create an array of CSS files for each media type first, since each type needs to be served
3066
  // to the browser differently.
3067
  if (isset($data)) {
3068
    $options += array(
3069
      'type' => 'file',
3070
      'group' => CSS_DEFAULT,
3071
      'weight' => 0,
3072
      'every_page' => FALSE,
3073
      'media' => 'all',
3074
      'preprocess' => TRUE,
3075
      'data' => $data,
3076
      'browsers' => array(),
3077
    );
3078
    $options['browsers'] += array(
3079
      'IE' => TRUE,
3080
      '!IE' => TRUE,
3081
    );
3082

    
3083
    // Files with a query string cannot be preprocessed.
3084
    if ($options['type'] === 'file' && $options['preprocess'] && strpos($options['data'], '?') !== FALSE) {
3085
      $options['preprocess'] = FALSE;
3086
    }
3087

    
3088
    // Always add a tiny value to the weight, to conserve the insertion order.
3089
    $options['weight'] += $count / 1000;
3090
    $count++;
3091

    
3092
    // Add the data to the CSS array depending on the type.
3093
    switch ($options['type']) {
3094
      case 'inline':
3095
        // For inline stylesheets, we don't want to use the $data as the array
3096
        // key as $data could be a very long string of CSS.
3097
        $css[] = $options;
3098
        break;
3099
      default:
3100
        // Local and external files must keep their name as the associative key
3101
        // so the same CSS file is not be added twice.
3102
        $css[$data] = $options;
3103
    }
3104
  }
3105

    
3106
  return $css;
3107
}
3108

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

    
3143
  // Allow modules and themes to alter the CSS items.
3144
  if (!$skip_alter) {
3145
    drupal_alter('css', $css);
3146
  }
3147

    
3148
  // Sort CSS items, so that they appear in the correct order.
3149
  uasort($css, 'drupal_sort_css_js');
3150

    
3151
  // Provide the page with information about the individual CSS files used,
3152
  // information not otherwise available when CSS aggregation is enabled. The
3153
  // setting is attached later in this function, but is set here, so that CSS
3154
  // files removed below are still considered "used" and prevented from being
3155
  // added in a later AJAX request.
3156
  // Skip if no files were added to the page or jQuery.extend() will overwrite
3157
  // the Drupal.settings.ajaxPageState.css object with an empty array.
3158
  if (!empty($css)) {
3159
    // Cast the array to an object to be on the safe side even if not empty.
3160
    $setting['ajaxPageState']['css'] = (object) array_fill_keys(array_keys($css), 1);
3161
  }
3162

    
3163
  // Remove the overridden CSS files. Later CSS files override former ones.
3164
  $previous_item = array();
3165
  foreach ($css as $key => $item) {
3166
    if ($item['type'] == 'file') {
3167
      // If defined, force a unique basename for this file.
3168
      $basename = isset($item['basename']) ? $item['basename'] : drupal_basename($item['data']);
3169
      if (isset($previous_item[$basename])) {
3170
        // Remove the previous item that shared the same base name.
3171
        unset($css[$previous_item[$basename]]);
3172
      }
3173
      $previous_item[$basename] = $key;
3174
    }
3175
  }
3176

    
3177
  // Render the HTML needed to load the CSS.
3178
  $styles = array(
3179
    '#type' => 'styles',
3180
    '#items' => $css,
3181
  );
3182

    
3183
  if (!empty($setting)) {
3184
    $styles['#attached']['js'][] = array('type' => 'setting', 'data' => $setting);
3185
  }
3186

    
3187
  return drupal_render($styles);
3188
}
3189

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

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

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

    
3322
    // If the group keys don't match the most recent group we're working with,
3323
    // then a new group must be made.
3324
    if ($group_keys !== $current_group_keys) {
3325
      $i++;
3326
      // Initialize the new group with the same properties as the first item
3327
      // being placed into it. The item's 'data' and 'weight' properties are
3328
      // unique to the item and should not be carried over to the group.
3329
      $groups[$i] = $item;
3330
      unset($groups[$i]['data'], $groups[$i]['weight']);
3331
      $groups[$i]['items'] = array();
3332
      $current_group_keys = $group_keys ? $group_keys : NULL;
3333
    }
3334

    
3335
    // Add the item to the current group.
3336
    $groups[$i]['items'][] = $item;
3337
  }
3338
  return $groups;
3339
}
3340

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

    
3363
  // For each group that needs aggregation, aggregate its items.
3364
  foreach ($css_groups as $key => $group) {
3365
    switch ($group['type']) {
3366
      // If a file group can be aggregated into a single file, do so, and set
3367
      // the group's data property to the file path of the aggregate file.
3368
      case 'file':
3369
        if ($group['preprocess'] && $preprocess_css) {
3370
          $css_groups[$key]['data'] = drupal_build_css_cache($group['items']);
3371
        }
3372
        break;
3373
      // Aggregate all inline CSS content into the group's data property.
3374
      case 'inline':
3375
        $css_groups[$key]['data'] = '';
3376
        foreach ($group['items'] as $item) {
3377
          $css_groups[$key]['data'] .= drupal_load_stylesheet_content($item['data'], $item['preprocess']);
3378
        }
3379
        break;
3380
    }
3381
  }
3382
}
3383

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

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

    
3460
  // For inline CSS to validate as XHTML, all CSS containing XHTML needs to be
3461
  // wrapped in CDATA. To make that backwards compatible with HTML 4, we need to
3462
  // comment out the CDATA-tag.
3463
  $embed_prefix = "\n<!--/*--><![CDATA[/*><!--*/\n";
3464
  $embed_suffix = "\n/*]]>*/-->\n";
3465

    
3466
  // Defaults for LINK and STYLE elements.
3467
  $link_element_defaults = array(
3468
    '#type' => 'html_tag',
3469
    '#tag' => 'link',
3470
    '#attributes' => array(
3471
      'type' => 'text/css',
3472
      'rel' => 'stylesheet',
3473
    ),
3474
  );
3475
  $style_element_defaults = array(
3476
    '#type' => 'html_tag',
3477
    '#tag' => 'style',
3478
    '#attributes' => array(
3479
      'type' => 'text/css',
3480
    ),
3481
  );
3482

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

    
3609
  return $elements;
3610
}
3611

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

    
3651
  if (empty($uri) || !file_exists($uri)) {
3652
    // Build aggregate CSS file.
3653
    foreach ($css as $stylesheet) {
3654
      // Only 'file' stylesheets can be aggregated.
3655
      if ($stylesheet['type'] == 'file') {
3656
        $contents = drupal_load_stylesheet($stylesheet['data'], TRUE);
3657

    
3658
        // Build the base URL of this CSS file: start with the full URL.
3659
        $css_base_url = file_create_url($stylesheet['data']);
3660
        // Move to the parent.
3661
        $css_base_url = substr($css_base_url, 0, strrpos($css_base_url, '/'));
3662
        // Simplify to a relative URL if the stylesheet URL starts with the
3663
        // base URL of the website.
3664
        if (substr($css_base_url, 0, strlen($GLOBALS['base_root'])) == $GLOBALS['base_root']) {
3665
          $css_base_url = substr($css_base_url, strlen($GLOBALS['base_root']));
3666
        }
3667

    
3668
        _drupal_build_css_path(NULL, $css_base_url . '/');
3669
        // Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
3670
        $data .= preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);
3671
      }
3672
    }
3673

    
3674
    // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
3675
    // @import rules must proceed any other style, so we move those to the top.
3676
    $regexp = '/@import[^;]+;/i';
3677
    preg_match_all($regexp, $data, $matches);
3678
    $data = preg_replace($regexp, '', $data);
3679
    $data = implode('', $matches[0]) . $data;
3680

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

    
3708
/**
3709
 * Prefixes all paths within a CSS file for drupal_build_css_cache().
3710
 */
3711
function _drupal_build_css_path($matches, $base = NULL) {
3712
  $_base = &drupal_static(__FUNCTION__);
3713
  // Store base path for preg_replace_callback.
3714
  if (isset($base)) {
3715
    $_base = $base;
3716
  }
3717

    
3718
  // Prefix with base and remove '../' segments where possible.
3719
  $path = $_base . $matches[1];
3720
  $last = '';
3721
  while ($path != $last) {
3722
    $last = $path;
3723
    $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
3724
  }
3725
  return 'url(' . $path . ')';
3726
}
3727

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

    
3761
  // Stylesheets are relative one to each other. Start by adding a base path
3762
  // prefix provided by the parent stylesheet (if necessary).
3763
  if ($basepath && !file_uri_scheme($file)) {
3764
    $file = $basepath . '/' . $file;
3765
  }
3766
  // Store the parent base path to restore it later.
3767
  $parent_base_path = $basepath;
3768
  // Set the current base path to process possible child imports.
3769
  $basepath = dirname($file);
3770

    
3771
  // Load the CSS stylesheet. We suppress errors because themes may specify
3772
  // stylesheets in their .info file that don't exist in the theme's path,
3773
  // but are merely there to disable certain module CSS files.
3774
  $content = '';
3775
  if ($contents = @file_get_contents($file)) {
3776
    // Return the processed stylesheet.
3777
    $content = drupal_load_stylesheet_content($contents, $_optimize);
3778
  }
3779

    
3780
  // Restore the parent base path as the file and its childen are processed.
3781
  $basepath = $parent_base_path;
3782
  return $content;
3783
}
3784

    
3785
/**
3786
 * Processes the contents of a stylesheet for aggregation.
3787
 *
3788
 * @param $contents
3789
 *   The contents of the stylesheet.
3790
 * @param $optimize
3791
 *   (optional) Boolean whether CSS contents should be minified. Defaults to
3792
 *   FALSE.
3793
 *
3794
 * @return
3795
 *   Contents of the stylesheet including the imported stylesheets.
3796
 */
3797
function drupal_load_stylesheet_content($contents, $optimize = FALSE) {
3798
  // Remove multiple charset declarations for standards compliance (and fixing Safari problems).
3799
  $contents = preg_replace('/^@charset\s+[\'"](\S*?)\b[\'"];/i', '', $contents);
3800

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

    
3841
  // Replaces @import commands with the actual stylesheet content.
3842
  // This happens recursively but omits external files.
3843
  $contents = preg_replace_callback('/@import\s*(?:url\(\s*)?[\'"]?(?![a-z]+:)(?!\/\/)([^\'"\()]+)[\'"]?\s*\)?\s*;/', '_drupal_load_stylesheet', $contents);
3844
  return $contents;
3845
}
3846

    
3847
/**
3848
 * Loads stylesheets recursively and returns contents with corrected paths.
3849
 *
3850
 * This function is used for recursive loading of stylesheets and
3851
 * returns the stylesheet content with all url() paths corrected.
3852
 */
3853
function _drupal_load_stylesheet($matches) {
3854
  $filename = $matches[1];
3855
  // Load the imported stylesheet and replace @import commands in there as well.
3856
  $file = drupal_load_stylesheet($filename, NULL, FALSE);
3857

    
3858
  // Determine the file's directory.
3859
  $directory = dirname($filename);
3860
  // If the file is in the current directory, make sure '.' doesn't appear in
3861
  // the url() path.
3862
  $directory = $directory == '.' ? '' : $directory .'/';
3863

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

    
3870
/**
3871
 * Deletes old cached CSS files.
3872
 */
3873
function drupal_clear_css_cache() {
3874
  variable_del('drupal_css_cache_files');
3875
  file_scan_directory('public://css', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
3876
}
3877

    
3878
/**
3879
 * Callback to delete files modified more than a set time ago.
3880
 */
3881
function drupal_delete_file_if_stale($uri) {
3882
  // Default stale file threshold is 30 days.
3883
  if (REQUEST_TIME - filemtime($uri) > variable_get('drupal_stale_file_threshold', 2592000)) {
3884
    file_unmanaged_delete($uri);
3885
  }
3886
}
3887

    
3888
/**
3889
 * Prepares a string for use as a CSS identifier (element, class, or ID name).
3890
 *
3891
 * http://www.w3.org/TR/CSS21/syndata.html#characters shows the syntax for valid
3892
 * CSS identifiers (including element names, classes, and IDs in selectors.)
3893
 *
3894
 * @param $identifier
3895
 *   The identifier to clean.
3896
 * @param $filter
3897
 *   An array of string replacements to use on the identifier.
3898
 *
3899
 * @return
3900
 *   The cleaned identifier.
3901
 */
3902
function drupal_clean_css_identifier($identifier, $filter = array(' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '')) {
3903
  // Use the advanced drupal_static() pattern, since this is called very often.
3904
  static $drupal_static_fast;
3905
  if (!isset($drupal_static_fast)) {
3906
    $drupal_static_fast['allow_css_double_underscores'] = &drupal_static(__FUNCTION__ . ':allow_css_double_underscores');
3907
  }
3908
  $allow_css_double_underscores = &$drupal_static_fast['allow_css_double_underscores'];
3909
  if (!isset($allow_css_double_underscores)) {
3910
    $allow_css_double_underscores = variable_get('allow_css_double_underscores', FALSE);
3911
  }
3912

    
3913
  // Preserve BEM-style double-underscores depending on custom setting.
3914
  if ($allow_css_double_underscores) {
3915
    $filter['__'] = '__';
3916
  }
3917

    
3918
  // By default, we filter using Drupal's coding standards.
3919
  $identifier = strtr($identifier, $filter);
3920

    
3921
  // Valid characters in a CSS identifier are:
3922
  // - the hyphen (U+002D)
3923
  // - a-z (U+0030 - U+0039)
3924
  // - A-Z (U+0041 - U+005A)
3925
  // - the underscore (U+005F)
3926
  // - 0-9 (U+0061 - U+007A)
3927
  // - ISO 10646 characters U+00A1 and higher
3928
  // We strip out any character not in the above list.
3929
  $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);
3930

    
3931
  return $identifier;
3932
}
3933

    
3934
/**
3935
 * Prepares a string for use as a valid class name.
3936
 *
3937
 * Do not pass one string containing multiple classes as they will be
3938
 * incorrectly concatenated with dashes, i.e. "one two" will become "one-two".
3939
 *
3940
 * @param $class
3941
 *   The class name to clean.
3942
 *
3943
 * @return
3944
 *   The cleaned class name.
3945
 */
3946
function drupal_html_class($class) {
3947
  // The output of this function will never change, so this uses a normal
3948
  // static instead of drupal_static().
3949
  static $classes = array();
3950

    
3951
  if (!isset($classes[$class])) {
3952
    $classes[$class] = drupal_clean_css_identifier(drupal_strtolower($class));
3953
  }
3954
  return $classes[$class];
3955
}
3956

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

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

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

    
4046
  // Removing multiple consecutive hyphens.
4047
  $id = preg_replace('/\-+/', '-', $id);
4048
  // Ensure IDs are unique by appending a counter after the first occurrence.
4049
  // The counter needs to be appended with a delimiter that does not exist in
4050
  // the base ID. Requiring a unique delimiter helps ensure that we really do
4051
  // return unique IDs and also helps us re-create the $seen_ids array during
4052
  // Ajax requests.
4053
  if (isset($seen_ids[$id])) {
4054
    $id = $id . '--' . ++$seen_ids[$id];
4055
  }
4056
  else {
4057
    $seen_ids[$id] = 1;
4058
  }
4059

    
4060
  return $id;
4061
}
4062

    
4063
/**
4064
 * Provides a standard HTML class name that identifies a page region.
4065
 *
4066
 * It is recommended that template preprocess functions apply this class to any
4067
 * page region that is output by the theme (Drupal core already handles this in
4068
 * the standard template preprocess implementation). Standardizing the class
4069
 * names in this way allows modules to implement certain features, such as
4070
 * drag-and-drop or dynamic Ajax loading, in a theme-independent way.
4071
 *
4072
 * @param $region
4073
 *   The name of the page region (for example, 'page_top' or 'content').
4074
 *
4075
 * @return
4076
 *   An HTML class that identifies the region (for example, 'region-page-top'
4077
 *   or 'region-content').
4078
 *
4079
 * @see template_preprocess_region()
4080
 */
4081
function drupal_region_class($region) {
4082
  return drupal_html_class("region-$region");
4083
}
4084

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

    
4244
  // If the $javascript variable has been reset with drupal_static_reset(),
4245
  // jQuery and related files will have been removed from the list, so set the
4246
  // variable back to FALSE to indicate they have not yet been added.
4247
  if (empty($javascript)) {
4248
    $jquery_added = FALSE;
4249
  }
4250

    
4251
  // Construct the options, taking the defaults into consideration.
4252
  if (isset($options)) {
4253
    if (!is_array($options)) {
4254
      $options = array('type' => $options);
4255
    }
4256
  }
4257
  else {
4258
    $options = array();
4259
  }
4260
  if (isset($options['type']) && $options['type'] == 'setting') {
4261
    $options += array('requires_jquery' => FALSE);
4262
  }
4263
  $options += drupal_js_defaults($data);
4264

    
4265
  // Preprocess can only be set if caching is enabled.
4266
  $options['preprocess'] = $options['cache'] ? $options['preprocess'] : FALSE;
4267

    
4268
  // Tweak the weight so that files of the same weight are included in the
4269
  // order of the calls to drupal_add_js().
4270
  $options['weight'] += count($javascript) / 1000;
4271

    
4272
  if (isset($data)) {
4273
    // Add jquery.js, drupal.js, and related files and settings if they have
4274
    // not been added yet. However, if the 'javascript_always_use_jquery'
4275
    // variable is set to FALSE (indicating that the site does not want jQuery
4276
    // automatically added on all pages) then only add it if a file or setting
4277
    // that requires jQuery is being added also.
4278
    if (!$jquery_added && (variable_get('javascript_always_use_jquery', TRUE) || $options['requires_jquery'])) {
4279
      $jquery_added = TRUE;
4280
      // url() generates the prefix using hook_url_outbound_alter(). Instead of
4281
      // running the hook_url_outbound_alter() again here, extract the prefix
4282
      // from url().
4283
      url('', array('prefix' => &$prefix));
4284
      $default_javascript = array(
4285
        'settings' => array(
4286
          'data' => array(
4287
            array('basePath' => base_path()),
4288
            array('pathPrefix' => empty($prefix) ? '' : $prefix),
4289
          ),
4290
          'type' => 'setting',
4291
          'scope' => 'header',
4292
          'group' => JS_LIBRARY,
4293
          'every_page' => TRUE,
4294
          'weight' => 0,
4295
        ),
4296
        'misc/drupal.js' => array(
4297
          'data' => 'misc/drupal.js',
4298
          'type' => 'file',
4299
          'scope' => 'header',
4300
          'group' => JS_LIBRARY,
4301
          'every_page' => TRUE,
4302
          'weight' => -1,
4303
          'requires_jquery' => TRUE,
4304
          'preprocess' => TRUE,
4305
          'cache' => TRUE,
4306
          'defer' => FALSE,
4307
        ),
4308
      );
4309
      $javascript = drupal_array_merge_deep($javascript, $default_javascript);
4310
      // Register all required libraries.
4311
      drupal_add_library('system', 'jquery', TRUE);
4312
      drupal_add_library('system', 'jquery.once', TRUE);
4313
    }
4314

    
4315
    switch ($options['type']) {
4316
      case 'setting':
4317
        // All JavaScript settings are placed in the header of the page with
4318
        // the library weight so that inline scripts appear afterwards.
4319
        $javascript['settings']['data'][] = $data;
4320
        break;
4321

    
4322
      case 'inline':
4323
        $javascript[] = $options;
4324
        break;
4325

    
4326
      default: // 'file' and 'external'
4327
        // Local and external files must keep their name as the associative key
4328
        // so the same JavaScript file is not added twice.
4329
        $javascript[$options['data']] = $options;
4330
    }
4331
  }
4332
  return $javascript;
4333
}
4334

    
4335
/**
4336
 * Constructs an array of the defaults that are used for JavaScript items.
4337
 *
4338
 * @param $data
4339
 *   (optional) The default data parameter for the JavaScript item array.
4340
 *
4341
 * @see drupal_get_js()
4342
 * @see drupal_add_js()
4343
 */
4344
function drupal_js_defaults($data = NULL) {
4345
  return array(
4346
    'type' => 'file',
4347
    'group' => JS_DEFAULT,
4348
    'every_page' => FALSE,
4349
    'weight' => 0,
4350
    'requires_jquery' => TRUE,
4351
    'scope' => 'header',
4352
    'cache' => TRUE,
4353
    'defer' => FALSE,
4354
    'preprocess' => TRUE,
4355
    'version' => NULL,
4356
    'data' => $data,
4357
  );
4358
}
4359

    
4360
/**
4361
 * Returns a themed presentation of all JavaScript code for the current page.
4362
 *
4363
 * References to JavaScript files are placed in a certain order: first, all
4364
 * 'core' files, then all 'module' and finally all 'theme' JavaScript files
4365
 * are added to the page. Then, all settings are output, followed by 'inline'
4366
 * JavaScript code. If running update.php, all preprocessing is disabled.
4367
 *
4368
 * Note that hook_js_alter(&$javascript) is called during this function call
4369
 * to allow alterations of the JavaScript during its presentation. Calls to
4370
 * drupal_add_js() from hook_js_alter() will not be added to the output
4371
 * presentation. The correct way to add JavaScript during hook_js_alter()
4372
 * is to add another element to the $javascript array, deriving from
4373
 * drupal_js_defaults(). See locale_js_alter() for an example of this.
4374
 *
4375
 * @param $scope
4376
 *   (optional) The scope for which the JavaScript rules should be returned.
4377
 *   Defaults to 'header'.
4378
 * @param $javascript
4379
 *   (optional) An array with all JavaScript code. Defaults to the default
4380
 *   JavaScript array for the given scope.
4381
 * @param $skip_alter
4382
 *   (optional) If set to TRUE, this function skips calling drupal_alter() on
4383
 *   $javascript, useful when the calling function passes a $javascript array
4384
 *   that has already been altered.
4385
 *
4386
 * @return
4387
 *   All JavaScript code segments and includes for the scope as HTML tags.
4388
 *
4389
 * @see drupal_add_js()
4390
 * @see locale_js_alter()
4391
 * @see drupal_js_defaults()
4392
 */
4393
function drupal_get_js($scope = 'header', $javascript = NULL, $skip_alter = FALSE) {
4394
  if (!isset($javascript)) {
4395
    $javascript = drupal_add_js();
4396
  }
4397

    
4398
  // If no JavaScript items have been added, or if the only JavaScript items
4399
  // that have been added are JavaScript settings (which don't do anything
4400
  // without any JavaScript code to use them), then no JavaScript code should
4401
  // be added to the page.
4402
  if (empty($javascript) || (isset($javascript['settings']) && count($javascript) == 1)) {
4403
    return '';
4404
  }
4405

    
4406
  // Allow modules to alter the JavaScript.
4407
  if (!$skip_alter) {
4408
    drupal_alter('js', $javascript);
4409
  }
4410

    
4411
  // Filter out elements of the given scope.
4412
  $items = array();
4413
  foreach ($javascript as $key => $item) {
4414
    if ($item['scope'] == $scope) {
4415
      $items[$key] = $item;
4416
    }
4417
  }
4418

    
4419
  $output = '';
4420
  // The index counter is used to keep aggregated and non-aggregated files in
4421
  // order by weight.
4422
  $index = 1;
4423
  $processed = array();
4424
  $files = array();
4425
  $preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
4426

    
4427
  // A dummy query-string is added to filenames, to gain control over
4428
  // browser-caching. The string changes on every update or full cache
4429
  // flush, forcing browsers to load a new copy of the files, as the
4430
  // URL changed. Files that should not be cached (see drupal_add_js())
4431
  // get REQUEST_TIME as query-string instead, to enforce reload on every
4432
  // page request.
4433
  $default_query_string = variable_get('css_js_query_string', '0');
4434

    
4435
  // For inline JavaScript to validate as XHTML, all JavaScript containing
4436
  // XHTML needs to be wrapped in CDATA. To make that backwards compatible
4437
  // with HTML 4, we need to comment out the CDATA-tag.
4438
  $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
4439
  $embed_suffix = "\n//--><!]]>\n";
4440

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

    
4445
  // Sort the JavaScript so that it appears in the correct order.
4446
  uasort($items, 'drupal_sort_css_js');
4447

    
4448
  // Provide the page with information about the individual JavaScript files
4449
  // used, information not otherwise available when aggregation is enabled.
4450
  $setting['ajaxPageState']['js'] = array_fill_keys(array_keys($items), 1);
4451
  unset($setting['ajaxPageState']['js']['settings']);
4452
  drupal_add_js($setting, 'setting');
4453

    
4454
  // If we're outputting the header scope, then this might be the final time
4455
  // that drupal_get_js() is running, so add the setting to this output as well
4456
  // as to the drupal_add_js() cache. If $items['settings'] doesn't exist, it's
4457
  // because drupal_get_js() was intentionally passed a $javascript argument
4458
  // stripped off settings, potentially in order to override how settings get
4459
  // output, so in this case, do not add the setting to this output.
4460
  if ($scope == 'header' && isset($items['settings'])) {
4461
    $items['settings']['data'][] = $setting;
4462
  }
4463

    
4464
  // Loop through the JavaScript to construct the rendered output.
4465
  $element = array(
4466
    '#tag' => 'script',
4467
    '#value' => '',
4468
    '#attributes' => array(
4469
      'type' => 'text/javascript',
4470
    ),
4471
  );
4472
  foreach ($items as $item) {
4473
    $query_string =  empty($item['version']) ? $default_query_string : $js_version_string . $item['version'];
4474

    
4475
    switch ($item['type']) {
4476
      case 'setting':
4477
        $js_element = $element;
4478
        $js_element['#value_prefix'] = $embed_prefix;
4479
        $js_element['#value'] = 'jQuery.extend(Drupal.settings, ' . drupal_json_encode(drupal_array_merge_deep_array($item['data'])) . ");";
4480
        $js_element['#value_suffix'] = $embed_suffix;
4481
        $output .= theme('html_tag', array('element' => $js_element));
4482
        break;
4483

    
4484
      case 'inline':
4485
        $js_element = $element;
4486
        if ($item['defer']) {
4487
          $js_element['#attributes']['defer'] = 'defer';
4488
        }
4489
        $js_element['#value_prefix'] = $embed_prefix;
4490
        $js_element['#value'] = $item['data'];
4491
        $js_element['#value_suffix'] = $embed_suffix;
4492
        $processed[$index++] = theme('html_tag', array('element' => $js_element));
4493
        break;
4494

    
4495
      case 'file':
4496
        $js_element = $element;
4497
        if (!$item['preprocess'] || !$preprocess_js) {
4498
          if ($item['defer']) {
4499
            $js_element['#attributes']['defer'] = 'defer';
4500
          }
4501
          $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
4502
          $js_element['#attributes']['src'] = file_create_url($item['data']) . $query_string_separator . ($item['cache'] ? $query_string : REQUEST_TIME);
4503
          $processed[$index++] = theme('html_tag', array('element' => $js_element));
4504
        }
4505
        else {
4506
          // By increasing the index for each aggregated file, we maintain
4507
          // the relative ordering of JS by weight. We also set the key such
4508
          // that groups are split by items sharing the same 'group' value and
4509
          // 'every_page' flag. While this potentially results in more aggregate
4510
          // files, it helps make each one more reusable across a site visit,
4511
          // leading to better front-end performance of a website as a whole.
4512
          // See drupal_add_js() for details.
4513
          $key = 'aggregate_' . $item['group'] . '_' . $item['every_page'] . '_' . $index;
4514
          $processed[$key] = '';
4515
          $files[$key][$item['data']] = $item;
4516
        }
4517
        break;
4518

    
4519
      case 'external':
4520
        $js_element = $element;
4521
        // Preprocessing for external JavaScript files is ignored.
4522
        if ($item['defer']) {
4523
          $js_element['#attributes']['defer'] = 'defer';
4524
        }
4525
        $js_element['#attributes']['src'] = $item['data'];
4526
        $processed[$index++] = theme('html_tag', array('element' => $js_element));
4527
        break;
4528
    }
4529
  }
4530

    
4531
  // Aggregate any remaining JS files that haven't already been output.
4532
  if ($preprocess_js && count($files) > 0) {
4533
    foreach ($files as $key => $file_set) {
4534
      $uri = drupal_build_js_cache($file_set);
4535
      // Only include the file if was written successfully. Errors are logged
4536
      // using watchdog.
4537
      if ($uri) {
4538
        $preprocess_file = file_create_url($uri);
4539
        $js_element = $element;
4540
        $js_element['#attributes']['src'] = $preprocess_file;
4541
        $processed[$key] = theme('html_tag', array('element' => $js_element));
4542
      }
4543
    }
4544
  }
4545

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

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

    
4615
  // Add the libraries first.
4616
  $success = TRUE;
4617
  foreach ($elements['#attached']['library'] as $library) {
4618
    if (drupal_add_library($library[0], $library[1], $every_page) === FALSE) {
4619
      $success = FALSE;
4620
      // Exit if the dependency is missing.
4621
      if ($dependency_check) {
4622
        return $success;
4623
      }
4624
    }
4625
  }
4626
  unset($elements['#attached']['library']);
4627

    
4628
  // Add both the JavaScript and the CSS.
4629
  // The parameters for drupal_add_js() and drupal_add_css() require special
4630
  // handling.
4631
  foreach (array('js', 'css') as $type) {
4632
    foreach ($elements['#attached'][$type] as $data => $options) {
4633
      // If the value is not an array, it's a filename and passed as first
4634
      // (and only) argument.
4635
      if (!is_array($options)) {
4636
        $data = $options;
4637
        $options = NULL;
4638
      }
4639
      // In some cases, the first parameter ($data) is an array. Arrays can't be
4640
      // passed as keys in PHP, so we have to get $data from the value array.
4641
      if (is_numeric($data)) {
4642
        $data = $options['data'];
4643
        unset($options['data']);
4644
      }
4645
      // Apply the default group if it isn't explicitly given.
4646
      if (!isset($options['group'])) {
4647
        $options['group'] = $group;
4648
      }
4649
      // Set the every_page flag if one was passed.
4650
      if (isset($every_page)) {
4651
        $options['every_page'] = $every_page;
4652
      }
4653
      call_user_func('drupal_add_' . $type, $data, $options);
4654
    }
4655
    unset($elements['#attached'][$type]);
4656
  }
4657

    
4658
  // Add additional types of attachments specified in the render() structure.
4659
  // Libraries, JavaScript and CSS have been added already, as they require
4660
  // special handling.
4661
  foreach ($elements['#attached'] as $callback => $options) {
4662
    if (function_exists($callback)) {
4663
      foreach ($elements['#attached'][$callback] as $args) {
4664
        call_user_func_array($callback, $args);
4665
      }
4666
    }
4667
  }
4668

    
4669
  return $success;
4670
}
4671

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

    
4803
/**
4804
 * Adds multiple JavaScript or CSS files at the same time.
4805
 *
4806
 * A library defines a set of JavaScript and/or CSS files, optionally using
4807
 * settings, and optionally requiring another library. For example, a library
4808
 * can be a jQuery plugin, a JavaScript framework, or a CSS framework. This
4809
 * function allows modules to load a library defined/shipped by itself or a
4810
 * depending module, without having to add all files of the library separately.
4811
 * Each library is only loaded once.
4812
 *
4813
 * @param $module
4814
 *   The name of the module that registered the library.
4815
 * @param $name
4816
 *   The name of the library to add.
4817
 * @param $every_page
4818
 *   Set to TRUE if this library is added to every page on the site. Only items
4819
 *   with the every_page flag set to TRUE can participate in aggregation.
4820
 *
4821
 * @return
4822
 *   TRUE if the library was successfully added; FALSE if the library or one of
4823
 *   its dependencies could not be added.
4824
 *
4825
 * @see drupal_get_library()
4826
 * @see hook_library()
4827
 * @see hook_library_alter()
4828
 */
4829
function drupal_add_library($module, $name, $every_page = NULL) {
4830
  $added = &drupal_static(__FUNCTION__, array());
4831

    
4832
  // Only process the library if it exists and it was not added already.
4833
  if (!isset($added[$module][$name])) {
4834
    if ($library = drupal_get_library($module, $name)) {
4835
      // Add all components within the library.
4836
      $elements['#attached'] = array(
4837
        'library' => $library['dependencies'],
4838
        'js' => $library['js'],
4839
        'css' => $library['css'],
4840
      );
4841
      $added[$module][$name] = drupal_process_attached($elements, JS_LIBRARY, TRUE, $every_page);
4842
    }
4843
    else {
4844
      // Requested library does not exist.
4845
      $added[$module][$name] = FALSE;
4846
    }
4847
  }
4848

    
4849
  return $added[$module][$name];
4850
}
4851

    
4852
/**
4853
 * Retrieves information for a JavaScript/CSS library.
4854
 *
4855
 * Library information is statically cached. Libraries are keyed by module for
4856
 * several reasons:
4857
 * - Libraries are not unique. Multiple modules might ship with the same library
4858
 *   in a different version or variant. This registry cannot (and does not
4859
 *   attempt to) prevent library conflicts.
4860
 * - Modules implementing and thereby depending on a library that is registered
4861
 *   by another module can only rely on that module's library.
4862
 * - Two (or more) modules can still register the same library and use it
4863
 *   without conflicts in case the libraries are loaded on certain pages only.
4864
 *
4865
 * @param $module
4866
 *   The name of a module that registered a library.
4867
 * @param $name
4868
 *   (optional) The name of a registered library to retrieve. By default, all
4869
 *   libraries registered by $module are returned.
4870
 *
4871
 * @return
4872
 *   The definition of the requested library, if $name was passed and it exists,
4873
 *   or FALSE if it does not exist. If no $name was passed, an associative array
4874
 *   of libraries registered by $module is returned (which may be empty).
4875
 *
4876
 * @see drupal_add_library()
4877
 * @see hook_library()
4878
 * @see hook_library_alter()
4879
 *
4880
 * @todo The purpose of drupal_get_*() is completely different to other page
4881
 *   requisite API functions; find and use a different name.
4882
 */
4883
function drupal_get_library($module, $name = NULL) {
4884
  $libraries = &drupal_static(__FUNCTION__, array());
4885

    
4886
  if (!isset($libraries[$module])) {
4887
    // Retrieve all libraries associated with the module.
4888
    $module_libraries = module_invoke($module, 'library');
4889
    if (empty($module_libraries)) {
4890
      $module_libraries = array();
4891
    }
4892
    // Allow modules to alter the module's registered libraries.
4893
    drupal_alter('library', $module_libraries, $module);
4894

    
4895
    foreach ($module_libraries as $key => $data) {
4896
      if (is_array($data)) {
4897
        // Add default elements to allow for easier processing.
4898
        $module_libraries[$key] += array('dependencies' => array(), 'js' => array(), 'css' => array());
4899
        foreach ($module_libraries[$key]['js'] as $file => $options) {
4900
          $module_libraries[$key]['js'][$file]['version'] = $module_libraries[$key]['version'];
4901
        }
4902
      }
4903
    }
4904
    $libraries[$module] = $module_libraries;
4905
  }
4906
  if (isset($name)) {
4907
    if (!isset($libraries[$module][$name])) {
4908
      $libraries[$module][$name] = FALSE;
4909
    }
4910
    return $libraries[$module][$name];
4911
  }
4912
  return $libraries[$module];
4913
}
4914

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

    
5033
  // If a subgroup or source isn't set, assume it is the same as the group.
5034
  $target = isset($subgroup) ? $subgroup : $group;
5035
  $source = isset($source) ? $source : $target;
5036
  $settings['tableDrag'][$table_id][$group][] = array(
5037
    'target' => $target,
5038
    'source' => $source,
5039
    'relationship' => $relationship,
5040
    'action' => $action,
5041
    'hidden' => $hidden,
5042
    'limit' => $limit,
5043
  );
5044
  drupal_add_js($settings, 'setting');
5045
}
5046

    
5047
/**
5048
 * Aggregates JavaScript files into a cache file in the files directory.
5049
 *
5050
 * The file name for the JavaScript cache file is generated from the hash of
5051
 * the aggregated contents of the files in $files. This forces proxies and
5052
 * browsers to download new JavaScript when the JavaScript changes.
5053
 *
5054
 * The cache file name is retrieved on a page load via a lookup variable that
5055
 * contains an associative array. The array key is the hash of the names in
5056
 * $files while the value is the cache file name. The cache file is generated
5057
 * in two cases. First, if there is no file name value for the key, which will
5058
 * happen if a new file name has been added to $files or after the lookup
5059
 * variable is emptied to force a rebuild of the cache. Second, the cache file
5060
 * is generated if it is missing on disk. Old cache files are not deleted
5061
 * immediately when the lookup variable is emptied, but are deleted after a set
5062
 * period by drupal_delete_file_if_stale(). This ensures that files referenced
5063
 * by a cached page will still be available.
5064
 *
5065
 * @param $files
5066
 *   An array of JavaScript files to aggregate and compress into one file.
5067
 *
5068
 * @return
5069
 *   The URI of the cache file, or FALSE if the file could not be saved.
5070
 */
5071
function drupal_build_js_cache($files) {
5072
  $contents = '';
5073
  $uri = '';
5074
  $map = variable_get('drupal_js_cache_files', array());
5075
  // Create a new array so that only the file names are used to create the hash.
5076
  // This prevents new aggregates from being created unnecessarily.
5077
  $js_data = array();
5078
  foreach ($files as $file) {
5079
    $js_data[] = $file['data'];
5080
  }
5081
  $key = hash('sha256', serialize($js_data));
5082
  if (isset($map[$key])) {
5083
    $uri = $map[$key];
5084
  }
5085

    
5086
  if (empty($uri) || !file_exists($uri)) {
5087
    // Build aggregate JS file.
5088
    foreach ($files as $path => $info) {
5089
      if ($info['preprocess']) {
5090
        // Append a ';' and a newline after each JS file to prevent them from running together.
5091
        $contents .= file_get_contents($path) . ";\n";
5092
      }
5093
    }
5094
    // Prefix filename to prevent blocking by firewalls which reject files
5095
    // starting with "ad*".
5096
    $filename = 'js_' . drupal_hash_base64($contents) . '.js';
5097
    // Create the js/ within the files folder.
5098
    $jspath = 'public://js';
5099
    $uri = $jspath . '/' . $filename;
5100
    // Create the JS file.
5101
    file_prepare_directory($jspath, FILE_CREATE_DIRECTORY);
5102
    if (!file_exists($uri) && !file_unmanaged_save_data($contents, $uri, FILE_EXISTS_REPLACE)) {
5103
      return FALSE;
5104
    }
5105
    // If JS gzip compression is enabled, clean URLs are enabled (which means
5106
    // that rewrite rules are working) and the zlib extension is available then
5107
    // create a gzipped version of this file. This file is served conditionally
5108
    // to browsers that accept gzip using .htaccess rules.
5109
    if (variable_get('js_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
5110
      if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($contents, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
5111
        return FALSE;
5112
      }
5113
    }
5114
    $map[$key] = $uri;
5115
    variable_set('drupal_js_cache_files', $map);
5116
  }
5117
  return $uri;
5118
}
5119

    
5120
/**
5121
 * Deletes old cached JavaScript files and variables.
5122
 */
5123
function drupal_clear_js_cache() {
5124
  variable_del('javascript_parsed');
5125
  variable_del('drupal_js_cache_files');
5126
  file_scan_directory('public://js', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
5127
}
5128

    
5129
/**
5130
 * Converts a PHP variable into its JavaScript equivalent.
5131
 *
5132
 * We use HTML-safe strings, with several characters escaped.
5133
 *
5134
 * @see drupal_json_decode()
5135
 * @see drupal_json_encode_helper()
5136
 * @ingroup php_wrappers
5137
 */
5138
function drupal_json_encode($var) {
5139
  // The PHP version cannot change within a request.
5140
  static $php530;
5141

    
5142
  if (!isset($php530)) {
5143
    $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
5144
  }
5145

    
5146
  if ($php530) {
5147
    // Encode <, >, ', &, and " using the json_encode() options parameter.
5148
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
5149
  }
5150

    
5151
  // json_encode() escapes <, >, ', &, and " using its options parameter, but
5152
  // does not support this parameter prior to PHP 5.3.0.  Use a helper instead.
5153
  include_once DRUPAL_ROOT . '/includes/json-encode.inc';
5154
  return drupal_json_encode_helper($var);
5155
}
5156

    
5157
/**
5158
 * Converts an HTML-safe JSON string into its PHP equivalent.
5159
 *
5160
 * @see drupal_json_encode()
5161
 * @ingroup php_wrappers
5162
 */
5163
function drupal_json_decode($var) {
5164
  return json_decode($var, TRUE);
5165
}
5166

    
5167
/**
5168
 * Returns data in JSON format.
5169
 *
5170
 * This function should be used for JavaScript callback functions returning
5171
 * data in JSON format. It sets the header for JavaScript output.
5172
 *
5173
 * @param $var
5174
 *   (optional) If set, the variable will be converted to JSON and output.
5175
 */
5176
function drupal_json_output($var = NULL) {
5177
  // We are returning JSON, so tell the browser.
5178
  drupal_add_http_header('Content-Type', 'application/json');
5179

    
5180
  if (isset($var)) {
5181
    echo drupal_json_encode($var);
5182
  }
5183
}
5184

    
5185
/**
5186
 * Ensures the private key variable used to generate tokens is set.
5187
 *
5188
 * @return
5189
 *   The private key.
5190
 */
5191
function drupal_get_private_key() {
5192
  if (!($key = variable_get('drupal_private_key', 0))) {
5193
    $key = drupal_random_key();
5194
    variable_set('drupal_private_key', $key);
5195
  }
5196
  return $key;
5197
}
5198

    
5199
/**
5200
 * Generates a token based on $value, the user session, and the private key.
5201
 *
5202
 * @param $value
5203
 *   An additional value to base the token on.
5204
 *
5205
 * The generated token is based on the session ID of the current user. Normally,
5206
 * anonymous users do not have a session, so the generated token will be
5207
 * different on every page request. To generate a token for users without a
5208
 * session, manually start a session prior to calling this function.
5209
 *
5210
 * @return string
5211
 *   A 43-character URL-safe token for validation, based on the user session ID,
5212
 *   the hash salt provided from drupal_get_hash_salt(), and the
5213
 *   'drupal_private_key' configuration variable.
5214
 *
5215
 * @see drupal_get_hash_salt()
5216
 */
5217
function drupal_get_token($value = '') {
5218
  return drupal_hmac_base64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());
5219
}
5220

    
5221
/**
5222
 * Validates a token based on $value, the user session, and the private key.
5223
 *
5224
 * @param $token
5225
 *   The token to be validated.
5226
 * @param $value
5227
 *   An additional value to base the token on.
5228
 * @param $skip_anonymous
5229
 *   Set to true to skip token validation for anonymous users.
5230
 *
5231
 * @return
5232
 *   True for a valid token, false for an invalid token. When $skip_anonymous
5233
 *   is true, the return value will always be true for anonymous users.
5234
 */
5235
function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
5236
  global $user;
5237
  return (($skip_anonymous && $user->uid == 0) || ($token === drupal_get_token($value)));
5238
}
5239

    
5240
function _drupal_bootstrap_full() {
5241
  static $called = FALSE;
5242

    
5243
  if ($called) {
5244
    return;
5245
  }
5246
  $called = TRUE;
5247
  require_once DRUPAL_ROOT . '/' . variable_get('path_inc', 'includes/path.inc');
5248
  require_once DRUPAL_ROOT . '/includes/theme.inc';
5249
  require_once DRUPAL_ROOT . '/includes/pager.inc';
5250
  require_once DRUPAL_ROOT . '/' . variable_get('menu_inc', 'includes/menu.inc');
5251
  require_once DRUPAL_ROOT . '/includes/tablesort.inc';
5252
  require_once DRUPAL_ROOT . '/includes/file.inc';
5253
  require_once DRUPAL_ROOT . '/includes/unicode.inc';
5254
  require_once DRUPAL_ROOT . '/includes/image.inc';
5255
  require_once DRUPAL_ROOT . '/includes/form.inc';
5256
  require_once DRUPAL_ROOT . '/includes/mail.inc';
5257
  require_once DRUPAL_ROOT . '/includes/actions.inc';
5258
  require_once DRUPAL_ROOT . '/includes/ajax.inc';
5259
  require_once DRUPAL_ROOT . '/includes/token.inc';
5260
  require_once DRUPAL_ROOT . '/includes/errors.inc';
5261

    
5262
  // Detect string handling method
5263
  unicode_check();
5264
  // Undo magic quotes
5265
  fix_gpc_magic();
5266
  // Load all enabled modules
5267
  module_load_all();
5268
  // Reset drupal_alter() and module_implements() static caches as these
5269
  // include implementations for vital modules only when called early on
5270
  // in the bootstrap.
5271
  drupal_static_reset('drupal_alter');
5272
  drupal_static_reset('module_implements');
5273
  // Make sure all stream wrappers are registered.
5274
  file_get_stream_wrappers();
5275
  // Ensure mt_rand is reseeded, to prevent random values from one page load
5276
  // being exploited to predict random values in subsequent page loads.
5277
  $seed = unpack("L", drupal_random_bytes(4));
5278
  mt_srand($seed[1]);
5279

    
5280
  $test_info = &$GLOBALS['drupal_test_info'];
5281
  if (!empty($test_info['in_child_site'])) {
5282
    // Running inside the simpletest child site, log fatal errors to test
5283
    // specific file directory.
5284
    ini_set('log_errors', 1);
5285
    ini_set('error_log', 'public://error.log');
5286
  }
5287

    
5288
  // Initialize $_GET['q'] prior to invoking hook_init().
5289
  drupal_path_initialize();
5290

    
5291
  // Let all modules take action before the menu system handles the request.
5292
  // We do not want this while running update.php.
5293
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
5294
    // Prior to invoking hook_init(), initialize the theme (potentially a custom
5295
    // one for this page), so that:
5296
    // - Modules with hook_init() implementations that call theme() or
5297
    //   theme_get_registry() don't initialize the incorrect theme.
5298
    // - The theme can have hook_*_alter() implementations affect page building
5299
    //   (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
5300
    //   ahead of when rendering starts.
5301
    menu_set_custom_theme();
5302
    drupal_theme_initialize();
5303
    module_invoke_all('init');
5304
  }
5305
}
5306

    
5307
/**
5308
 * Stores the current page in the cache.
5309
 *
5310
 * If page_compression is enabled, a gzipped version of the page is stored in
5311
 * the cache to avoid compressing the output on each request. The cache entry
5312
 * is unzipped in the relatively rare event that the page is requested by a
5313
 * client without gzip support.
5314
 *
5315
 * Page compression requires the PHP zlib extension
5316
 * (http://php.net/manual/ref.zlib.php).
5317
 *
5318
 * @see drupal_page_header()
5319
 */
5320
function drupal_page_set_cache() {
5321
  global $base_root;
5322

    
5323
  if (drupal_page_is_cacheable()) {
5324

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

    
5328
    $cache = (object) array(
5329
      'cid' => $base_root . request_uri(),
5330
      'data' => array(
5331
        'path' => $_GET['q'],
5332
        'body' => ob_get_clean(),
5333
        'title' => drupal_get_title(),
5334
        'headers' => array(),
5335
        // We need to store whether page was compressed or not,
5336
        // because by the time it is read, the configuration might change.
5337
        'page_compressed' => $page_compressed,
5338
      ),
5339
      'expire' => CACHE_TEMPORARY,
5340
      'created' => REQUEST_TIME,
5341
    );
5342

    
5343
    // Restore preferred header names based on the lower-case names returned
5344
    // by drupal_get_http_header().
5345
    $header_names = _drupal_set_preferred_header_name();
5346
    foreach (drupal_get_http_header() as $name_lower => $value) {
5347
      $cache->data['headers'][$header_names[$name_lower]] = $value;
5348
      if ($name_lower == 'expires') {
5349
        // Use the actual timestamp from an Expires header if available.
5350
        $cache->expire = strtotime($value);
5351
      }
5352
    }
5353

    
5354
    if ($cache->data['body']) {
5355
      if ($page_compressed) {
5356
        $cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
5357
      }
5358
      cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire);
5359
    }
5360
    return $cache;
5361
  }
5362
}
5363

    
5364
/**
5365
 * Executes a cron run when called.
5366
 *
5367
 * Do not call this function from a test. Use $this->cronRun() instead.
5368
 *
5369
 * @return bool
5370
 *   TRUE if cron ran successfully and FALSE if cron is already running.
5371
 */
5372
function drupal_cron_run() {
5373
  // Allow execution to continue even if the request gets canceled.
5374
  @ignore_user_abort(TRUE);
5375

    
5376
  // Prevent session information from being saved while cron is running.
5377
  $original_session_saving = drupal_save_session();
5378
  drupal_save_session(FALSE);
5379

    
5380
  // Force the current user to anonymous to ensure consistent permissions on
5381
  // cron runs.
5382
  $original_user = $GLOBALS['user'];
5383
  $GLOBALS['user'] = drupal_anonymous_user();
5384

    
5385
  // Try to allocate enough time to run all the hook_cron implementations.
5386
  drupal_set_time_limit(240);
5387

    
5388
  $return = FALSE;
5389
  // Grab the defined cron queues.
5390
  $queues = module_invoke_all('cron_queue_info');
5391
  drupal_alter('cron_queue_info', $queues);
5392

    
5393
  // Try to acquire cron lock.
5394
  if (!lock_acquire('cron', 240.0)) {
5395
    // Cron is still running normally.
5396
    watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
5397
  }
5398
  else {
5399
    // Make sure every queue exists. There is no harm in trying to recreate an
5400
    // existing queue.
5401
    foreach ($queues as $queue_name => $info) {
5402
      DrupalQueue::get($queue_name)->createQueue();
5403
    }
5404

    
5405
    // Iterate through the modules calling their cron handlers (if any):
5406
    foreach (module_implements('cron') as $module) {
5407
      // Do not let an exception thrown by one module disturb another.
5408
      try {
5409
        module_invoke($module, 'cron');
5410
      }
5411
      catch (Exception $e) {
5412
        watchdog_exception('cron', $e);
5413
      }
5414
    }
5415

    
5416
    // Record cron time.
5417
    variable_set('cron_last', REQUEST_TIME);
5418
    watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
5419

    
5420
    // Release cron lock.
5421
    lock_release('cron');
5422

    
5423
    // Return TRUE so other functions can check if it did run successfully
5424
    $return = TRUE;
5425
  }
5426

    
5427
  foreach ($queues as $queue_name => $info) {
5428
    if (!empty($info['skip on cron'])) {
5429
      // Do not run if queue wants to skip.
5430
      continue;
5431
    }
5432
    $callback = $info['worker callback'];
5433
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
5434
    $queue = DrupalQueue::get($queue_name);
5435
    while (time() < $end && ($item = $queue->claimItem())) {
5436
      try {
5437
        call_user_func($callback, $item->data);
5438
        $queue->deleteItem($item);
5439
      }
5440
      catch (Exception $e) {
5441
        // In case of exception log it and leave the item in the queue
5442
        // to be processed again later.
5443
        watchdog_exception('cron', $e);
5444
      }
5445
    }
5446
  }
5447
  // Restore the user.
5448
  $GLOBALS['user'] = $original_user;
5449
  drupal_save_session($original_session_saving);
5450

    
5451
  return $return;
5452
}
5453

    
5454
/**
5455
 * DEPRECATED: Shutdown function: Performs cron cleanup.
5456
 *
5457
 * This function is deprecated because the 'cron_semaphore' variable it
5458
 * references no longer exists. It is therefore no longer used as a shutdown
5459
 * function by Drupal core.
5460
 *
5461
 * @deprecated
5462
 */
5463
function drupal_cron_cleanup() {
5464