Projet

Général

Profil

Paste
Télécharger (305 ko) Statistiques
| Branche: | Révision:

root / drupal7 / includes / common.inc @ 7c856df4

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&...'. Defaults to NULL.
764
 *   - max_redirects: An integer representing how many times a redirect
765
 *     may be followed. Defaults to 3.
766
 *   - timeout: A float representing the maximum number of seconds the function
767
 *     call may take. The default is 30 seconds. If a timeout occurs, the error
768
 *     code is set to the HTTP_REQUEST_TIMEOUT constant.
769
 *   - context: A context resource created with stream_context_create().
770
 *
771
 * @return object
772
 *   An object that can have one or more of the following components:
773
 *   - request: A string containing the request body that was sent.
774
 *   - code: An integer containing the response status code, or the error code
775
 *     if an error occurred.
776
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
777
 *   - status_message: The status message from the response, if a response was
778
 *     received.
779
 *   - redirect_code: If redirected, an integer containing the initial response
780
 *     status code.
781
 *   - redirect_url: If redirected, a string containing the URL of the redirect
782
 *     target.
783
 *   - error: If an error occurred, the error message. Otherwise not set.
784
 *   - headers: An array containing the response headers as name/value pairs.
785
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
786
 *     easy access the array keys are returned in lower case.
787
 *   - data: A string containing the response body that was received.
788
 */
789
function drupal_http_request($url, array $options = array()) {
790
  // Allow an alternate HTTP client library to replace Drupal's default
791
  // implementation.
792
  $override_function = variable_get('drupal_http_request_function', FALSE);
793
  if (!empty($override_function) && function_exists($override_function)) {
794
    return $override_function($url, $options);
795
  }
796

    
797
  $result = new stdClass();
798

    
799
  // Parse the URL and make sure we can handle the schema.
800
  $uri = @parse_url($url);
801

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

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

    
814
  timer_start(__FUNCTION__);
815

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

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

    
831
  // stream_socket_client() requires timeout to be a float.
832
  $options['timeout'] = (float) $options['timeout'];
833

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

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

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

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

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

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

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

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

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

    
914
    return $result;
915
  }
916

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

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

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

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

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

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

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

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

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

    
1000
  $result->headers = array();
1001

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

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

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

    
1098
  return $result;
1099
}
1100

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

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

    
1143
/**
1144
 * @} End of "HTTP handling".
1145
 */
1146

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

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

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

    
1208
/**
1209
 * @defgroup validation Input validation
1210
 * @{
1211
 * Functions to validate user input.
1212
 */
1213

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

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

    
1268
/**
1269
 * @} End of "defgroup validation".
1270
 */
1271

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

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

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

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

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

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

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

    
1408
  return $uri;
1409
}
1410

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

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

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

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

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

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

    
1522
  if ($store) {
1523
    $allowed_html = array_flip($m);
1524
    return;
1525
  }
1526

    
1527
  $string = $m[1];
1528

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

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

    
1543
  $slash = trim($matches[1]);
1544
  $elem = &$matches[2];
1545
  $attrlist = &$matches[3];
1546
  $comment = &$matches[4];
1547

    
1548
  if ($comment) {
1549
    $elem = '!--';
1550
  }
1551

    
1552
  if (!isset($allowed_html[strtolower($elem)])) {
1553
    // Disallowed HTML element.
1554
    return '';
1555
  }
1556

    
1557
  if ($comment) {
1558
    return $comment;
1559
  }
1560

    
1561
  if ($slash != '') {
1562
    return "</$elem>";
1563
  }
1564

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

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

    
1574
  return "<$elem$attr2$xhtml_slash>";
1575
}
1576

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

    
1588
  while (strlen($attr) != 0) {
1589
    // Was the last operation successful?
1590
    $working = 0;
1591

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

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

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

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

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

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

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

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

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

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

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

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

    
1704
    $string = decode_entities($string);
1705
  }
1706
  return check_plain(drupal_strip_dangerous_protocols($string));
1707
}
1708

    
1709
/**
1710
 * @} End of "defgroup sanitization".
1711
 */
1712

    
1713
/**
1714
 * @defgroup format Formatting
1715
 * @{
1716
 * Functions to format numbers, strings, dates, etc.
1717
 */
1718

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

    
1728
  $output = "<channel>\n";
1729
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1730
  $output .= ' <link>' . check_url($link) . "</link>\n";
1731

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

    
1741
  return $output;
1742
}
1743

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

    
1757
  return $output;
1758
}
1759

    
1760
/**
1761
 * Formats XML elements.
1762
 *
1763
 * @param $array
1764
 *   An array where each item represents an element and is either a:
1765
 *   - (key => value) pair (<key>value</key>)
1766
 *   - Associative array with fields:
1767
 *     - 'key': element name
1768
 *     - 'value': element contents
1769
 *     - 'attributes': associative array of element attributes
1770
 *
1771
 * In both cases, 'value' can be a simple string, or it can be another array
1772
 * with the same format as $array itself for nesting.
1773
 */
1774
function format_xml_elements($array) {
1775
  $output = '';
1776
  foreach ($array as $key => $value) {
1777
    if (is_numeric($key)) {
1778
      if ($value['key']) {
1779
        $output .= ' <' . $value['key'];
1780
        if (isset($value['attributes']) && is_array($value['attributes'])) {
1781
          $output .= drupal_attributes($value['attributes']);
1782
        }
1783

    
1784
        if (isset($value['value']) && $value['value'] != '') {
1785
          $output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) . '</' . $value['key'] . ">\n";
1786
        }
1787
        else {
1788
          $output .= " />\n";
1789
        }
1790
      }
1791
    }
1792
    else {
1793
      $output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</$key>\n";
1794
    }
1795
  }
1796
  return $output;
1797
}
1798

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

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

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

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

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

    
1966
    if ($granularity == 0) {
1967
      break;
1968
    }
1969
  }
1970
  return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
1971
}
1972

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

    
2009
  if (!isset($timezone)) {
2010
    $timezone = date_default_timezone_get();
2011
  }
2012
  // Store DateTimeZone objects in an array rather than repeatedly
2013
  // constructing identical objects over the life of a request.
2014
  if (!isset($timezones[$timezone])) {
2015
    $timezones[$timezone] = timezone_open($timezone);
2016
  }
2017

    
2018
  // Use the default langcode if none is set.
2019
  global $language;
2020
  if (empty($langcode)) {
2021
    $langcode = isset($language->language) ? $language->language : 'en';
2022
  }
2023

    
2024
  switch ($type) {
2025
    case 'short':
2026
      $format = variable_get('date_format_short', 'm/d/Y - H:i');
2027
      break;
2028

    
2029
    case 'long':
2030
      $format = variable_get('date_format_long', 'l, F j, Y - H:i');
2031
      break;
2032

    
2033
    case 'custom':
2034
      // No change to format.
2035
      break;
2036

    
2037
    case 'medium':
2038
    default:
2039
      // Retrieve the format of the custom $type passed.
2040
      if ($type != 'medium') {
2041
        $format = variable_get('date_format_' . $type, '');
2042
      }
2043
      // Fall back to 'medium'.
2044
      if ($format === '') {
2045
        $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
2046
      }
2047
      break;
2048
  }
2049

    
2050
  // Create a DateTime object from the timestamp.
2051
  $date_time = date_create('@' . $timestamp);
2052
  // Set the time zone for the DateTime object.
2053
  date_timezone_set($date_time, $timezones[$timezone]);
2054

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

    
2062
  // Call date_format().
2063
  $format = date_format($date_time, $format);
2064

    
2065
  // Pass the langcode to _format_date_callback().
2066
  _format_date_callback(NULL, $langcode);
2067

    
2068
  // Translate the marked sequences.
2069
  return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);
2070
}
2071

    
2072
/**
2073
 * Returns an ISO8601 formatted date based on the given date.
2074
 *
2075
 * Callback for use within hook_rdf_mapping() implementations.
2076
 *
2077
 * @param $date
2078
 *   A UNIX timestamp.
2079
 *
2080
 * @return string
2081
 *   An ISO8601 formatted date.
2082
 */
2083
function date_iso8601($date) {
2084
  // The DATE_ISO8601 constant cannot be used here because it does not match
2085
  // date('c') and produces invalid RDF markup.
2086
  return date('c', $date);
2087
}
2088

    
2089
/**
2090
 * Translates a formatted date string.
2091
 *
2092
 * Callback for preg_replace_callback() within format_date().
2093
 */
2094
function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
2095
  // We cache translations to avoid redundant and rather costly calls to t().
2096
  static $cache, $langcode;
2097

    
2098
  if (!isset($matches)) {
2099
    $langcode = $new_langcode;
2100
    return;
2101
  }
2102

    
2103
  $code = $matches[1];
2104
  $string = $matches[2];
2105

    
2106
  if (!isset($cache[$langcode][$code][$string])) {
2107
    $options = array(
2108
      'langcode' => $langcode,
2109
    );
2110

    
2111
    if ($code == 'F') {
2112
      $options['context'] = 'Long month name';
2113
    }
2114

    
2115
    if ($code == '') {
2116
      $cache[$langcode][$code][$string] = $string;
2117
    }
2118
    else {
2119
      $cache[$langcode][$code][$string] = t($string, array(), $options);
2120
    }
2121
  }
2122
  return $cache[$langcode][$code][$string];
2123
}
2124

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

    
2151
/**
2152
 * @} End of "defgroup format".
2153
 */
2154

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

    
2230
  if (!isset($options['external'])) {
2231
    $options['external'] = url_is_external($path);
2232
  }
2233

    
2234
  // Preserve the original path before altering or aliasing.
2235
  $original_path = $path;
2236

    
2237
  // Allow other modules to alter the outbound URL and options.
2238
  drupal_alter('url_outbound', $path, $options, $original_path);
2239

    
2240
  if (isset($options['fragment']) && $options['fragment'] !== '') {
2241
    $options['fragment'] = '#' . $options['fragment'];
2242
  }
2243

    
2244
  if ($options['external']) {
2245
    // Split off the fragment.
2246
    if (strpos($path, '#') !== FALSE) {
2247
      list($path, $old_fragment) = explode('#', $path, 2);
2248
      // If $options contains no fragment, take it over from the path.
2249
      if (isset($old_fragment) && !$options['fragment']) {
2250
        $options['fragment'] = '#' . $old_fragment;
2251
      }
2252
    }
2253
    // Append the query.
2254
    if ($options['query']) {
2255
      $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($options['query']);
2256
    }
2257
    if (isset($options['https']) && variable_get('https', FALSE)) {
2258
      if ($options['https'] === TRUE) {
2259
        $path = str_replace('http://', 'https://', $path);
2260
      }
2261
      elseif ($options['https'] === FALSE) {
2262
        $path = str_replace('https://', 'http://', $path);
2263
      }
2264
    }
2265
    // Reassemble.
2266
    return $path . $options['fragment'];
2267
  }
2268

    
2269
  // Strip leading slashes from internal paths to prevent them becoming external
2270
  // URLs without protocol. /example.com should not be turned into
2271
  // //example.com.
2272
  $path = ltrim($path, '/');
2273

    
2274
  global $base_url, $base_secure_url, $base_insecure_url;
2275

    
2276
  // The base_url might be rewritten from the language rewrite in domain mode.
2277
  if (!isset($options['base_url'])) {
2278
    if (isset($options['https']) && variable_get('https', FALSE)) {
2279
      if ($options['https'] === TRUE) {
2280
        $options['base_url'] = $base_secure_url;
2281
        $options['absolute'] = TRUE;
2282
      }
2283
      elseif ($options['https'] === FALSE) {
2284
        $options['base_url'] = $base_insecure_url;
2285
        $options['absolute'] = TRUE;
2286
      }
2287
    }
2288
    else {
2289
      $options['base_url'] = $base_url;
2290
    }
2291
  }
2292

    
2293
  // The special path '<front>' links to the default front page.
2294
  if ($path == '<front>') {
2295
    $path = '';
2296
  }
2297
  elseif (!empty($path) && !$options['alias']) {
2298
    $language = isset($options['language']) && isset($options['language']->language) ? $options['language']->language : '';
2299
    $alias = drupal_get_path_alias($original_path, $language);
2300
    if ($alias != $original_path) {
2301
      $path = $alias;
2302
    }
2303
  }
2304

    
2305
  $base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
2306
  $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
2307

    
2308
  // With Clean URLs.
2309
  if (!empty($GLOBALS['conf']['clean_url'])) {
2310
    $path = drupal_encode_path($prefix . $path);
2311
    if ($options['query']) {
2312
      return $base . $path . '?' . drupal_http_build_query($options['query']) . $options['fragment'];
2313
    }
2314
    else {
2315
      return $base . $path . $options['fragment'];
2316
    }
2317
  }
2318
  // Without Clean URLs.
2319
  else {
2320
    $path = $prefix . $path;
2321
    $query = array();
2322
    if (!empty($path)) {
2323
      $query['q'] = $path;
2324
    }
2325
    if ($options['query']) {
2326
      // We do not use array_merge() here to prevent overriding $path via query
2327
      // parameters.
2328
      $query += $options['query'];
2329
    }
2330
    $query = $query ? ('?' . drupal_http_build_query($query)) : '';
2331
    $script = isset($options['script']) ? $options['script'] : '';
2332
    return $base . $script . $query . $options['fragment'];
2333
  }
2334
}
2335

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

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

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

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

    
2485
  // Merge in defaults.
2486
  $options += array(
2487
    'attributes' => array(),
2488
    'html' => FALSE,
2489
  );
2490

    
2491
  // Append active class.
2492
  if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
2493
      (empty($options['language']) || $options['language']->language == $language_url->language)) {
2494
    $options['attributes']['class'][] = 'active';
2495
  }
2496

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

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

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

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

    
2643
  // Send appropriate HTTP-Header for browsers and search engines.
2644
  global $language;
2645
  drupal_add_http_header('Content-Language', $language->language);
2646

    
2647
  // Menu status constants are integers; page content is a string or array.
2648
  if (is_int($page_callback_result)) {
2649
    // @todo: Break these up into separate functions?
2650
    switch ($page_callback_result) {
2651
      case MENU_NOT_FOUND:
2652
        // Print a 404 page.
2653
        drupal_add_http_header('Status', '404 Not Found');
2654

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

    
2657
        // Check for and return a fast 404 page if configured.
2658
        drupal_fast_404();
2659

    
2660
        // Keep old path for reference, and to allow forms to redirect to it.
2661
        if (!isset($_GET['destination'])) {
2662
          // Make sure that the current path is not interpreted as external URL.
2663
          if (!url_is_external($_GET['q'])) {
2664
            $_GET['destination'] = $_GET['q'];
2665
          }
2666
        }
2667

    
2668
        $path = drupal_get_normal_path(variable_get('site_404', ''));
2669
        if ($path && $path != $_GET['q']) {
2670
          // Custom 404 handler. Set the active item in case there are tabs to
2671
          // display, or other dependencies on the path.
2672
          menu_set_active_item($path);
2673
          $return = menu_execute_active_handler($path, FALSE);
2674
        }
2675

    
2676
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2677
          // Standard 404 handler.
2678
          drupal_set_title(t('Page not found'));
2679
          $return = t('The requested page "@path" could not be found.', array('@path' => request_uri()));
2680
        }
2681

    
2682
        drupal_set_page_content($return);
2683
        $page = element_info('page');
2684
        print drupal_render_page($page);
2685
        break;
2686

    
2687
      case MENU_ACCESS_DENIED:
2688
        // Print a 403 page.
2689
        drupal_add_http_header('Status', '403 Forbidden');
2690
        watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
2691

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

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

    
2708
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2709
          // Standard 403 handler.
2710
          drupal_set_title(t('Access denied'));
2711
          $return = t('You are not authorized to access this page.');
2712
        }
2713

    
2714
        print drupal_render_page($return);
2715
        break;
2716

    
2717
      case MENU_SITE_OFFLINE:
2718
        // Print a 503 page.
2719
        drupal_maintenance_theme();
2720
        drupal_add_http_header('Status', '503 Service unavailable');
2721
        drupal_set_title(t('Site under maintenance'));
2722
        print theme('maintenance_page', array('content' => filter_xss_admin(variable_get('maintenance_mode_message',
2723
          t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))))));
2724
        break;
2725
    }
2726
  }
2727
  elseif (isset($page_callback_result)) {
2728
    // Print anything besides a menu constant, assuming it's not NULL or
2729
    // undefined.
2730
    print drupal_render_page($page_callback_result);
2731
  }
2732

    
2733
  // Perform end-of-request tasks.
2734
  drupal_page_footer();
2735
}
2736

    
2737
/**
2738
 * Performs end-of-request tasks.
2739
 *
2740
 * This function sets the page cache if appropriate, and allows modules to
2741
 * react to the closing of the page by calling hook_exit().
2742
 */
2743
function drupal_page_footer() {
2744
  global $user;
2745

    
2746
  module_invoke_all('exit');
2747

    
2748
  // Commit the user session, if needed.
2749
  drupal_session_commit();
2750

    
2751
  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
2752
    drupal_serve_page_from_cache($cache);
2753
  }
2754
  else {
2755
    ob_flush();
2756
  }
2757

    
2758
  _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
2759
  drupal_cache_system_paths();
2760
  module_implements_write_cache();
2761
  system_run_automated_cron();
2762
}
2763

    
2764
/**
2765
 * Performs end-of-request tasks.
2766
 *
2767
 * In some cases page requests need to end without calling drupal_page_footer().
2768
 * In these cases, call drupal_exit() instead. There should rarely be a reason
2769
 * to call exit instead of drupal_exit();
2770
 *
2771
 * @param $destination
2772
 *   If this function is called from drupal_goto(), then this argument
2773
 *   will be a fully-qualified URL that is the destination of the redirect.
2774
 *   This should be passed along to hook_exit() implementations.
2775
 */
2776
function drupal_exit($destination = NULL) {
2777
  if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL) {
2778
    if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
2779
      module_invoke_all('exit', $destination);
2780
    }
2781
    drupal_session_commit();
2782
  }
2783
  exit;
2784
}
2785

    
2786
/**
2787
 * Forms an associative array from a linear array.
2788
 *
2789
 * This function walks through the provided array and constructs an associative
2790
 * array out of it. The keys of the resulting array will be the values of the
2791
 * input array. The values will be the same as the keys unless a function is
2792
 * specified, in which case the output of the function is used for the values
2793
 * instead.
2794
 *
2795
 * @param $array
2796
 *   A linear array.
2797
 * @param $function
2798
 *   A name of a function to apply to all values before output.
2799
 *
2800
 * @return
2801
 *   An associative array.
2802
 */
2803
function drupal_map_assoc($array, $function = NULL) {
2804
  // array_combine() fails with empty arrays:
2805
  // http://bugs.php.net/bug.php?id=34857.
2806
  $array = !empty($array) ? array_combine($array, $array) : array();
2807
  if (is_callable($function)) {
2808
    $array = array_map($function, $array);
2809
  }
2810
  return $array;
2811
}
2812

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

    
2851
/**
2852
 * Returns the path to a system item (module, theme, etc.).
2853
 *
2854
 * @param $type
2855
 *   The type of the item (i.e. theme, theme_engine, module, profile).
2856
 * @param $name
2857
 *   The name of the item for which the path is requested.
2858
 *
2859
 * @return
2860
 *   The path to the requested item or an empty string if the item is not found.
2861
 */
2862
function drupal_get_path($type, $name) {
2863
  return dirname(drupal_get_filename($type, $name));
2864
}
2865

    
2866
/**
2867
 * Returns the base URL path (i.e., directory) of the Drupal installation.
2868
 *
2869
 * base_path() adds a "/" to the beginning and end of the returned path if the
2870
 * path is not empty. At the very least, this will return "/".
2871
 *
2872
 * Examples:
2873
 * - http://example.com returns "/" because the path is empty.
2874
 * - http://example.com/drupal/folder returns "/drupal/folder/".
2875
 */
2876
function base_path() {
2877
  return $GLOBALS['base_path'];
2878
}
2879

    
2880
/**
2881
 * Adds a LINK tag with a distinct 'rel' attribute to the page's HEAD.
2882
 *
2883
 * This function can be called as long the HTML header hasn't been sent, which
2884
 * on normal pages is up through the preprocess step of theme('html'). Adding
2885
 * a link will overwrite a prior link with the exact same 'rel' and 'href'
2886
 * attributes.
2887
 *
2888
 * @param $attributes
2889
 *   Associative array of element attributes including 'href' and 'rel'.
2890
 * @param $header
2891
 *   Optional flag to determine if a HTTP 'Link:' header should be sent.
2892
 */
2893
function drupal_add_html_head_link($attributes, $header = FALSE) {
2894
  $element = array(
2895
    '#tag' => 'link',
2896
    '#attributes' => $attributes,
2897
  );
2898
  $href = $attributes['href'];
2899

    
2900
  if ($header) {
2901
    // Also add a HTTP header "Link:".
2902
    $href = '<' . check_plain($attributes['href']) . '>;';
2903
    unset($attributes['href']);
2904
    $element['#attached']['drupal_add_http_header'][] = array('Link',  $href . drupal_http_header_attributes($attributes), TRUE);
2905
  }
2906

    
2907
  drupal_add_html_head($element, 'drupal_add_html_head_link:' . $attributes['rel'] . ':' . $href);
2908
}
2909

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

    
3029
  // Construct the options, taking the defaults into consideration.
3030
  if (isset($options)) {
3031
    if (!is_array($options)) {
3032
      $options = array('type' => $options);
3033
    }
3034
  }
3035
  else {
3036
    $options = array();
3037
  }
3038

    
3039
  // Create an array of CSS files for each media type first, since each type needs to be served
3040
  // to the browser differently.
3041
  if (isset($data)) {
3042
    $options += array(
3043
      'type' => 'file',
3044
      'group' => CSS_DEFAULT,
3045
      'weight' => 0,
3046
      'every_page' => FALSE,
3047
      'media' => 'all',
3048
      'preprocess' => TRUE,
3049
      'data' => $data,
3050
      'browsers' => array(),
3051
    );
3052
    $options['browsers'] += array(
3053
      'IE' => TRUE,
3054
      '!IE' => TRUE,
3055
    );
3056

    
3057
    // Files with a query string cannot be preprocessed.
3058
    if ($options['type'] === 'file' && $options['preprocess'] && strpos($options['data'], '?') !== FALSE) {
3059
      $options['preprocess'] = FALSE;
3060
    }
3061

    
3062
    // Always add a tiny value to the weight, to conserve the insertion order.
3063
    $options['weight'] += count($css) / 1000;
3064

    
3065
    // Add the data to the CSS array depending on the type.
3066
    switch ($options['type']) {
3067
      case 'inline':
3068
        // For inline stylesheets, we don't want to use the $data as the array
3069
        // key as $data could be a very long string of CSS.
3070
        $css[] = $options;
3071
        break;
3072
      default:
3073
        // Local and external files must keep their name as the associative key
3074
        // so the same CSS file is not be added twice.
3075
        $css[$data] = $options;
3076
    }
3077
  }
3078

    
3079
  return $css;
3080
}
3081

    
3082
/**
3083
 * Returns a themed representation of all stylesheets to attach to the page.
3084
 *
3085
 * It loads the CSS in order, with 'module' first, then 'theme' afterwards.
3086
 * This ensures proper cascading of styles so themes can easily override
3087
 * module styles through CSS selectors.
3088
 *
3089
 * Themes may replace module-defined CSS files by adding a stylesheet with the
3090
 * same filename. For example, themes/bartik/system-menus.css would replace
3091
 * modules/system/system-menus.css. This allows themes to override complete
3092
 * CSS files, rather than specific selectors, when necessary.
3093
 *
3094
 * If the original CSS file is being overridden by a theme, the theme is
3095
 * responsible for supplying an accompanying RTL CSS file to replace the
3096
 * module's.
3097
 *
3098
 * @param $css
3099
 *   (optional) An array of CSS files. If no array is provided, the default
3100
 *   stylesheets array is used instead.
3101
 * @param $skip_alter
3102
 *   (optional) If set to TRUE, this function skips calling drupal_alter() on
3103
 *   $css, useful when the calling function passes a $css array that has already
3104
 *   been altered.
3105
 *
3106
 * @return
3107
 *   A string of XHTML CSS tags.
3108
 *
3109
 * @see drupal_add_css()
3110
 */
3111
function drupal_get_css($css = NULL, $skip_alter = FALSE) {
3112
  if (!isset($css)) {
3113
    $css = drupal_add_css();
3114
  }
3115

    
3116
  // Allow modules and themes to alter the CSS items.
3117
  if (!$skip_alter) {
3118
    drupal_alter('css', $css);
3119
  }
3120

    
3121
  // Sort CSS items, so that they appear in the correct order.
3122
  uasort($css, 'drupal_sort_css_js');
3123

    
3124
  // Provide the page with information about the individual CSS files used,
3125
  // information not otherwise available when CSS aggregation is enabled. The
3126
  // setting is attached later in this function, but is set here, so that CSS
3127
  // files removed below are still considered "used" and prevented from being
3128
  // added in a later AJAX request.
3129
  // Skip if no files were added to the page or jQuery.extend() will overwrite
3130
  // the Drupal.settings.ajaxPageState.css object with an empty array.
3131
  if (!empty($css)) {
3132
    // Cast the array to an object to be on the safe side even if not empty.
3133
    $setting['ajaxPageState']['css'] = (object) array_fill_keys(array_keys($css), 1);
3134
  }
3135

    
3136
  // Remove the overridden CSS files. Later CSS files override former ones.
3137
  $previous_item = array();
3138
  foreach ($css as $key => $item) {
3139
    if ($item['type'] == 'file') {
3140
      // If defined, force a unique basename for this file.
3141
      $basename = isset($item['basename']) ? $item['basename'] : drupal_basename($item['data']);
3142
      if (isset($previous_item[$basename])) {
3143
        // Remove the previous item that shared the same base name.
3144
        unset($css[$previous_item[$basename]]);
3145
      }
3146
      $previous_item[$basename] = $key;
3147
    }
3148
  }
3149

    
3150
  // Render the HTML needed to load the CSS.
3151
  $styles = array(
3152
    '#type' => 'styles',
3153
    '#items' => $css,
3154
  );
3155

    
3156
  if (!empty($setting)) {
3157
    $styles['#attached']['js'][] = array('type' => 'setting', 'data' => $setting);
3158
  }
3159

    
3160
  return drupal_render($styles);
3161
}
3162

    
3163
/**
3164
 * Sorts CSS and JavaScript resources.
3165
 *
3166
 * Callback for uasort() within:
3167
 * - drupal_get_css()
3168
 * - drupal_get_js()
3169
 *
3170
 * This sort order helps optimize front-end performance while providing modules
3171
 * and themes with the necessary control for ordering the CSS and JavaScript
3172
 * appearing on a page.
3173
 *
3174
 * @param $a
3175
 *   First item for comparison. The compared items should be associative arrays
3176
 *   of member items from drupal_add_css() or drupal_add_js().
3177
 * @param $b
3178
 *   Second item for comparison.
3179
 *
3180
 * @see drupal_add_css()
3181
 * @see drupal_add_js()
3182
 */
3183
function drupal_sort_css_js($a, $b) {
3184
  // First order by group, so that, for example, all items in the CSS_SYSTEM
3185
  // group appear before items in the CSS_DEFAULT group, which appear before
3186
  // all items in the CSS_THEME group. Modules may create additional groups by
3187
  // defining their own constants.
3188
  if ($a['group'] < $b['group']) {
3189
    return -1;
3190
  }
3191
  elseif ($a['group'] > $b['group']) {
3192
    return 1;
3193
  }
3194
  // Within a group, order all infrequently needed, page-specific files after
3195
  // common files needed throughout the website. Separating this way allows for
3196
  // the aggregate file generated for all of the common files to be reused
3197
  // across a site visit without being cut by a page using a less common file.
3198
  elseif ($a['every_page'] && !$b['every_page']) {
3199
    return -1;
3200
  }
3201
  elseif (!$a['every_page'] && $b['every_page']) {
3202
    return 1;
3203
  }
3204
  // Finally, order by weight.
3205
  elseif ($a['weight'] < $b['weight']) {
3206
    return -1;
3207
  }
3208
  elseif ($a['weight'] > $b['weight']) {
3209
    return 1;
3210
  }
3211
  else {
3212
    return 0;
3213
  }
3214
}
3215

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

    
3267
    // If the item can be grouped with other items, set $group_keys to an array
3268
    // of information that must be the same for all items in its group. If the
3269
    // item can't be grouped with other items, set $group_keys to FALSE. We
3270
    // put items into a group that can be aggregated together: whether they will
3271
    // be aggregated is up to the _drupal_css_aggregate() function or an
3272
    // override of that function specified in hook_css_alter(), but regardless
3273
    // of the details of that function, a group represents items that can be
3274
    // aggregated. Since a group may be rendered with a single HTML tag, all
3275
    // items in the group must share the same information that would need to be
3276
    // part of that HTML tag.
3277
    switch ($item['type']) {
3278
      case 'file':
3279
        // Group file items if their 'preprocess' flag is TRUE.
3280
        // Help ensure maximum reuse of aggregate files by only grouping
3281
        // together items that share the same 'group' value and 'every_page'
3282
        // flag. See drupal_add_css() for details about that.
3283
        $group_keys = $item['preprocess'] ? array($item['type'], $item['group'], $item['every_page'], $item['media'], $item['browsers']) : FALSE;
3284
        break;
3285
      case 'inline':
3286
        // Always group inline items.
3287
        $group_keys = array($item['type'], $item['media'], $item['browsers']);
3288
        break;
3289
      case 'external':
3290
        // Do not group external items.
3291
        $group_keys = FALSE;
3292
        break;
3293
    }
3294

    
3295
    // If the group keys don't match the most recent group we're working with,
3296
    // then a new group must be made.
3297
    if ($group_keys !== $current_group_keys) {
3298
      $i++;
3299
      // Initialize the new group with the same properties as the first item
3300
      // being placed into it. The item's 'data' and 'weight' properties are
3301
      // unique to the item and should not be carried over to the group.
3302
      $groups[$i] = $item;
3303
      unset($groups[$i]['data'], $groups[$i]['weight']);
3304
      $groups[$i]['items'] = array();
3305
      $current_group_keys = $group_keys ? $group_keys : NULL;
3306
    }
3307

    
3308
    // Add the item to the current group.
3309
    $groups[$i]['items'][] = $item;
3310
  }
3311
  return $groups;
3312
}
3313

    
3314
/**
3315
 * Default callback to aggregate CSS files and inline content.
3316
 *
3317
 * Having the browser load fewer CSS files results in much faster page loads
3318
 * than when it loads many small files. This function aggregates files within
3319
 * the same group into a single file unless the site-wide setting to do so is
3320
 * disabled (commonly the case during site development). To optimize download,
3321
 * it also compresses the aggregate files by removing comments, whitespace, and
3322
 * other unnecessary content. Additionally, this functions aggregates inline
3323
 * content together, regardless of the site-wide aggregation setting.
3324
 *
3325
 * @param $css_groups
3326
 *   An array of CSS groups as returned by drupal_group_css(). This function
3327
 *   modifies the group's 'data' property for each group that is aggregated.
3328
 *
3329
 * @see drupal_group_css()
3330
 * @see drupal_pre_render_styles()
3331
 * @see system_element_info()
3332
 */
3333
function drupal_aggregate_css(&$css_groups) {
3334
  $preprocess_css = (variable_get('preprocess_css', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
3335

    
3336
  // For each group that needs aggregation, aggregate its items.
3337
  foreach ($css_groups as $key => $group) {
3338
    switch ($group['type']) {
3339
      // If a file group can be aggregated into a single file, do so, and set
3340
      // the group's data property to the file path of the aggregate file.
3341
      case 'file':
3342
        if ($group['preprocess'] && $preprocess_css) {
3343
          $css_groups[$key]['data'] = drupal_build_css_cache($group['items']);
3344
        }
3345
        break;
3346
      // Aggregate all inline CSS content into the group's data property.
3347
      case 'inline':
3348
        $css_groups[$key]['data'] = '';
3349
        foreach ($group['items'] as $item) {
3350
          $css_groups[$key]['data'] .= drupal_load_stylesheet_content($item['data'], $item['preprocess']);
3351
        }
3352
        break;
3353
    }
3354
  }
3355
}
3356

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

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

    
3433
  // For inline CSS to validate as XHTML, all CSS containing XHTML needs to be
3434
  // wrapped in CDATA. To make that backwards compatible with HTML 4, we need to
3435
  // comment out the CDATA-tag.
3436
  $embed_prefix = "\n<!--/*--><![CDATA[/*><!--*/\n";
3437
  $embed_suffix = "\n/*]]>*/-->\n";
3438

    
3439
  // Defaults for LINK and STYLE elements.
3440
  $link_element_defaults = array(
3441
    '#type' => 'html_tag',
3442
    '#tag' => 'link',
3443
    '#attributes' => array(
3444
      'type' => 'text/css',
3445
      'rel' => 'stylesheet',
3446
    ),
3447
  );
3448
  $style_element_defaults = array(
3449
    '#type' => 'html_tag',
3450
    '#tag' => 'style',
3451
    '#attributes' => array(
3452
      'type' => 'text/css',
3453
    ),
3454
  );
3455

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

    
3582
  return $elements;
3583
}
3584

    
3585
/**
3586
 * Aggregates and optimizes CSS files into a cache file in the files directory.
3587
 *
3588
 * The file name for the CSS cache file is generated from the hash of the
3589
 * aggregated contents of the files in $css. This forces proxies and browsers
3590
 * to download new CSS when the CSS changes.
3591
 *
3592
 * The cache file name is retrieved on a page load via a lookup variable that
3593
 * contains an associative array. The array key is the hash of the file names
3594
 * in $css while the value is the cache file name. The cache file is generated
3595
 * in two cases. First, if there is no file name value for the key, which will
3596
 * happen if a new file name has been added to $css or after the lookup
3597
 * variable is emptied to force a rebuild of the cache. Second, the cache file
3598
 * is generated if it is missing on disk. Old cache files are not deleted
3599
 * immediately when the lookup variable is emptied, but are deleted after a set
3600
 * period by drupal_delete_file_if_stale(). This ensures that files referenced
3601
 * by a cached page will still be available.
3602
 *
3603
 * @param $css
3604
 *   An array of CSS files to aggregate and compress into one file.
3605
 *
3606
 * @return
3607
 *   The URI of the CSS cache file, or FALSE if the file could not be saved.
3608
 */
3609
function drupal_build_css_cache($css) {
3610
  $data = '';
3611
  $uri = '';
3612
  $map = variable_get('drupal_css_cache_files', array());
3613
  // Create a new array so that only the file names are used to create the hash.
3614
  // This prevents new aggregates from being created unnecessarily.
3615
  $css_data = array();
3616
  foreach ($css as $css_file) {
3617
    $css_data[] = $css_file['data'];
3618
  }
3619
  $key = hash('sha256', serialize($css_data));
3620
  if (isset($map[$key])) {
3621
    $uri = $map[$key];
3622
  }
3623

    
3624
  if (empty($uri) || !file_exists($uri)) {
3625
    // Build aggregate CSS file.
3626
    foreach ($css as $stylesheet) {
3627
      // Only 'file' stylesheets can be aggregated.
3628
      if ($stylesheet['type'] == 'file') {
3629
        $contents = drupal_load_stylesheet($stylesheet['data'], TRUE);
3630

    
3631
        // Build the base URL of this CSS file: start with the full URL.
3632
        $css_base_url = file_create_url($stylesheet['data']);
3633
        // Move to the parent.
3634
        $css_base_url = substr($css_base_url, 0, strrpos($css_base_url, '/'));
3635
        // Simplify to a relative URL if the stylesheet URL starts with the
3636
        // base URL of the website.
3637
        if (substr($css_base_url, 0, strlen($GLOBALS['base_root'])) == $GLOBALS['base_root']) {
3638
          $css_base_url = substr($css_base_url, strlen($GLOBALS['base_root']));
3639
        }
3640

    
3641
        _drupal_build_css_path(NULL, $css_base_url . '/');
3642
        // Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
3643
        $data .= preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);
3644
      }
3645
    }
3646

    
3647
    // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
3648
    // @import rules must proceed any other style, so we move those to the top.
3649
    $regexp = '/@import[^;]+;/i';
3650
    preg_match_all($regexp, $data, $matches);
3651
    $data = preg_replace($regexp, '', $data);
3652
    $data = implode('', $matches[0]) . $data;
3653

    
3654
    // Prefix filename to prevent blocking by firewalls which reject files
3655
    // starting with "ad*".
3656
    $filename = 'css_' . drupal_hash_base64($data) . '.css';
3657
    // Create the css/ within the files folder.
3658
    $csspath = 'public://css';
3659
    $uri = $csspath . '/' . $filename;
3660
    // Create the CSS file.
3661
    file_prepare_directory($csspath, FILE_CREATE_DIRECTORY);
3662
    if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
3663
      return FALSE;
3664
    }
3665
    // If CSS gzip compression is enabled, clean URLs are enabled (which means
3666
    // that rewrite rules are working) and the zlib extension is available then
3667
    // create a gzipped version of this file. This file is served conditionally
3668
    // to browsers that accept gzip using .htaccess rules.
3669
    if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
3670
      if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
3671
        return FALSE;
3672
      }
3673
    }
3674
    // Save the updated map.
3675
    $map[$key] = $uri;
3676
    variable_set('drupal_css_cache_files', $map);
3677
  }
3678
  return $uri;
3679
}
3680

    
3681
/**
3682
 * Prefixes all paths within a CSS file for drupal_build_css_cache().
3683
 */
3684
function _drupal_build_css_path($matches, $base = NULL) {
3685
  $_base = &drupal_static(__FUNCTION__);
3686
  // Store base path for preg_replace_callback.
3687
  if (isset($base)) {
3688
    $_base = $base;
3689
  }
3690

    
3691
  // Prefix with base and remove '../' segments where possible.
3692
  $path = $_base . $matches[1];
3693
  $last = '';
3694
  while ($path != $last) {
3695
    $last = $path;
3696
    $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
3697
  }
3698
  return 'url(' . $path . ')';
3699
}
3700

    
3701
/**
3702
 * Loads the stylesheet and resolves all @import commands.
3703
 *
3704
 * Loads a stylesheet and replaces @import commands with the contents of the
3705
 * imported file. Use this instead of file_get_contents when processing
3706
 * stylesheets.
3707
 *
3708
 * The returned contents are compressed removing white space and comments only
3709
 * when CSS aggregation is enabled. This optimization will not apply for
3710
 * color.module enabled themes with CSS aggregation turned off.
3711
 *
3712
 * @param $file
3713
 *   Name of the stylesheet to be processed.
3714
 * @param $optimize
3715
 *   Defines if CSS contents should be compressed or not.
3716
 * @param $reset_basepath
3717
 *   Used internally to facilitate recursive resolution of @import commands.
3718
 *
3719
 * @return
3720
 *   Contents of the stylesheet, including any resolved @import commands.
3721
 */
3722
function drupal_load_stylesheet($file, $optimize = NULL, $reset_basepath = TRUE) {
3723
  // These statics are not cache variables, so we don't use drupal_static().
3724
  static $_optimize, $basepath;
3725
  if ($reset_basepath) {
3726
    $basepath = '';
3727
  }
3728
  // Store the value of $optimize for preg_replace_callback with nested
3729
  // @import loops.
3730
  if (isset($optimize)) {
3731
    $_optimize = $optimize;
3732
  }
3733

    
3734
  // Stylesheets are relative one to each other. Start by adding a base path
3735
  // prefix provided by the parent stylesheet (if necessary).
3736
  if ($basepath && !file_uri_scheme($file)) {
3737
    $file = $basepath . '/' . $file;
3738
  }
3739
  // Store the parent base path to restore it later.
3740
  $parent_base_path = $basepath;
3741
  // Set the current base path to process possible child imports.
3742
  $basepath = dirname($file);
3743

    
3744
  // Load the CSS stylesheet. We suppress errors because themes may specify
3745
  // stylesheets in their .info file that don't exist in the theme's path,
3746
  // but are merely there to disable certain module CSS files.
3747
  $content = '';
3748
  if ($contents = @file_get_contents($file)) {
3749
    // Return the processed stylesheet.
3750
    $content = drupal_load_stylesheet_content($contents, $_optimize);
3751
  }
3752

    
3753
  // Restore the parent base path as the file and its childen are processed.
3754
  $basepath = $parent_base_path;
3755
  return $content;
3756
}
3757

    
3758
/**
3759
 * Processes the contents of a stylesheet for aggregation.
3760
 *
3761
 * @param $contents
3762
 *   The contents of the stylesheet.
3763
 * @param $optimize
3764
 *   (optional) Boolean whether CSS contents should be minified. Defaults to
3765
 *   FALSE.
3766
 *
3767
 * @return
3768
 *   Contents of the stylesheet including the imported stylesheets.
3769
 */
3770
function drupal_load_stylesheet_content($contents, $optimize = FALSE) {
3771
  // Remove multiple charset declarations for standards compliance (and fixing Safari problems).
3772
  $contents = preg_replace('/^@charset\s+[\'"](\S*?)\b[\'"];/i', '', $contents);
3773

    
3774
  if ($optimize) {
3775
    // Perform some safe CSS optimizations.
3776
    // Regexp to match comment blocks.
3777
    $comment     = '/\*[^*]*\*+(?:[^/*][^*]*\*+)*/';
3778
    // Regexp to match double quoted strings.
3779
    $double_quot = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
3780
    // Regexp to match single quoted strings.
3781
    $single_quot = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'";
3782
    // Strip all comment blocks, but keep double/single quoted strings.
3783
    $contents = preg_replace(
3784
      "<($double_quot|$single_quot)|$comment>Ss",
3785
      "$1",
3786
      $contents
3787
    );
3788
    // Remove certain whitespace.
3789
    // There are different conditions for removing leading and trailing
3790
    // whitespace.
3791
    // @see http://php.net/manual/regexp.reference.subpatterns.php
3792
    $contents = preg_replace('<
3793
      # Strip leading and trailing whitespace.
3794
        \s*([@{};,])\s*
3795
      # Strip only leading whitespace from:
3796
      # - Closing parenthesis: Retain "@media (bar) and foo".
3797
      | \s+([\)])
3798
      # Strip only trailing whitespace from:
3799
      # - Opening parenthesis: Retain "@media (bar) and foo".
3800
      # - Colon: Retain :pseudo-selectors.
3801
      | ([\(:])\s+
3802
    >xS',
3803
      // Only one of the three capturing groups will match, so its reference
3804
      // will contain the wanted value and the references for the
3805
      // two non-matching groups will be replaced with empty strings.
3806
      '$1$2$3',
3807
      $contents
3808
    );
3809
    // End the file with a new line.
3810
    $contents = trim($contents);
3811
    $contents .= "\n";
3812
  }
3813

    
3814
  // Replaces @import commands with the actual stylesheet content.
3815
  // This happens recursively but omits external files.
3816
  $contents = preg_replace_callback('/@import\s*(?:url\(\s*)?[\'"]?(?![a-z]+:)(?!\/\/)([^\'"\()]+)[\'"]?\s*\)?\s*;/', '_drupal_load_stylesheet', $contents);
3817
  return $contents;
3818
}
3819

    
3820
/**
3821
 * Loads stylesheets recursively and returns contents with corrected paths.
3822
 *
3823
 * This function is used for recursive loading of stylesheets and
3824
 * returns the stylesheet content with all url() paths corrected.
3825
 */
3826
function _drupal_load_stylesheet($matches) {
3827
  $filename = $matches[1];
3828
  // Load the imported stylesheet and replace @import commands in there as well.
3829
  $file = drupal_load_stylesheet($filename, NULL, FALSE);
3830

    
3831
  // Determine the file's directory.
3832
  $directory = dirname($filename);
3833
  // If the file is in the current directory, make sure '.' doesn't appear in
3834
  // the url() path.
3835
  $directory = $directory == '.' ? '' : $directory .'/';
3836

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

    
3843
/**
3844
 * Deletes old cached CSS files.
3845
 */
3846
function drupal_clear_css_cache() {
3847
  variable_del('drupal_css_cache_files');
3848
  file_scan_directory('public://css', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
3849
}
3850

    
3851
/**
3852
 * Callback to delete files modified more than a set time ago.
3853
 */
3854
function drupal_delete_file_if_stale($uri) {
3855
  // Default stale file threshold is 30 days.
3856
  if (REQUEST_TIME - filemtime($uri) > variable_get('drupal_stale_file_threshold', 2592000)) {
3857
    file_unmanaged_delete($uri);
3858
  }
3859
}
3860

    
3861
/**
3862
 * Prepares a string for use as a CSS identifier (element, class, or ID name).
3863
 *
3864
 * http://www.w3.org/TR/CSS21/syndata.html#characters shows the syntax for valid
3865
 * CSS identifiers (including element names, classes, and IDs in selectors.)
3866
 *
3867
 * @param $identifier
3868
 *   The identifier to clean.
3869
 * @param $filter
3870
 *   An array of string replacements to use on the identifier.
3871
 *
3872
 * @return
3873
 *   The cleaned identifier.
3874
 */
3875
function drupal_clean_css_identifier($identifier, $filter = array(' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '')) {
3876
  // By default, we filter using Drupal's coding standards.
3877
  $identifier = strtr($identifier, $filter);
3878

    
3879
  // Valid characters in a CSS identifier are:
3880
  // - the hyphen (U+002D)
3881
  // - a-z (U+0030 - U+0039)
3882
  // - A-Z (U+0041 - U+005A)
3883
  // - the underscore (U+005F)
3884
  // - 0-9 (U+0061 - U+007A)
3885
  // - ISO 10646 characters U+00A1 and higher
3886
  // We strip out any character not in the above list.
3887
  $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);
3888

    
3889
  return $identifier;
3890
}
3891

    
3892
/**
3893
 * Prepares a string for use as a valid class name.
3894
 *
3895
 * Do not pass one string containing multiple classes as they will be
3896
 * incorrectly concatenated with dashes, i.e. "one two" will become "one-two".
3897
 *
3898
 * @param $class
3899
 *   The class name to clean.
3900
 *
3901
 * @return
3902
 *   The cleaned class name.
3903
 */
3904
function drupal_html_class($class) {
3905
  // The output of this function will never change, so this uses a normal
3906
  // static instead of drupal_static().
3907
  static $classes = array();
3908

    
3909
  if (!isset($classes[$class])) {
3910
    $classes[$class] = drupal_clean_css_identifier(drupal_strtolower($class));
3911
  }
3912
  return $classes[$class];
3913
}
3914

    
3915
/**
3916
 * Prepares a string for use as a valid HTML ID and guarantees uniqueness.
3917
 *
3918
 * This function ensures that each passed HTML ID value only exists once on the
3919
 * page. By tracking the already returned ids, this function enables forms,
3920
 * blocks, and other content to be output multiple times on the same page,
3921
 * without breaking (X)HTML validation.
3922
 *
3923
 * For already existing IDs, a counter is appended to the ID string. Therefore,
3924
 * JavaScript and CSS code should not rely on any value that was generated by
3925
 * this function and instead should rely on manually added CSS classes or
3926
 * similarly reliable constructs.
3927
 *
3928
 * Two consecutive hyphens separate the counter from the original ID. To manage
3929
 * uniqueness across multiple Ajax requests on the same page, Ajax requests
3930
 * POST an array of all IDs currently present on the page, which are used to
3931
 * prime this function's cache upon first invocation.
3932
 *
3933
 * To allow reverse-parsing of IDs submitted via Ajax, any multiple consecutive
3934
 * hyphens in the originally passed $id are replaced with a single hyphen.
3935
 *
3936
 * @param $id
3937
 *   The ID to clean.
3938
 *
3939
 * @return
3940
 *   The cleaned ID.
3941
 */
3942
function drupal_html_id($id) {
3943
  // If this is an Ajax request, then content returned by this page request will
3944
  // be merged with content already on the base page. The HTML IDs must be
3945
  // unique for the fully merged content. Therefore, initialize $seen_ids to
3946
  // take into account IDs that are already in use on the base page.
3947
  $seen_ids_init = &drupal_static(__FUNCTION__ . ':init');
3948
  if (!isset($seen_ids_init)) {
3949
    // Ideally, Drupal would provide an API to persist state information about
3950
    // prior page requests in the database, and we'd be able to add this
3951
    // function's $seen_ids static variable to that state information in order
3952
    // to have it properly initialized for this page request. However, no such
3953
    // page state API exists, so instead, ajax.js adds all of the in-use HTML
3954
    // IDs to the POST data of Ajax submissions. Direct use of $_POST is
3955
    // normally not recommended as it could open up security risks, but because
3956
    // the raw POST data is cast to a number before being returned by this
3957
    // function, this usage is safe.
3958
    if (empty($_POST['ajax_html_ids'])) {
3959
      $seen_ids_init = array();
3960
    }
3961
    else {
3962
      // This function ensures uniqueness by appending a counter to the base id
3963
      // requested by the calling function after the first occurrence of that
3964
      // requested id. $_POST['ajax_html_ids'] contains the ids as they were
3965
      // returned by this function, potentially with the appended counter, so
3966
      // we parse that to reconstruct the $seen_ids array.
3967
      if (isset($_POST['ajax_html_ids'][0]) && strpos($_POST['ajax_html_ids'][0], ',') === FALSE) {
3968
        $ajax_html_ids = $_POST['ajax_html_ids'];
3969
      }
3970
      else {
3971
        // jquery.form.js may send the server a comma-separated string as the
3972
        // first element of an array (see http://drupal.org/node/1575060), so
3973
        // we need to convert it to an array in that case.
3974
        $ajax_html_ids = explode(',', $_POST['ajax_html_ids'][0]);
3975
      }
3976
      foreach ($ajax_html_ids as $seen_id) {
3977
        // We rely on '--' being used solely for separating a base id from the
3978
        // counter, which this function ensures when returning an id.
3979
        $parts = explode('--', $seen_id, 2);
3980
        if (!empty($parts[1]) && is_numeric($parts[1])) {
3981
          list($seen_id, $i) = $parts;
3982
        }
3983
        else {
3984
          $i = 1;
3985
        }
3986
        if (!isset($seen_ids_init[$seen_id]) || ($i > $seen_ids_init[$seen_id])) {
3987
          $seen_ids_init[$seen_id] = $i;
3988
        }
3989
      }
3990
    }
3991
  }
3992
  $seen_ids = &drupal_static(__FUNCTION__, $seen_ids_init);
3993

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

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

    
4004
  // Removing multiple consecutive hyphens.
4005
  $id = preg_replace('/\-+/', '-', $id);
4006
  // Ensure IDs are unique by appending a counter after the first occurrence.
4007
  // The counter needs to be appended with a delimiter that does not exist in
4008
  // the base ID. Requiring a unique delimiter helps ensure that we really do
4009
  // return unique IDs and also helps us re-create the $seen_ids array during
4010
  // Ajax requests.
4011
  if (isset($seen_ids[$id])) {
4012
    $id = $id . '--' . ++$seen_ids[$id];
4013
  }
4014
  else {
4015
    $seen_ids[$id] = 1;
4016
  }
4017

    
4018
  return $id;
4019
}
4020

    
4021
/**
4022
 * Provides a standard HTML class name that identifies a page region.
4023
 *
4024
 * It is recommended that template preprocess functions apply this class to any
4025
 * page region that is output by the theme (Drupal core already handles this in
4026
 * the standard template preprocess implementation). Standardizing the class
4027
 * names in this way allows modules to implement certain features, such as
4028
 * drag-and-drop or dynamic Ajax loading, in a theme-independent way.
4029
 *
4030
 * @param $region
4031
 *   The name of the page region (for example, 'page_top' or 'content').
4032
 *
4033
 * @return
4034
 *   An HTML class that identifies the region (for example, 'region-page-top'
4035
 *   or 'region-content').
4036
 *
4037
 * @see template_preprocess_region()
4038
 */
4039
function drupal_region_class($region) {
4040
  return drupal_html_class("region-$region");
4041
}
4042

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

    
4202
  // If the $javascript variable has been reset with drupal_static_reset(),
4203
  // jQuery and related files will have been removed from the list, so set the
4204
  // variable back to FALSE to indicate they have not yet been added.
4205
  if (empty($javascript)) {
4206
    $jquery_added = FALSE;
4207
  }
4208

    
4209
  // Construct the options, taking the defaults into consideration.
4210
  if (isset($options)) {
4211
    if (!is_array($options)) {
4212
      $options = array('type' => $options);
4213
    }
4214
  }
4215
  else {
4216
    $options = array();
4217
  }
4218
  if (isset($options['type']) && $options['type'] == 'setting') {
4219
    $options += array('requires_jquery' => FALSE);
4220
  }
4221
  $options += drupal_js_defaults($data);
4222

    
4223
  // Preprocess can only be set if caching is enabled.
4224
  $options['preprocess'] = $options['cache'] ? $options['preprocess'] : FALSE;
4225

    
4226
  // Tweak the weight so that files of the same weight are included in the
4227
  // order of the calls to drupal_add_js().
4228
  $options['weight'] += count($javascript) / 1000;
4229

    
4230
  if (isset($data)) {
4231
    // Add jquery.js, drupal.js, and related files and settings if they have
4232
    // not been added yet. However, if the 'javascript_always_use_jquery'
4233
    // variable is set to FALSE (indicating that the site does not want jQuery
4234
    // automatically added on all pages) then only add it if a file or setting
4235
    // that requires jQuery is being added also.
4236
    if (!$jquery_added && (variable_get('javascript_always_use_jquery', TRUE) || $options['requires_jquery'])) {
4237
      $jquery_added = TRUE;
4238
      // url() generates the prefix using hook_url_outbound_alter(). Instead of
4239
      // running the hook_url_outbound_alter() again here, extract the prefix
4240
      // from url().
4241
      url('', array('prefix' => &$prefix));
4242
      $default_javascript = array(
4243
        'settings' => array(
4244
          'data' => array(
4245
            array('basePath' => base_path()),
4246
            array('pathPrefix' => empty($prefix) ? '' : $prefix),
4247
          ),
4248
          'type' => 'setting',
4249
          'scope' => 'header',
4250
          'group' => JS_LIBRARY,
4251
          'every_page' => TRUE,
4252
          'weight' => 0,
4253
        ),
4254
        'misc/drupal.js' => array(
4255
          'data' => 'misc/drupal.js',
4256
          'type' => 'file',
4257
          'scope' => 'header',
4258
          'group' => JS_LIBRARY,
4259
          'every_page' => TRUE,
4260
          'weight' => -1,
4261
          'requires_jquery' => TRUE,
4262
          'preprocess' => TRUE,
4263
          'cache' => TRUE,
4264
          'defer' => FALSE,
4265
        ),
4266
      );
4267
      $javascript = drupal_array_merge_deep($javascript, $default_javascript);
4268
      // Register all required libraries.
4269
      drupal_add_library('system', 'jquery', TRUE);
4270
      drupal_add_library('system', 'jquery.once', TRUE);
4271
    }
4272

    
4273
    switch ($options['type']) {
4274
      case 'setting':
4275
        // All JavaScript settings are placed in the header of the page with
4276
        // the library weight so that inline scripts appear afterwards.
4277
        $javascript['settings']['data'][] = $data;
4278
        break;
4279

    
4280
      case 'inline':
4281
        $javascript[] = $options;
4282
        break;
4283

    
4284
      default: // 'file' and 'external'
4285
        // Local and external files must keep their name as the associative key
4286
        // so the same JavaScript file is not added twice.
4287
        $javascript[$options['data']] = $options;
4288
    }
4289
  }
4290
  return $javascript;
4291
}
4292

    
4293
/**
4294
 * Constructs an array of the defaults that are used for JavaScript items.
4295
 *
4296
 * @param $data
4297
 *   (optional) The default data parameter for the JavaScript item array.
4298
 *
4299
 * @see drupal_get_js()
4300
 * @see drupal_add_js()
4301
 */
4302
function drupal_js_defaults($data = NULL) {
4303
  return array(
4304
    'type' => 'file',
4305
    'group' => JS_DEFAULT,
4306
    'every_page' => FALSE,
4307
    'weight' => 0,
4308
    'requires_jquery' => TRUE,
4309
    'scope' => 'header',
4310
    'cache' => TRUE,
4311
    'defer' => FALSE,
4312
    'preprocess' => TRUE,
4313
    'version' => NULL,
4314
    'data' => $data,
4315
  );
4316
}
4317

    
4318
/**
4319
 * Returns a themed presentation of all JavaScript code for the current page.
4320
 *
4321
 * References to JavaScript files are placed in a certain order: first, all
4322
 * 'core' files, then all 'module' and finally all 'theme' JavaScript files
4323
 * are added to the page. Then, all settings are output, followed by 'inline'
4324
 * JavaScript code. If running update.php, all preprocessing is disabled.
4325
 *
4326
 * Note that hook_js_alter(&$javascript) is called during this function call
4327
 * to allow alterations of the JavaScript during its presentation. Calls to
4328
 * drupal_add_js() from hook_js_alter() will not be added to the output
4329
 * presentation. The correct way to add JavaScript during hook_js_alter()
4330
 * is to add another element to the $javascript array, deriving from
4331
 * drupal_js_defaults(). See locale_js_alter() for an example of this.
4332
 *
4333
 * @param $scope
4334
 *   (optional) The scope for which the JavaScript rules should be returned.
4335
 *   Defaults to 'header'.
4336
 * @param $javascript
4337
 *   (optional) An array with all JavaScript code. Defaults to the default
4338
 *   JavaScript array for the given scope.
4339
 * @param $skip_alter
4340
 *   (optional) If set to TRUE, this function skips calling drupal_alter() on
4341
 *   $javascript, useful when the calling function passes a $javascript array
4342
 *   that has already been altered.
4343
 *
4344
 * @return
4345
 *   All JavaScript code segments and includes for the scope as HTML tags.
4346
 *
4347
 * @see drupal_add_js()
4348
 * @see locale_js_alter()
4349
 * @see drupal_js_defaults()
4350
 */
4351
function drupal_get_js($scope = 'header', $javascript = NULL, $skip_alter = FALSE) {
4352
  if (!isset($javascript)) {
4353
    $javascript = drupal_add_js();
4354
  }
4355

    
4356
  // If no JavaScript items have been added, or if the only JavaScript items
4357
  // that have been added are JavaScript settings (which don't do anything
4358
  // without any JavaScript code to use them), then no JavaScript code should
4359
  // be added to the page.
4360
  if (empty($javascript) || (isset($javascript['settings']) && count($javascript) == 1)) {
4361
    return '';
4362
  }
4363

    
4364
  // Allow modules to alter the JavaScript.
4365
  if (!$skip_alter) {
4366
    drupal_alter('js', $javascript);
4367
  }
4368

    
4369
  // Filter out elements of the given scope.
4370
  $items = array();
4371
  foreach ($javascript as $key => $item) {
4372
    if ($item['scope'] == $scope) {
4373
      $items[$key] = $item;
4374
    }
4375
  }
4376

    
4377
  $output = '';
4378
  // The index counter is used to keep aggregated and non-aggregated files in
4379
  // order by weight.
4380
  $index = 1;
4381
  $processed = array();
4382
  $files = array();
4383
  $preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
4384

    
4385
  // A dummy query-string is added to filenames, to gain control over
4386
  // browser-caching. The string changes on every update or full cache
4387
  // flush, forcing browsers to load a new copy of the files, as the
4388
  // URL changed. Files that should not be cached (see drupal_add_js())
4389
  // get REQUEST_TIME as query-string instead, to enforce reload on every
4390
  // page request.
4391
  $default_query_string = variable_get('css_js_query_string', '0');
4392

    
4393
  // For inline JavaScript to validate as XHTML, all JavaScript containing
4394
  // XHTML needs to be wrapped in CDATA. To make that backwards compatible
4395
  // with HTML 4, we need to comment out the CDATA-tag.
4396
  $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
4397
  $embed_suffix = "\n//--><!]]>\n";
4398

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

    
4403
  // Sort the JavaScript so that it appears in the correct order.
4404
  uasort($items, 'drupal_sort_css_js');
4405

    
4406
  // Provide the page with information about the individual JavaScript files
4407
  // used, information not otherwise available when aggregation is enabled.
4408
  $setting['ajaxPageState']['js'] = array_fill_keys(array_keys($items), 1);
4409
  unset($setting['ajaxPageState']['js']['settings']);
4410
  drupal_add_js($setting, 'setting');
4411

    
4412
  // If we're outputting the header scope, then this might be the final time
4413
  // that drupal_get_js() is running, so add the setting to this output as well
4414
  // as to the drupal_add_js() cache. If $items['settings'] doesn't exist, it's
4415
  // because drupal_get_js() was intentionally passed a $javascript argument
4416
  // stripped off settings, potentially in order to override how settings get
4417
  // output, so in this case, do not add the setting to this output.
4418
  if ($scope == 'header' && isset($items['settings'])) {
4419
    $items['settings']['data'][] = $setting;
4420
  }
4421

    
4422
  // Loop through the JavaScript to construct the rendered output.
4423
  $element = array(
4424
    '#tag' => 'script',
4425
    '#value' => '',
4426
    '#attributes' => array(
4427
      'type' => 'text/javascript',
4428
    ),
4429
  );
4430
  foreach ($items as $item) {
4431
    $query_string =  empty($item['version']) ? $default_query_string : $js_version_string . $item['version'];
4432

    
4433
    switch ($item['type']) {
4434
      case 'setting':
4435
        $js_element = $element;
4436
        $js_element['#value_prefix'] = $embed_prefix;
4437
        $js_element['#value'] = 'jQuery.extend(Drupal.settings, ' . drupal_json_encode(drupal_array_merge_deep_array($item['data'])) . ");";
4438
        $js_element['#value_suffix'] = $embed_suffix;
4439
        $output .= theme('html_tag', array('element' => $js_element));
4440
        break;
4441

    
4442
      case 'inline':
4443
        $js_element = $element;
4444
        if ($item['defer']) {
4445
          $js_element['#attributes']['defer'] = 'defer';
4446
        }
4447
        $js_element['#value_prefix'] = $embed_prefix;
4448
        $js_element['#value'] = $item['data'];
4449
        $js_element['#value_suffix'] = $embed_suffix;
4450
        $processed[$index++] = theme('html_tag', array('element' => $js_element));
4451
        break;
4452

    
4453
      case 'file':
4454
        $js_element = $element;
4455
        if (!$item['preprocess'] || !$preprocess_js) {
4456
          if ($item['defer']) {
4457
            $js_element['#attributes']['defer'] = 'defer';
4458
          }
4459
          $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
4460
          $js_element['#attributes']['src'] = file_create_url($item['data']) . $query_string_separator . ($item['cache'] ? $query_string : REQUEST_TIME);
4461
          $processed[$index++] = theme('html_tag', array('element' => $js_element));
4462
        }
4463
        else {
4464
          // By increasing the index for each aggregated file, we maintain
4465
          // the relative ordering of JS by weight. We also set the key such
4466
          // that groups are split by items sharing the same 'group' value and
4467
          // 'every_page' flag. While this potentially results in more aggregate
4468
          // files, it helps make each one more reusable across a site visit,
4469
          // leading to better front-end performance of a website as a whole.
4470
          // See drupal_add_js() for details.
4471
          $key = 'aggregate_' . $item['group'] . '_' . $item['every_page'] . '_' . $index;
4472
          $processed[$key] = '';
4473
          $files[$key][$item['data']] = $item;
4474
        }
4475
        break;
4476

    
4477
      case 'external':
4478
        $js_element = $element;
4479
        // Preprocessing for external JavaScript files is ignored.
4480
        if ($item['defer']) {
4481
          $js_element['#attributes']['defer'] = 'defer';
4482
        }
4483
        $js_element['#attributes']['src'] = $item['data'];
4484
        $processed[$index++] = theme('html_tag', array('element' => $js_element));
4485
        break;
4486
    }
4487
  }
4488

    
4489
  // Aggregate any remaining JS files that haven't already been output.
4490
  if ($preprocess_js && count($files) > 0) {
4491
    foreach ($files as $key => $file_set) {
4492
      $uri = drupal_build_js_cache($file_set);
4493
      // Only include the file if was written successfully. Errors are logged
4494
      // using watchdog.
4495
      if ($uri) {
4496
        $preprocess_file = file_create_url($uri);
4497
        $js_element = $element;
4498
        $js_element['#attributes']['src'] = $preprocess_file;
4499
        $processed[$key] = theme('html_tag', array('element' => $js_element));
4500
      }
4501
    }
4502
  }
4503

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

    
4509
/**
4510
 * Adds attachments to a render() structure.
4511
 *
4512
 * Libraries, JavaScript, CSS and other types of custom structures are attached
4513
 * to elements using the #attached property. The #attached property is an
4514
 * associative array, where the keys are the attachment types and the values are
4515
 * the attached data. For example:
4516
 * @code
4517
 * $build['#attached'] = array(
4518
 *   'js' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.js'),
4519
 *   'css' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.css'),
4520
 * );
4521
 * @endcode
4522
 *
4523
 * 'js', 'css', and 'library' are types that get special handling. For any
4524
 * other kind of attached data, the array key must be the full name of the
4525
 * callback function and each value an array of arguments. For example:
4526
 * @code
4527
 * $build['#attached']['drupal_add_http_header'] = array(
4528
 *   array('Content-Type', 'application/rss+xml; charset=utf-8'),
4529
 * );
4530
 * @endcode
4531
 *
4532
 * External 'js' and 'css' files can also be loaded. For example:
4533
 * @code
4534
 * $build['#attached']['js'] = array(
4535
 *   'http://code.jquery.com/jquery-1.4.2.min.js' => array(
4536
 *     'type' => 'external',
4537
 *   ),
4538
 * );
4539
 * @endcode
4540
 *
4541
 * @param $elements
4542
 *   The structured array describing the data being rendered.
4543
 * @param $group
4544
 *   The default group of JavaScript and CSS being added. This is only applied
4545
 *   to the stylesheets and JavaScript items that don't have an explicit group
4546
 *   assigned to them.
4547
 * @param $dependency_check
4548
 *   When TRUE, will exit if a given library's dependencies are missing. When
4549
 *   set to FALSE, will continue to add the libraries, even though one or more
4550
 *   dependencies are missing. Defaults to FALSE.
4551
 * @param $every_page
4552
 *   Set to TRUE to indicate that the attachments are added to every page on the
4553
 *   site. Only attachments with the every_page flag set to TRUE can participate
4554
 *   in JavaScript/CSS aggregation.
4555
 *
4556
 * @return
4557
 *   FALSE if there were any missing library dependencies; TRUE if all library
4558
 *   dependencies were met.
4559
 *
4560
 * @see drupal_add_library()
4561
 * @see drupal_add_js()
4562
 * @see drupal_add_css()
4563
 * @see drupal_render()
4564
 */
4565
function drupal_process_attached($elements, $group = JS_DEFAULT, $dependency_check = FALSE, $every_page = NULL) {
4566
  // Add defaults to the special attached structures that should be processed differently.
4567
  $elements['#attached'] += array(
4568
    'library' => array(),
4569
    'js' => array(),
4570
    'css' => array(),
4571
  );
4572

    
4573
  // Add the libraries first.
4574
  $success = TRUE;
4575
  foreach ($elements['#attached']['library'] as $library) {
4576
    if (drupal_add_library($library[0], $library[1], $every_page) === FALSE) {
4577
      $success = FALSE;
4578
      // Exit if the dependency is missing.
4579
      if ($dependency_check) {
4580
        return $success;
4581
      }
4582
    }
4583
  }
4584
  unset($elements['#attached']['library']);
4585

    
4586
  // Add both the JavaScript and the CSS.
4587
  // The parameters for drupal_add_js() and drupal_add_css() require special
4588
  // handling.
4589
  foreach (array('js', 'css') as $type) {
4590
    foreach ($elements['#attached'][$type] as $data => $options) {
4591
      // If the value is not an array, it's a filename and passed as first
4592
      // (and only) argument.
4593
      if (!is_array($options)) {
4594
        $data = $options;
4595
        $options = NULL;
4596
      }
4597
      // In some cases, the first parameter ($data) is an array. Arrays can't be
4598
      // passed as keys in PHP, so we have to get $data from the value array.
4599
      if (is_numeric($data)) {
4600
        $data = $options['data'];
4601
        unset($options['data']);
4602
      }
4603
      // Apply the default group if it isn't explicitly given.
4604
      if (!isset($options['group'])) {
4605
        $options['group'] = $group;
4606
      }
4607
      // Set the every_page flag if one was passed.
4608
      if (isset($every_page)) {
4609
        $options['every_page'] = $every_page;
4610
      }
4611
      call_user_func('drupal_add_' . $type, $data, $options);
4612
    }
4613
    unset($elements['#attached'][$type]);
4614
  }
4615

    
4616
  // Add additional types of attachments specified in the render() structure.
4617
  // Libraries, JavaScript and CSS have been added already, as they require
4618
  // special handling.
4619
  foreach ($elements['#attached'] as $callback => $options) {
4620
    if (function_exists($callback)) {
4621
      foreach ($elements['#attached'][$callback] as $args) {
4622
        call_user_func_array($callback, $args);
4623
      }
4624
    }
4625
  }
4626

    
4627
  return $success;
4628
}
4629

    
4630
/**
4631
 * Adds JavaScript to change the state of an element based on another element.
4632
 *
4633
 * A "state" means a certain property on a DOM element, such as "visible" or
4634
 * "checked". A state can be applied to an element, depending on the state of
4635
 * another element on the page. In general, states depend on HTML attributes and
4636
 * DOM element properties, which change due to user interaction.
4637
 *
4638
 * Since states are driven by JavaScript only, it is important to understand
4639
 * that all states are applied on presentation only, none of the states force
4640
 * any server-side logic, and that they will not be applied for site visitors
4641
 * without JavaScript support. All modules implementing states have to make
4642
 * sure that the intended logic also works without JavaScript being enabled.
4643
 *
4644
 * #states is an associative array in the form of:
4645
 * @code
4646
 * array(
4647
 *   STATE1 => CONDITIONS_ARRAY1,
4648
 *   STATE2 => CONDITIONS_ARRAY2,
4649
 *   ...
4650
 * )
4651
 * @endcode
4652
 * Each key is the name of a state to apply to the element, such as 'visible'.
4653
 * Each value is a list of conditions that denote when the state should be
4654
 * applied.
4655
 *
4656
 * Multiple different states may be specified to act on complex conditions:
4657
 * @code
4658
 * array(
4659
 *   'visible' => CONDITIONS,
4660
 *   'checked' => OTHER_CONDITIONS,
4661
 * )
4662
 * @endcode
4663
 *
4664
 * Every condition is a key/value pair, whose key is a jQuery selector that
4665
 * denotes another element on the page, and whose value is an array of
4666
 * conditions, which must bet met on that element:
4667
 * @code
4668
 * array(
4669
 *   'visible' => array(
4670
 *     JQUERY_SELECTOR => REMOTE_CONDITIONS,
4671
 *     JQUERY_SELECTOR => REMOTE_CONDITIONS,
4672
 *     ...
4673
 *   ),
4674
 * )
4675
 * @endcode
4676
 * All conditions must be met for the state to be applied.
4677
 *
4678
 * Each remote condition is a key/value pair specifying conditions on the other
4679
 * element that need to be met to apply the state to the element:
4680
 * @code
4681
 * array(
4682
 *   'visible' => array(
4683
 *     ':input[name="remote_checkbox"]' => array('checked' => TRUE),
4684
 *   ),
4685
 * )
4686
 * @endcode
4687
 *
4688
 * For example, to show a textfield only when a checkbox is checked:
4689
 * @code
4690
 * $form['toggle_me'] = array(
4691
 *   '#type' => 'checkbox',
4692
 *   '#title' => t('Tick this box to type'),
4693
 * );
4694
 * $form['settings'] = array(
4695
 *   '#type' => 'textfield',
4696
 *   '#states' => array(
4697
 *     // Only show this field when the 'toggle_me' checkbox is enabled.
4698
 *     'visible' => array(
4699
 *       ':input[name="toggle_me"]' => array('checked' => TRUE),
4700
 *     ),
4701
 *   ),
4702
 * );
4703
 * @endcode
4704
 *
4705
 * The following states may be applied to an element:
4706
 * - enabled
4707
 * - disabled
4708
 * - required
4709
 * - optional
4710
 * - visible
4711
 * - invisible
4712
 * - checked
4713
 * - unchecked
4714
 * - expanded
4715
 * - collapsed
4716
 *
4717
 * The following states may be used in remote conditions:
4718
 * - empty
4719
 * - filled
4720
 * - checked
4721
 * - unchecked
4722
 * - expanded
4723
 * - collapsed
4724
 * - value
4725
 *
4726
 * The following states exist for both elements and remote conditions, but are
4727
 * not fully implemented and may not change anything on the element:
4728
 * - relevant
4729
 * - irrelevant
4730
 * - valid
4731
 * - invalid
4732
 * - touched
4733
 * - untouched
4734
 * - readwrite
4735
 * - readonly
4736
 *
4737
 * When referencing select lists and radio buttons in remote conditions, a
4738
 * 'value' condition must be used:
4739
 * @code
4740
 *   '#states' => array(
4741
 *     // Show the settings if 'bar' has been selected for 'foo'.
4742
 *     'visible' => array(
4743
 *       ':input[name="foo"]' => array('value' => 'bar'),
4744
 *     ),
4745
 *   ),
4746
 * @endcode
4747
 *
4748
 * @param $elements
4749
 *   A renderable array element having a #states property as described above.
4750
 *
4751
 * @see form_example_states_form()
4752
 */
4753
function drupal_process_states(&$elements) {
4754
  $elements['#attached']['library'][] = array('system', 'drupal.states');
4755
  $elements['#attached']['js'][] = array(
4756
    'type' => 'setting',
4757
    'data' => array('states' => array('#' . $elements['#id'] => $elements['#states'])),
4758
  );
4759
}
4760

    
4761
/**
4762
 * Adds multiple JavaScript or CSS files at the same time.
4763
 *
4764
 * A library defines a set of JavaScript and/or CSS files, optionally using
4765
 * settings, and optionally requiring another library. For example, a library
4766
 * can be a jQuery plugin, a JavaScript framework, or a CSS framework. This
4767
 * function allows modules to load a library defined/shipped by itself or a
4768
 * depending module, without having to add all files of the library separately.
4769
 * Each library is only loaded once.
4770
 *
4771
 * @param $module
4772
 *   The name of the module that registered the library.
4773
 * @param $name
4774
 *   The name of the library to add.
4775
 * @param $every_page
4776
 *   Set to TRUE if this library is added to every page on the site. Only items
4777
 *   with the every_page flag set to TRUE can participate in aggregation.
4778
 *
4779
 * @return
4780
 *   TRUE if the library was successfully added; FALSE if the library or one of
4781
 *   its dependencies could not be added.
4782
 *
4783
 * @see drupal_get_library()
4784
 * @see hook_library()
4785
 * @see hook_library_alter()
4786
 */
4787
function drupal_add_library($module, $name, $every_page = NULL) {
4788
  $added = &drupal_static(__FUNCTION__, array());
4789

    
4790
  // Only process the library if it exists and it was not added already.
4791
  if (!isset($added[$module][$name])) {
4792
    if ($library = drupal_get_library($module, $name)) {
4793
      // Add all components within the library.
4794
      $elements['#attached'] = array(
4795
        'library' => $library['dependencies'],
4796
        'js' => $library['js'],
4797
        'css' => $library['css'],
4798
      );
4799
      $added[$module][$name] = drupal_process_attached($elements, JS_LIBRARY, TRUE, $every_page);
4800
    }
4801
    else {
4802
      // Requested library does not exist.
4803
      $added[$module][$name] = FALSE;
4804
    }
4805
  }
4806

    
4807
  return $added[$module][$name];
4808
}
4809

    
4810
/**
4811
 * Retrieves information for a JavaScript/CSS library.
4812
 *
4813
 * Library information is statically cached. Libraries are keyed by module for
4814
 * several reasons:
4815
 * - Libraries are not unique. Multiple modules might ship with the same library
4816
 *   in a different version or variant. This registry cannot (and does not
4817
 *   attempt to) prevent library conflicts.
4818
 * - Modules implementing and thereby depending on a library that is registered
4819
 *   by another module can only rely on that module's library.
4820
 * - Two (or more) modules can still register the same library and use it
4821
 *   without conflicts in case the libraries are loaded on certain pages only.
4822
 *
4823
 * @param $module
4824
 *   The name of a module that registered a library.
4825
 * @param $name
4826
 *   (optional) The name of a registered library to retrieve. By default, all
4827
 *   libraries registered by $module are returned.
4828
 *
4829
 * @return
4830
 *   The definition of the requested library, if $name was passed and it exists,
4831
 *   or FALSE if it does not exist. If no $name was passed, an associative array
4832
 *   of libraries registered by $module is returned (which may be empty).
4833
 *
4834
 * @see drupal_add_library()
4835
 * @see hook_library()
4836
 * @see hook_library_alter()
4837
 *
4838
 * @todo The purpose of drupal_get_*() is completely different to other page
4839
 *   requisite API functions; find and use a different name.
4840
 */
4841
function drupal_get_library($module, $name = NULL) {
4842
  $libraries = &drupal_static(__FUNCTION__, array());
4843

    
4844
  if (!isset($libraries[$module])) {
4845
    // Retrieve all libraries associated with the module.
4846
    $module_libraries = module_invoke($module, 'library');
4847
    if (empty($module_libraries)) {
4848
      $module_libraries = array();
4849
    }
4850
    // Allow modules to alter the module's registered libraries.
4851
    drupal_alter('library', $module_libraries, $module);
4852

    
4853
    foreach ($module_libraries as $key => $data) {
4854
      if (is_array($data)) {
4855
        // Add default elements to allow for easier processing.
4856
        $module_libraries[$key] += array('dependencies' => array(), 'js' => array(), 'css' => array());
4857
        foreach ($module_libraries[$key]['js'] as $file => $options) {
4858
          $module_libraries[$key]['js'][$file]['version'] = $module_libraries[$key]['version'];
4859
        }
4860
      }
4861
    }
4862
    $libraries[$module] = $module_libraries;
4863
  }
4864
  if (isset($name)) {
4865
    if (!isset($libraries[$module][$name])) {
4866
      $libraries[$module][$name] = FALSE;
4867
    }
4868
    return $libraries[$module][$name];
4869
  }
4870
  return $libraries[$module];
4871
}
4872

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

    
4991
  // If a subgroup or source isn't set, assume it is the same as the group.
4992
  $target = isset($subgroup) ? $subgroup : $group;
4993
  $source = isset($source) ? $source : $target;
4994
  $settings['tableDrag'][$table_id][$group][] = array(
4995
    'target' => $target,
4996
    'source' => $source,
4997
    'relationship' => $relationship,
4998
    'action' => $action,
4999
    'hidden' => $hidden,
5000
    'limit' => $limit,
5001
  );
5002
  drupal_add_js($settings, 'setting');
5003
}
5004

    
5005
/**
5006
 * Aggregates JavaScript files into a cache file in the files directory.
5007
 *
5008
 * The file name for the JavaScript cache file is generated from the hash of
5009
 * the aggregated contents of the files in $files. This forces proxies and
5010
 * browsers to download new JavaScript when the JavaScript changes.
5011
 *
5012
 * The cache file name is retrieved on a page load via a lookup variable that
5013
 * contains an associative array. The array key is the hash of the names in
5014
 * $files while the value is the cache file name. The cache file is generated
5015
 * in two cases. First, if there is no file name value for the key, which will
5016
 * happen if a new file name has been added to $files or after the lookup
5017
 * variable is emptied to force a rebuild of the cache. Second, the cache file
5018
 * is generated if it is missing on disk. Old cache files are not deleted
5019
 * immediately when the lookup variable is emptied, but are deleted after a set
5020
 * period by drupal_delete_file_if_stale(). This ensures that files referenced
5021
 * by a cached page will still be available.
5022
 *
5023
 * @param $files
5024
 *   An array of JavaScript files to aggregate and compress into one file.
5025
 *
5026
 * @return
5027
 *   The URI of the cache file, or FALSE if the file could not be saved.
5028
 */
5029
function drupal_build_js_cache($files) {
5030
  $contents = '';
5031
  $uri = '';
5032
  $map = variable_get('drupal_js_cache_files', array());
5033
  // Create a new array so that only the file names are used to create the hash.
5034
  // This prevents new aggregates from being created unnecessarily.
5035
  $js_data = array();
5036
  foreach ($files as $file) {
5037
    $js_data[] = $file['data'];
5038
  }
5039
  $key = hash('sha256', serialize($js_data));
5040
  if (isset($map[$key])) {
5041
    $uri = $map[$key];
5042
  }
5043

    
5044
  if (empty($uri) || !file_exists($uri)) {
5045
    // Build aggregate JS file.
5046
    foreach ($files as $path => $info) {
5047
      if ($info['preprocess']) {
5048
        // Append a ';' and a newline after each JS file to prevent them from running together.
5049
        $contents .= file_get_contents($path) . ";\n";
5050
      }
5051
    }
5052
    // Prefix filename to prevent blocking by firewalls which reject files
5053
    // starting with "ad*".
5054
    $filename = 'js_' . drupal_hash_base64($contents) . '.js';
5055
    // Create the js/ within the files folder.
5056
    $jspath = 'public://js';
5057
    $uri = $jspath . '/' . $filename;
5058
    // Create the JS file.
5059
    file_prepare_directory($jspath, FILE_CREATE_DIRECTORY);
5060
    if (!file_exists($uri) && !file_unmanaged_save_data($contents, $uri, FILE_EXISTS_REPLACE)) {
5061
      return FALSE;
5062
    }
5063
    // If JS gzip compression is enabled, clean URLs are enabled (which means
5064
    // that rewrite rules are working) and the zlib extension is available then
5065
    // create a gzipped version of this file. This file is served conditionally
5066
    // to browsers that accept gzip using .htaccess rules.
5067
    if (variable_get('js_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
5068
      if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($contents, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
5069
        return FALSE;
5070
      }
5071
    }
5072
    $map[$key] = $uri;
5073
    variable_set('drupal_js_cache_files', $map);
5074
  }
5075
  return $uri;
5076
}
5077

    
5078
/**
5079
 * Deletes old cached JavaScript files and variables.
5080
 */
5081
function drupal_clear_js_cache() {
5082
  variable_del('javascript_parsed');
5083
  variable_del('drupal_js_cache_files');
5084
  file_scan_directory('public://js', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
5085
}
5086

    
5087
/**
5088
 * Converts a PHP variable into its JavaScript equivalent.
5089
 *
5090
 * We use HTML-safe strings, with several characters escaped.
5091
 *
5092
 * @see drupal_json_decode()
5093
 * @see drupal_json_encode_helper()
5094
 * @ingroup php_wrappers
5095
 */
5096
function drupal_json_encode($var) {
5097
  // The PHP version cannot change within a request.
5098
  static $php530;
5099

    
5100
  if (!isset($php530)) {
5101
    $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
5102
  }
5103

    
5104
  if ($php530) {
5105
    // Encode <, >, ', &, and " using the json_encode() options parameter.
5106
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
5107
  }
5108

    
5109
  // json_encode() escapes <, >, ', &, and " using its options parameter, but
5110
  // does not support this parameter prior to PHP 5.3.0.  Use a helper instead.
5111
  include_once DRUPAL_ROOT . '/includes/json-encode.inc';
5112
  return drupal_json_encode_helper($var);
5113
}
5114

    
5115
/**
5116
 * Converts an HTML-safe JSON string into its PHP equivalent.
5117
 *
5118
 * @see drupal_json_encode()
5119
 * @ingroup php_wrappers
5120
 */
5121
function drupal_json_decode($var) {
5122
  return json_decode($var, TRUE);
5123
}
5124

    
5125
/**
5126
 * Returns data in JSON format.
5127
 *
5128
 * This function should be used for JavaScript callback functions returning
5129
 * data in JSON format. It sets the header for JavaScript output.
5130
 *
5131
 * @param $var
5132
 *   (optional) If set, the variable will be converted to JSON and output.
5133
 */
5134
function drupal_json_output($var = NULL) {
5135
  // We are returning JSON, so tell the browser.
5136
  drupal_add_http_header('Content-Type', 'application/json');
5137

    
5138
  if (isset($var)) {
5139
    echo drupal_json_encode($var);
5140
  }
5141
}
5142

    
5143
/**
5144
 * Ensures the private key variable used to generate tokens is set.
5145
 *
5146
 * @return
5147
 *   The private key.
5148
 */
5149
function drupal_get_private_key() {
5150
  if (!($key = variable_get('drupal_private_key', 0))) {
5151
    $key = drupal_random_key();
5152
    variable_set('drupal_private_key', $key);
5153
  }
5154
  return $key;
5155
}
5156

    
5157
/**
5158
 * Generates a token based on $value, the user session, and the private key.
5159
 *
5160
 * @param $value
5161
 *   An additional value to base the token on.
5162
 *
5163
 * The generated token is based on the session ID of the current user. Normally,
5164
 * anonymous users do not have a session, so the generated token will be
5165
 * different on every page request. To generate a token for users without a
5166
 * session, manually start a session prior to calling this function.
5167
 *
5168
 * @return string
5169
 *   A 43-character URL-safe token for validation, based on the user session ID,
5170
 *   the hash salt provided from drupal_get_hash_salt(), and the
5171
 *   'drupal_private_key' configuration variable.
5172
 *
5173
 * @see drupal_get_hash_salt()
5174
 */
5175
function drupal_get_token($value = '') {
5176
  return drupal_hmac_base64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());
5177
}
5178

    
5179
/**
5180
 * Validates a token based on $value, the user session, and the private key.
5181
 *
5182
 * @param $token
5183
 *   The token to be validated.
5184
 * @param $value
5185
 *   An additional value to base the token on.
5186
 * @param $skip_anonymous
5187
 *   Set to true to skip token validation for anonymous users.
5188
 *
5189
 * @return
5190
 *   True for a valid token, false for an invalid token. When $skip_anonymous
5191
 *   is true, the return value will always be true for anonymous users.
5192
 */
5193
function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
5194
  global $user;
5195
  return (($skip_anonymous && $user->uid == 0) || ($token === drupal_get_token($value)));
5196
}
5197

    
5198
function _drupal_bootstrap_full() {
5199
  static $called = FALSE;
5200

    
5201
  if ($called) {
5202
    return;
5203
  }
5204
  $called = TRUE;
5205
  require_once DRUPAL_ROOT . '/' . variable_get('path_inc', 'includes/path.inc');
5206
  require_once DRUPAL_ROOT . '/includes/theme.inc';
5207
  require_once DRUPAL_ROOT . '/includes/pager.inc';
5208
  require_once DRUPAL_ROOT . '/' . variable_get('menu_inc', 'includes/menu.inc');
5209
  require_once DRUPAL_ROOT . '/includes/tablesort.inc';
5210
  require_once DRUPAL_ROOT . '/includes/file.inc';
5211
  require_once DRUPAL_ROOT . '/includes/unicode.inc';
5212
  require_once DRUPAL_ROOT . '/includes/image.inc';
5213
  require_once DRUPAL_ROOT . '/includes/form.inc';
5214
  require_once DRUPAL_ROOT . '/includes/mail.inc';
5215
  require_once DRUPAL_ROOT . '/includes/actions.inc';
5216
  require_once DRUPAL_ROOT . '/includes/ajax.inc';
5217
  require_once DRUPAL_ROOT . '/includes/token.inc';
5218
  require_once DRUPAL_ROOT . '/includes/errors.inc';
5219

    
5220
  // Detect string handling method
5221
  unicode_check();
5222
  // Undo magic quotes
5223
  fix_gpc_magic();
5224
  // Load all enabled modules
5225
  module_load_all();
5226
  // Reset drupal_alter() and module_implements() static caches as these
5227
  // include implementations for vital modules only when called early on
5228
  // in the bootstrap.
5229
  drupal_static_reset('drupal_alter');
5230
  drupal_static_reset('module_implements');
5231
  // Make sure all stream wrappers are registered.
5232
  file_get_stream_wrappers();
5233
  // Ensure mt_rand is reseeded, to prevent random values from one page load
5234
  // being exploited to predict random values in subsequent page loads.
5235
  $seed = unpack("L", drupal_random_bytes(4));
5236
  mt_srand($seed[1]);
5237

    
5238
  $test_info = &$GLOBALS['drupal_test_info'];
5239
  if (!empty($test_info['in_child_site'])) {
5240
    // Running inside the simpletest child site, log fatal errors to test
5241
    // specific file directory.
5242
    ini_set('log_errors', 1);
5243
    ini_set('error_log', 'public://error.log');
5244
  }
5245

    
5246
  // Initialize $_GET['q'] prior to invoking hook_init().
5247
  drupal_path_initialize();
5248

    
5249
  // Let all modules take action before the menu system handles the request.
5250
  // We do not want this while running update.php.
5251
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
5252
    // Prior to invoking hook_init(), initialize the theme (potentially a custom
5253
    // one for this page), so that:
5254
    // - Modules with hook_init() implementations that call theme() or
5255
    //   theme_get_registry() don't initialize the incorrect theme.
5256
    // - The theme can have hook_*_alter() implementations affect page building
5257
    //   (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
5258
    //   ahead of when rendering starts.
5259
    menu_set_custom_theme();
5260
    drupal_theme_initialize();
5261
    module_invoke_all('init');
5262
  }
5263
}
5264

    
5265
/**
5266
 * Stores the current page in the cache.
5267
 *
5268
 * If page_compression is enabled, a gzipped version of the page is stored in
5269
 * the cache to avoid compressing the output on each request. The cache entry
5270
 * is unzipped in the relatively rare event that the page is requested by a
5271
 * client without gzip support.
5272
 *
5273
 * Page compression requires the PHP zlib extension
5274
 * (http://php.net/manual/ref.zlib.php).
5275
 *
5276
 * @see drupal_page_header()
5277
 */
5278
function drupal_page_set_cache() {
5279
  global $base_root;
5280

    
5281
  if (drupal_page_is_cacheable()) {
5282

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

    
5286
    $cache = (object) array(
5287
      'cid' => $base_root . request_uri(),
5288
      'data' => array(
5289
        'path' => $_GET['q'],
5290
        'body' => ob_get_clean(),
5291
        'title' => drupal_get_title(),
5292
        'headers' => array(),
5293
        // We need to store whether page was compressed or not,
5294
        // because by the time it is read, the configuration might change.
5295
        'page_compressed' => $page_compressed,
5296
      ),
5297
      'expire' => CACHE_TEMPORARY,
5298
      'created' => REQUEST_TIME,
5299
    );
5300

    
5301
    // Restore preferred header names based on the lower-case names returned
5302
    // by drupal_get_http_header().
5303
    $header_names = _drupal_set_preferred_header_name();
5304
    foreach (drupal_get_http_header() as $name_lower => $value) {
5305
      $cache->data['headers'][$header_names[$name_lower]] = $value;
5306
      if ($name_lower == 'expires') {
5307
        // Use the actual timestamp from an Expires header if available.
5308
        $cache->expire = strtotime($value);
5309
      }
5310
    }
5311

    
5312
    if ($cache->data['body']) {
5313
      if ($page_compressed) {
5314
        $cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
5315
      }
5316
      cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire);
5317
    }
5318
    return $cache;
5319
  }
5320
}
5321

    
5322
/**
5323
 * Executes a cron run when called.
5324
 *
5325
 * Do not call this function from a test. Use $this->cronRun() instead.
5326
 *
5327
 * @return bool
5328
 *   TRUE if cron ran successfully and FALSE if cron is already running.
5329
 */
5330
function drupal_cron_run() {
5331
  // Allow execution to continue even if the request gets canceled.
5332
  @ignore_user_abort(TRUE);
5333

    
5334
  // Prevent session information from being saved while cron is running.
5335
  $original_session_saving = drupal_save_session();
5336
  drupal_save_session(FALSE);
5337

    
5338
  // Force the current user to anonymous to ensure consistent permissions on
5339
  // cron runs.
5340
  $original_user = $GLOBALS['user'];
5341
  $GLOBALS['user'] = drupal_anonymous_user();
5342

    
5343
  // Try to allocate enough time to run all the hook_cron implementations.
5344
  drupal_set_time_limit(240);
5345

    
5346
  $return = FALSE;
5347
  // Grab the defined cron queues.
5348
  $queues = module_invoke_all('cron_queue_info');
5349
  drupal_alter('cron_queue_info', $queues);
5350

    
5351
  // Try to acquire cron lock.
5352
  if (!lock_acquire('cron', 240.0)) {
5353
    // Cron is still running normally.
5354
    watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
5355
  }
5356
  else {
5357
    // Make sure every queue exists. There is no harm in trying to recreate an
5358
    // existing queue.
5359
    foreach ($queues as $queue_name => $info) {
5360
      DrupalQueue::get($queue_name)->createQueue();
5361
    }
5362

    
5363
    // Iterate through the modules calling their cron handlers (if any):
5364
    foreach (module_implements('cron') as $module) {
5365
      // Do not let an exception thrown by one module disturb another.
5366
      try {
5367
        module_invoke($module, 'cron');
5368
      }
5369
      catch (Exception $e) {
5370
        watchdog_exception('cron', $e);
5371
      }
5372
    }
5373

    
5374
    // Record cron time.
5375
    variable_set('cron_last', REQUEST_TIME);
5376
    watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
5377

    
5378
    // Release cron lock.
5379
    lock_release('cron');
5380

    
5381
    // Return TRUE so other functions can check if it did run successfully
5382
    $return = TRUE;
5383
  }
5384

    
5385
  foreach ($queues as $queue_name => $info) {
5386
    if (!empty($info['skip on cron'])) {
5387
      // Do not run if queue wants to skip.
5388
      continue;
5389
    }
5390
    $callback = $info['worker callback'];
5391
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
5392
    $queue = DrupalQueue::get($queue_name);
5393
    while (time() < $end && ($item = $queue->claimItem())) {
5394
      try {
5395
        call_user_func($callback, $item->data);
5396
        $queue->deleteItem($item);
5397
      }
5398
      catch (Exception $e) {
5399
        // In case of exception log it and leave the item in the queue
5400
        // to be processed again later.
5401
        watchdog_exception('cron', $e);
5402
      }
5403
    }
5404
  }
5405
  // Restore the user.
5406
  $GLOBALS['user'] = $original_user;
5407
  drupal_save_session($original_session_saving);
5408

    
5409
  return $return;
5410
}
5411

    
5412
/**
5413
 * DEPRECATED: Shutdown function: Performs cron cleanup.
5414
 *
5415
 * This function is deprecated because the 'cron_semaphore' variable it
5416
 * references no longer exists. It is therefore no longer used as a shutdown
5417
 * function by Drupal core.
5418
 *
5419
 * @deprecated
5420
 */
5421
function drupal_cron_cleanup() {
5422
  // See if the semaphore is still locked.
5423
  if (variable_get('cron_semaphore', FALSE)) {
5424
    watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);
5425

    
5426
    // Release cron semaphore.
5427
    variable_del('cron_semaphore');
5428
  }
5429
}
5430

    
5431
/**
5432
 * Returns information about system object files (modules, themes, etc.).
5433
 *
5434
 * This function is used to find all or some system object files (module files,
5435
 * theme files, etc.) that exist on the site. It searches in several locations,
5436
 * depending on what type of object you are looking for. For instance, if you
5437
 * are looking for modules and call:
5438
 * @code
5439
 * drupal_system_listing("/\.module$/", "modules", 'name', 0);
5440
 * @endcode
5441
 * this function will search the site-wide modules directory (i.e., /modules/),
5442
 * your installation profile's directory (i.e.,
5443
 * /profiles/your_site_profile/modules/), the all-sites directory (i.e.,
5444
 * /sites/all/modules/), and your site-specific directory (i.e.,
5445
 * /sites/your_site_dir/modules/), in that order, and return information about
5446
 * all of the files ending in .module in those directories.
5447
 *
5448
 * The information is returned in an associative array, which can be keyed on
5449
 * the file name ($key = 'filename'), the file name without the extension ($key
5450
 * = 'name'), or the full file stream URI ($key = 'uri'). If you use a key of
5451
 * 'filename' or 'name', files found later in the search will take precedence
5452
 * over files found earlier (unless they belong to a module or theme not
5453
 * compatible with Drupal core); if you choose a key of 'uri', you will get all
5454
 * files found.
5455
 *
5456
 * @param string $mask
5457
 *   The preg_match() regular expression for the files to find.
5458
 * @param string $directory
5459
 *   The subdirectory name in which the files are found. For example,
5460
 *   'modules' will search in sub-directories of the top-level /modules
5461
 *   directory, sub-directories of /sites/all/modules/, etc.
5462
 * @param string $key
5463
 *   The key to be used for the associative array returned. Possible values are
5464
 *   'uri', for the file's URI; 'filename', for the basename of the file; and
5465
 *   'name' for the name of the file without the extension. If you choose 'name'
5466
 *   or 'filename', only the highest-precedence file will be returned.
5467
 * @param int $min_depth
5468
 *   Minimum depth of directories to return files from, relative to each
5469
 *   directory searched. For instance, a minimum depth of 2 would find modules
5470
 *   inside /modules/node/tests, but not modules directly in /modules/node.
5471
 *
5472
 * @return array
5473
 *   An associative array of file objects, keyed on the chosen key. Each element
5474
 *   in the array is an object containing file information, with properties:
5475
 *   - 'uri': Full URI of the file.
5476
 *   - 'filename': File name.
5477
 *   - 'name': Name of file without the extension.
5478
 */
5479
function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
5480
  $config = conf_path();
5481

    
5482
  $searchdir = array($directory);
5483
  $files = array();
5484

    
5485
  // The 'profiles' directory contains pristine collections of modules and
5486
  // themes as organized by a distribution. It is pristine in the same way
5487
  // that /modules is pristine for core; users should avoid changing anything
5488
  // there in favor of sites/all or sites/<domain> directories.
5489
  $profiles = array();
5490
  $profile = drupal_get_profile();
5491
  // For SimpleTest to be able to test modules packaged together with a
5492
  // distribution we need to include the profile of the parent site (in which
5493
  // test runs are triggered).
5494
  if (drupal_valid_test_ua()) {
5495
    $testing_profile = variable_get('simpletest_parent_profile', FALSE);
5496
    if ($testing_profile && $testing_profile != $profile) {
5497
      $profiles[] = $testing_profile;
5498
    }
5499
  }
5500
  // In case both profile directories contain the same extension, the actual
5501
  // profile always has precedence.
5502
  $profiles[] = $profile;
5503
  foreach ($profiles as $profile) {
5504
    if (file_exists("profiles/$profile/$directory")) {
5505
      $searchdir[] = "profiles/$profile/$directory";
5506
    }
5507
  }
5508

    
5509
  // Always search sites/all/* as well as the global directories.
5510
  $searchdir[] = 'sites/all/' . $directory;
5511

    
5512
  if (file_exists("$config/$directory")) {
5513
    $searchdir[] = "$config/$directory";
5514
  }
5515

    
5516
  // Get current list of items.
5517
  if (!function_exists('file_scan_directory')) {
5518
    require_once DRUPAL_ROOT . '/includes/file.inc';
5519
  }
5520
  foreach ($searchdir as $dir) {
5521
    $files_to_add = file_scan_directory($dir, $mask, array('key' => $key, 'min_depth' => $min_depth));
5522

    
5523
    // Duplicate files found in later search directories take precedence over
5524
    // earlier ones, so we want them to overwrite keys in our resulting
5525
    // $files array.
5526
    // The exception to this is if the later file is from a module or theme not
5527
    // compatible with Drupal core. This may occur during upgrades of Drupal
5528
    // core when new modules exist in core while older contrib modules with the
5529
    // same name exist in a directory such as sites/all/modules/.
5530
    foreach (array_intersect_key($files_to_add, $files) as $file_key => $file) {
5531
      // If it has no info file, then we just behave liberally and accept the
5532
      // new resource on the list for merging.
5533
      if (file_exists($info_file = dirname($file->uri) . '/' . $file->name . '.info')) {
5534
        // Get the .info file for the module or theme this file belongs to.
5535
        $info = drupal_parse_info_file($info_file);
5536

    
5537
        // If the module or theme is incompatible with Drupal core, remove it
5538
        // from the array for the current search directory, so it is not
5539
        // overwritten when merged with the $files array.
5540
        if (isset($info['core']) && $info['core'] != DRUPAL_CORE_COMPATIBILITY) {
5541
          unset($files_to_add[$file_key]);
5542
        }
5543
      }
5544
    }
5545
    $files = array_merge($files, $files_to_add);
5546
  }
5547

    
5548
  return $files;
5549
}
5550

    
5551
/**
5552
 * Sets the main page content value for later use.
5553
 *
5554
 * Given the nature of the Drupal page handling, this will be called once with
5555
 * a string or array. We store that and return it later as the block is being
5556
 * displayed.
5557
 *
5558
 * @param $content
5559
 *   A string or renderable array representing the body of the page.
5560
 *
5561
 * @return
5562
 *   If called without $content, a renderable array representing the body of
5563
 *   the page.
5564
 */
5565
function drupal_set_page_content($content = NULL) {
5566
  $content_block = &drupal_static(__FUNCTION__, NULL);
5567
  $main_content_display = &drupal_static('system_main_content_added', FALSE);
5568

    
5569
  if (!empty($content)) {
5570
    $content_block = (is_array($content) ? $content : array('main' => array('#markup' => $content)));
5571
  }
5572
  else {
5573
    // Indicate that the main content has been requested. We assume that
5574
    // the module requesting the content will be adding it to the page.
5575
    // A module can indicate that it does not handle the content by setting
5576
    // the static variable back to FALSE after calling this function.
5577
    $main_content_display = TRUE;
5578
    return $content_block;
5579
  }
5580
}
5581

    
5582
/**
5583
 * #pre_render callback to render #browsers into #prefix and #suffix.
5584
 *
5585
 * @param $elements
5586
 *   A render array with a '#browsers' property. The '#browsers' property can
5587
 *   contain any or all of the following keys:
5588
 *   - 'IE': If FALSE, the element is not rendered by Internet Explorer. If
5589
 *     TRUE, the element is rendered by Internet Explorer. Can also be a string
5590
 *     containing an expression for Internet Explorer to evaluate as part of a
5591
 *     conditional comment. For example, this can be set to 'lt IE 7' for the
5592
 *     element to be rendered in Internet Explorer 6, but not in Internet
5593
 *     Explorer 7 or higher. Defaults to TRUE.
5594
 *   - '!IE': If FALSE, the element is not rendered by browsers other than
5595
 *     Internet Explorer. If TRUE, the element is rendered by those browsers.
5596
 *     Defaults to TRUE.
5597
 *   Examples:
5598
 *   - To render an element in all browsers, '#browsers' can be left out or set
5599
 *     to array('IE' => TRUE, '!IE' => TRUE).
5600
 *   - To render an element in Internet Explorer only, '#browsers' can be set
5601
 *     to array('!IE' => FALSE).
5602
 *   - To render an element in Internet Explorer 6 only, '#browsers' can be set
5603
 *     to array('IE' => 'lt IE 7', '!IE' => FALSE).
5604
 *   - To render an element in Internet Explorer 8 and higher and in all other
5605
 *     browsers, '#browsers' can be set to array('IE' => 'gte IE 8').
5606
 *
5607
 * @return
5608
 *   The passed-in element with markup for conditional comments potentially
5609
 *   added to '#prefix' and '#suffix'.
5610
 */
5611
function drupal_pre_render_conditional_comments($elements) {
5612
  $browsers = isset($elements['#browsers']) ? $elements['#browsers'] : array();
5613
  $browsers += array(
5614
    'IE' => TRUE,
5615
    '!IE' => TRUE,
5616
  );
5617

    
5618
  // If rendering in all browsers, no need for conditional comments.
5619
  if ($browsers['IE'] === TRUE && $browsers['!IE']) {
5620
    return $elements;
5621
  }
5622

    
5623
  // Determine the conditional comment expression for Internet Explorer to
5624
  // evaluate.
5625
  if ($browsers['IE'] === TRUE) {
5626
    $expression = 'IE';
5627
  }
5628
  elseif ($browsers['IE'] === FALSE) {
5629
    $expression = '!IE';
5630
  }
5631
  else {
5632
    $expression = $browsers['IE'];
5633
  }
5634

    
5635
  // Wrap the element's potentially existing #prefix and #suffix properties with
5636
  // conditional comment markup. The conditional comment expression is evaluated
5637
  // by Internet Explorer only. To control the rendering by other browsers,
5638
  // either the "downlevel-hidden" or "downlevel-revealed" technique must be
5639
  // used. See http://en.wikipedia.org/wiki/Conditional_comment for details.
5640
  $elements += array(
5641
    '#prefix' => '',
5642
    '#suffix' => '',
5643
  );
5644
  if (!$browsers['!IE']) {
5645
    // "downlevel-hidden".
5646
    $elements['#prefix'] = "\n<!--[if $expression]>\n" . $elements['#prefix'];
5647
    $elements['#suffix'] .= "<![endif]-->\n";
5648
  }
5649
  else {
5650
    // "downlevel-revealed".
5651
    $elements['#prefix'] = "\n<!--[if $expression]><!-->\n" . $elements['#prefix'];
5652
    $elements['#suffix'] .= "<!--<![endif]-->\n";
5653
  }
5654

    
5655
  return $elements;
5656
}
5657

    
5658
/**
5659
 * #pre_render callback to render a link into #markup.
5660
 *
5661
 * Doing so during pre_render gives modules a chance to alter the link parts.
5662
 *
5663
 * @param $elements
5664
 *   A structured array whose keys form the arguments to l():
5665
 *   - #title: The link text to pass as argument to l().
5666
 *   - #href: The URL path component to pass as argument to l().
5667
 *   - #options: (optional) An array of options to pass to l().
5668
 *
5669
 * @return
5670
 *   The passed-in elements containing a rendered link in '#markup'.
5671
 */
5672
function drupal_pre_render_link($element) {
5673
  // By default, link options to pass to l() are normally set in #options.
5674
  $element += array('#options' => array());
5675
  // However, within the scope of renderable elements, #attributes is a valid
5676
  // way to specify attributes, too. Take them into account, but do not override
5677
  // attributes from #options.
5678
  if (isset($element['#attributes'])) {
5679
    $element['#options'] += array('attributes' => array());
5680
    $element['#options']['attributes'] += $element['#attributes'];
5681
  }
5682

    
5683
  // This #pre_render callback can be invoked from inside or outside of a Form
5684
  // API context, and depending on that, a HTML ID may be already set in
5685
  // different locations. #options should have precedence over Form API's #id.
5686
  // #attributes have been taken over into #options above already.
5687
  if (isset($element['#options']['attributes']['id'])) {
5688
    $element['#id'] = $element['#options']['attributes']['id'];
5689
  }
5690
  elseif (isset($element['#id'])) {
5691
    $element['#options']['attributes']['id'] = $element['#id'];
5692
  }
5693

    
5694
  // Conditionally invoke ajax_pre_render_element(), if #ajax is set.
5695
  if (isset($element['#ajax']) && !isset($element['#ajax_processed'])) {
5696
    // If no HTML ID was found above, automatically create one.
5697
    if (!isset($element['#id'])) {
5698
      $element['#id'] = $element['#options']['attributes']['id'] = drupal_html_id('ajax-link');
5699
    }
5700
    // If #ajax['path] was not specified, use the href as Ajax request URL.
5701
    if (!isset($element['#ajax']['path'])) {
5702
      $element['#ajax']['path'] = $element['#href'];
5703
      $element['#ajax']['options'] = $element['#options'];
5704
    }
5705
    $element = ajax_pre_render_element($element);
5706
  }
5707

    
5708
  $element['#markup'] = l($element['#title'], $element['#href'], $element['#options']);
5709
  return $element;
5710
}
5711

    
5712
/**
5713
 * #pre_render callback that collects child links into a single array.
5714
 *
5715
 * This function can be added as a pre_render callback for a renderable array,
5716
 * usually one which will be themed by theme_links(). It iterates through all
5717
 * unrendered children of the element, collects any #links properties it finds,
5718
 * merges them into the parent element's #links array, and prevents those
5719
 * children from being rendered separately.
5720
 *
5721
 * The purpose of this is to allow links to be logically grouped into related
5722
 * categories, so that each child group can be rendered as its own list of
5723
 * links if drupal_render() is called on it, but calling drupal_render() on the
5724
 * parent element will still produce a single list containing all the remaining
5725
 * links, regardless of what group they were in.
5726
 *
5727
 * A typical example comes from node links, which are stored in a renderable
5728
 * array similar to this:
5729
 * @code
5730
 * $node->content['links'] = array(
5731
 *   '#theme' => 'links__node',
5732
 *   '#pre_render' => array('drupal_pre_render_links'),
5733
 *   'comment' => array(
5734
 *     '#theme' => 'links__node__comment',
5735
 *     '#links' => array(
5736
 *       // An array of links associated with node comments, suitable for
5737
 *       // passing in to theme_links().
5738
 *     ),
5739
 *   ),
5740
 *   'statistics' => array(
5741
 *     '#theme' => 'links__node__statistics',
5742
 *     '#links' => array(
5743
 *       // An array of links associated with node statistics, suitable for
5744
 *       // passing in to theme_links().
5745
 *     ),
5746
 *   ),
5747
 *   'translation' => array(
5748
 *     '#theme' => 'links__node__translation',
5749
 *     '#links' => array(
5750
 *       // An array of links associated with node translation, suitable for
5751
 *       // passing in to theme_links().
5752
 *     ),
5753
 *   ),
5754
 * );
5755
 * @endcode
5756
 *
5757
 * In this example, the links are grouped by functionality, which can be
5758
 * helpful to themers who want to display certain kinds of links independently.
5759
 * For example, adding this code to node.tpl.php will result in the comment
5760
 * links being rendered as a single list:
5761
 * @code
5762
 * print render($content['links']['comment']);
5763
 * @endcode
5764
 *
5765
 * (where $node->content has been transformed into $content before handing
5766
 * control to the node.tpl.php template).
5767
 *
5768
 * The pre_render function defined here allows the above flexibility, but also
5769
 * allows the following code to be used to render all remaining links into a
5770
 * single list, regardless of their group:
5771
 * @code
5772
 * print render($content['links']);
5773
 * @endcode
5774
 *
5775
 * In the above example, this will result in the statistics and translation
5776
 * links being rendered together in a single list (but not the comment links,
5777
 * which were rendered previously on their own).
5778
 *
5779
 * Because of the way this function works, the individual properties of each
5780
 * group (for example, a group-specific #theme property such as
5781
 * 'links__node__comment' in the example above, or any other property such as
5782
 * #attributes or #pre_render that is attached to it) are only used when that
5783
 * group is rendered on its own. When the group is rendered together with other
5784
 * children, these child-specific properties are ignored, and only the overall
5785
 * properties of the parent are used.
5786
 */
5787
function drupal_pre_render_links($element) {
5788
  $element += array('#links' => array());
5789
  foreach (element_children($element) as $key) {
5790
    $child = &$element[$key];
5791
    // If the child has links which have not been printed yet and the user has
5792
    // access to it, merge its links in to the parent.
5793
    if (isset($child['#links']) && empty($child['#printed']) && (!isset($child['#access']) || $child['#access'])) {
5794
      $element['#links'] += $child['#links'];
5795
      // Mark the child as having been printed already (so that its links
5796
      // cannot be mistakenly rendered twice).
5797
      $child['#printed'] = TRUE;
5798
    }
5799
  }
5800
  return $element;
5801
}
5802

    
5803
/**
5804
 * #pre_render callback to append contents in #markup to #children.
5805
 *
5806
 * This needs to be a #pre_render callback, because eventually assigned
5807
 * #theme_wrappers will expect the element's rendered content in #children.
5808
 * Note that if also a #theme is defined for the element, then the result of
5809
 * the theme callback will override #children.
5810
 *
5811
 * @param $elements
5812
 *   A structured array using the #markup key.
5813
 *
5814
 * @return
5815
 *   The passed-in elements, but #markup appended to #children.
5816
 *
5817
 * @see drupal_render()
5818
 */
5819
function drupal_pre_render_markup($elements) {
5820
  $elements['#children'] = $elements['#markup'];
5821
  return $elements;
5822
}
5823

    
5824
/**
5825
 * Renders the page, including all theming.
5826
 *
5827
 * @param $page
5828
 *   A string or array representing the content of a page. The array consists of
5829
 *   the following keys:
5830
 *   - #type: Value is always 'page'. This pushes the theming through
5831
 *     page.tpl.php (required).
5832
 *   - #show_messages: Suppress drupal_get_message() items. Used by Batch
5833
 *     API (optional).
5834
 *
5835
 * @see hook_page_alter()
5836
 * @see element_info()
5837
 */
5838
function drupal_render_page($page) {
5839
  $main_content_display = &drupal_static('system_main_content_added', FALSE);
5840

    
5841
  // Allow menu callbacks to return strings or arbitrary arrays to render.
5842
  // If the array returned is not of #type page directly, we need to fill
5843
  // in the page with defaults.
5844
  if (is_string($page) || (is_array($page) && (!isset($page['#type']) || ($page['#type'] != 'page')))) {
5845
    drupal_set_page_content($page);
5846
    $page = element_info('page');
5847
  }
5848

    
5849
  // Modules can add elements to $page as needed in hook_page_build().
5850
  foreach (module_implements('page_build') as $module) {
5851
    $function = $module . '_page_build';
5852
    $function($page);
5853
  }
5854
  // Modules alter the $page as needed. Blocks are populated into regions like
5855
  // 'sidebar_first', 'footer', etc.
5856
  drupal_alter('page', $page);
5857

    
5858
  // If no module has taken care of the main content, add it to the page now.
5859
  // This allows the site to still be usable even if no modules that
5860
  // control page regions (for example, the Block module) are enabled.
5861
  if (!$main_content_display) {
5862
    $page['content']['system_main'] = drupal_set_page_content();
5863
  }
5864

    
5865
  return drupal_render($page);
5866
}
5867

    
5868
/**
5869
 * Renders HTML given a structured array tree.
5870
 *
5871
 * Recursively iterates over each of the array elements, generating HTML code.
5872
 *
5873
 * Renderable arrays have two kinds of key/value pairs: properties and
5874
 * children. Properties have keys starting with '#' and their values influence
5875
 * how the array will be rendered. Children are all elements whose keys do not
5876
 * start with a '#'. Their values should be renderable arrays themselves,
5877
 * which will be rendered during the rendering of the parent array. The markup
5878
 * provided by the children is typically inserted into the markup generated by
5879
 * the parent array.
5880
 *
5881
 * HTML generation for a renderable array, and the treatment of any children,
5882
 * is controlled by two properties containing theme functions, #theme and
5883
 * #theme_wrappers.
5884
 *
5885
 * #theme is the theme function called first. If it is set and the element has
5886
 * any children, it is the responsibility of the theme function to render
5887
 * these children. For elements that are not allowed to have any children,
5888
 * e.g. buttons or textfields, the theme function can be used to render the
5889
 * element itself. If #theme is not present and the element has children, each
5890
 * child is itself rendered by a call to drupal_render(), and the results are
5891
 * concatenated.
5892
 *
5893
 * The #theme_wrappers property contains an array of theme functions which will
5894
 * be called, in order, after #theme has run. These can be used to add further
5895
 * markup around the rendered children; e.g., fieldsets add the required markup
5896
 * for a fieldset around their rendered child elements. All wrapper theme
5897
 * functions have to include the element's #children property in their output,
5898
 * as it contains the output of the previous theme functions and the rendered
5899
 * children.
5900
 *
5901
 * For example, for the form element type, by default only the #theme_wrappers
5902
 * property is set, which adds the form markup around the rendered child
5903
 * elements of the form. This allows you to set the #theme property on a
5904
 * specific form to a custom theme function, giving you complete control over
5905
 * the placement of the form's children while not at all having to deal with
5906
 * the form markup itself.
5907
 *
5908
 * drupal_render() can optionally cache the rendered output of elements to
5909
 * improve performance. To use drupal_render() caching, set the element's #cache
5910
 * property to an associative array with one or several of the following keys:
5911
 * - 'keys': An array of one or more keys that identify the element. If 'keys'
5912
 *   is set, the cache ID is created automatically from these keys. See
5913
 *   drupal_render_cid_create().
5914
 * - 'granularity' (optional): Define the cache granularity using binary
5915
 *   combinations of the cache granularity constants, e.g.
5916
 *   DRUPAL_CACHE_PER_USER to cache for each user separately or
5917
 *   DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE to cache separately for each
5918
 *   page and role. If not specified the element is cached globally for each
5919
 *   theme and language.
5920
 * - 'cid': Specify the cache ID directly. Either 'keys' or 'cid' is required.
5921
 *   If 'cid' is set, 'keys' and 'granularity' are ignored. Use only if you
5922
 *   have special requirements.
5923
 * - 'expire': Set to one of the cache lifetime constants.
5924
 * - 'bin': Specify a cache bin to cache the element in. Defaults to 'cache'.
5925
 *
5926
 * This function is usually called from within another function, like
5927
 * drupal_get_form() or a theme function. Elements are sorted internally
5928
 * using uasort(). Since this is expensive, when passing already sorted
5929
 * elements to drupal_render(), for example from a database query, set
5930
 * $elements['#sorted'] = TRUE to avoid sorting them a second time.
5931
 *
5932
 * drupal_render() flags each element with a '#printed' status to indicate that
5933
 * the element has been rendered, which allows individual elements of a given
5934
 * array to be rendered independently and prevents them from being rendered
5935
 * more than once on subsequent calls to drupal_render() (e.g., as part of a
5936
 * larger array). If the same array or array element is passed more than once
5937
 * to drupal_render(), it simply returns an empty string.
5938
 *
5939
 * @param array $elements
5940
 *   The structured array describing the data to be rendered.
5941
 *
5942
 * @return string
5943
 *   The rendered HTML.
5944
 */
5945
function drupal_render(&$elements) {
5946
  // Early-return nothing if user does not have access.
5947
  if (empty($elements) || (isset($elements['#access']) && !$elements['#access'])) {
5948
    return '';
5949
  }
5950

    
5951
  // Do not print elements twice.
5952
  if (!empty($elements['#printed'])) {
5953
    return '';
5954
  }
5955

    
5956
  // Try to fetch the element's markup from cache and return.
5957
  if (isset($elements['#cache'])) {
5958
    $cached_output = drupal_render_cache_get($elements);
5959
    if ($cached_output !== FALSE) {
5960
      return $cached_output;
5961
    }
5962
  }
5963

    
5964
  // If #markup is set, ensure #type is set. This allows to specify just #markup
5965
  // on an element without setting #type.
5966
  if (isset($elements['#markup']) && !isset($elements['#type'])) {
5967
    $elements['#type'] = 'markup';
5968
  }
5969

    
5970
  // If the default values for this element have not been loaded yet, populate
5971
  // them.
5972
  if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
5973
    $elements += element_info($elements['#type']);
5974
  }
5975

    
5976
  // Make any final changes to the element before it is rendered. This means
5977
  // that the $element or the children can be altered or corrected before the
5978
  // element is rendered into the final text.
5979
  if (isset($elements['#pre_render'])) {
5980
    foreach ($elements['#pre_render'] as $function) {
5981
      if (function_exists($function)) {
5982
        $elements = $function($elements);
5983
      }
5984
    }
5985
  }
5986

    
5987
  // Allow #pre_render to abort rendering.
5988
  if (!empty($elements['#printed'])) {
5989
    return '';
5990
  }
5991

    
5992
  // Get the children of the element, sorted by weight.
5993
  $children = element_children($elements, TRUE);
5994

    
5995
  // Initialize this element's #children, unless a #pre_render callback already
5996
  // preset #children.
5997
  if (!isset($elements['#children'])) {
5998
    $elements['#children'] = '';
5999
  }
6000
  // Call the element's #theme function if it is set. Then any children of the
6001
  // element have to be rendered there.
6002
  if (isset($elements['#theme'])) {
6003
    $elements['#children'] = theme($elements['#theme'], $elements);
6004
  }
6005
  // If #theme was not set and the element has children, render them now.
6006
  // This is the same process as drupal_render_children() but is inlined
6007
  // for speed.
6008
  if ($elements['#children'] == '') {
6009
    foreach ($children as $key) {
6010
      $elements['#children'] .= drupal_render($elements[$key]);
6011
    }
6012
  }
6013

    
6014
  // Let the theme functions in #theme_wrappers add markup around the rendered
6015
  // children.
6016
  if (isset($elements['#theme_wrappers'])) {
6017
    foreach ($elements['#theme_wrappers'] as $theme_wrapper) {
6018
      $elements['#children'] = theme($theme_wrapper, $elements);
6019
    }
6020
  }
6021

    
6022
  // Filter the outputted content and make any last changes before the
6023
  // content is sent to the browser. The changes are made on $content
6024
  // which allows the output'ed text to be filtered.
6025
  if (isset($elements['#post_render'])) {
6026
    foreach ($elements['#post_render'] as $function) {
6027
      if (function_exists($function)) {
6028
        $elements['#children'] = $function($elements['#children'], $elements);
6029
      }
6030
    }
6031
  }
6032

    
6033
  // Add any JavaScript state information associated with the element.
6034
  if (!empty($elements['#states'])) {
6035
    drupal_process_states($elements);
6036
  }
6037

    
6038
  // Add additional libraries, CSS, JavaScript an other custom
6039
  // attached data associated with this element.
6040
  if (!empty($elements['#attached'])) {
6041
    drupal_process_attached($elements);
6042
  }
6043

    
6044
  $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
6045
  $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
6046
  $output = $prefix . $elements['#children'] . $suffix;
6047

    
6048
  // Cache the processed element if #cache is set.
6049
  if (isset($elements['#cache'])) {
6050
    drupal_render_cache_set($output, $elements);
6051
  }
6052

    
6053
  $elements['#printed'] = TRUE;
6054
  return $output;
6055
}
6056

    
6057
/**
6058
 * Renders children of an element and concatenates them.
6059
 *
6060
 * @param array $element
6061
 *   The structured array whose children shall be rendered.
6062
 * @param array $children_keys
6063
 *   (optional) If the keys of the element's children are already known, they
6064
 *   can be passed in to save another run of element_children().
6065
 *
6066
 * @return string
6067
 *   The rendered HTML of all children of the element.
6068

    
6069
 * @see drupal_render()
6070
 */
6071
function drupal_render_children(&$element, $children_keys = NULL) {
6072
  if ($children_keys === NULL) {
6073
    $children_keys = element_children($element);
6074
  }
6075
  $output = '';
6076
  foreach ($children_keys as $key) {
6077
    if (!empty($element[$key])) {
6078
      $output .= drupal_render($element[$key]);
6079
    }
6080
  }
6081
  return $output;
6082
}
6083

    
6084
/**
6085
 * Renders an element.
6086
 *
6087
 * This function renders an element using drupal_render(). The top level
6088
 * element is shown with show() before rendering, so it will always be rendered
6089
 * even if hide() had been previously used on it.
6090
 *
6091
 * @param $element
6092
 *   The element to be rendered.
6093
 *
6094
 * @return
6095
 *   The rendered element.
6096
 *
6097
 * @see drupal_render()
6098
 * @see show()
6099
 * @see hide()
6100
 */
6101
function render(&$element) {
6102
  if (is_array($element)) {
6103
    show($element);
6104
    return drupal_render($element);
6105
  }
6106
  else {
6107
    // Safe-guard for inappropriate use of render() on flat variables: return
6108
    // the variable as-is.
6109
    return $element;
6110
  }
6111
}
6112

    
6113
/**
6114
 * Hides an element from later rendering.
6115
 *
6116
 * The first time render() or drupal_render() is called on an element tree,
6117
 * as each element in the tree is rendered, it is marked with a #printed flag
6118
 * and the rendered children of the element are cached. Subsequent calls to
6119
 * render() or drupal_render() will not traverse the child tree of this element
6120
 * again: they will just use the cached children. So if you want to hide an
6121
 * element, be sure to call hide() on the element before its parent tree is
6122
 * rendered for the first time, as it will have no effect on subsequent
6123
 * renderings of the parent tree.
6124
 *
6125
 * @param $element
6126
 *   The element to be hidden.
6127
 *
6128
 * @return
6129
 *   The element.
6130
 *
6131
 * @see render()
6132
 * @see show()
6133
 */
6134
function hide(&$element) {
6135
  $element['#printed'] = TRUE;
6136
  return $element;
6137
}
6138

    
6139
/**
6140
 * Shows a hidden element for later rendering.
6141
 *
6142
 * You can also use render($element), which shows the element while rendering
6143
 * it.
6144
 *
6145
 * The first time render() or drupal_render() is called on an element tree,
6146
 * as each element in the tree is rendered, it is marked with a #printed flag
6147
 * and the rendered children of the element are cached. Subsequent calls to
6148
 * render() or drupal_render() will not traverse the child tree of this element
6149
 * again: they will just use the cached children. So if you want to show an
6150
 * element, be sure to call show() on the element before its parent tree is
6151
 * rendered for the first time, as it will have no effect on subsequent
6152
 * renderings of the parent tree.
6153
 *
6154
 * @param $element
6155
 *   The element to be shown.
6156
 *
6157
 * @return
6158
 *   The element.
6159
 *
6160
 * @see render()
6161
 * @see hide()
6162
 */
6163
function show(&$element) {
6164
  $element['#printed'] = FALSE;
6165
  return $element;
6166
}
6167

    
6168
/**
6169
 * Gets the rendered output of a renderable element from the cache.
6170
 *
6171
 * @param $elements
6172
 *   A renderable array.
6173
 *
6174
 * @return
6175
 *   A markup string containing the rendered content of the element, or FALSE
6176
 *   if no cached copy of the element is available.
6177
 *
6178
 * @see drupal_render()
6179
 * @see drupal_render_cache_set()
6180
 */
6181
function drupal_render_cache_get($elements) {
6182
  if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
6183
    return FALSE;
6184
  }
6185
  $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
6186

    
6187
  if (!empty($cid) && $cache = cache_get($cid, $bin)) {
6188
    // Add additional libraries, JavaScript, CSS and other data attached
6189
    // to this element.
6190
    if (isset($cache->data['#attached'])) {
6191
      drupal_process_attached($cache->data);
6192
    }
6193
    // Return the rendered output.
6194
    return $cache->data['#markup'];
6195
  }
6196
  return FALSE;
6197
}
6198

    
6199
/**
6200
 * Caches the rendered output of a renderable element.
6201
 *
6202
 * This is called by drupal_render() if the #cache property is set on an
6203
 * element.
6204
 *
6205
 * @param $markup
6206
 *   The rendered output string of $elements.
6207
 * @param $elements
6208
 *   A renderable array.
6209
 *
6210
 * @see drupal_render_cache_get()
6211
 */
6212
function drupal_render_cache_set(&$markup, $elements) {
6213
  // Create the cache ID for the element.
6214
  if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
6215
    return FALSE;
6216
  }
6217

    
6218
  // Cache implementations are allowed to modify the markup, to support
6219
  // replacing markup with edge-side include commands. The supporting cache
6220
  // backend will store the markup in some other key (like
6221
  // $data['#real-value']) and return an include command instead. When the
6222
  // ESI command is executed by the content accelerator, the real value can
6223
  // be retrieved and used.
6224
  $data['#markup'] = &$markup;
6225
  // Persist attached data associated with this element.
6226
  $attached = drupal_render_collect_attached($elements, TRUE);
6227
  if ($attached) {
6228
    $data['#attached'] = $attached;
6229
  }
6230
  $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
6231
  $expire = isset($elements['#cache']['expire']) ? $elements['#cache']['expire'] : CACHE_PERMANENT;
6232
  cache_set($cid, $data, $bin, $expire);
6233
}
6234

    
6235
/**
6236
 * Collects #attached for an element and its children into a single array.
6237
 *
6238
 * When caching elements, it is necessary to collect all libraries, JavaScript
6239
 * and CSS into a single array, from both the element itself and all child
6240
 * elements. This allows drupal_render() to add these back to the page when the
6241
 * element is returned from cache.
6242
 *
6243
 * @param $elements
6244
 *   The element to collect #attached from.
6245
 * @param $return
6246
 *   Whether to return the attached elements and reset the internal static.
6247
 *
6248
 * @return
6249
 *   The #attached array for this element and its descendants.
6250
 */
6251
function drupal_render_collect_attached($elements, $return = FALSE) {
6252
  $attached = &drupal_static(__FUNCTION__, array());
6253

    
6254
  // Collect all #attached for this element.
6255
  if (isset($elements['#attached'])) {
6256
    foreach ($elements['#attached'] as $key => $value) {
6257
      if (!isset($attached[$key])) {
6258
        $attached[$key] = array();
6259
      }
6260
      $attached[$key] = array_merge($attached[$key], $value);
6261
    }
6262
  }
6263
  if ($children = element_children($elements)) {
6264
    foreach ($children as $child) {
6265
      drupal_render_collect_attached($elements[$child]);
6266
    }
6267
  }
6268

    
6269
  // If this was the first call to the function, return all attached elements
6270
  // and reset the static cache.
6271
  if ($return) {
6272
    $return = $attached;
6273
    $attached = array();
6274
    return $return;
6275
  }
6276
}
6277

    
6278
/**
6279
 * Prepares an element for caching based on a query.
6280
 *
6281
 * This smart caching strategy saves Drupal from querying and rendering to HTML
6282
 * when the underlying query is unchanged.
6283
 *
6284
 * Expensive queries should use the query builder to create the query and then
6285
 * call this function. Executing the query and formatting results should happen
6286
 * in a #pre_render callback.
6287
 *
6288
 * @param $query
6289
 *   A select query object as returned by db_select().
6290
 * @param $function
6291
 *   The name of the function doing this caching. A _pre_render suffix will be
6292
 *   added to this string and is also part of the cache key in
6293
 *   drupal_render_cache_set() and drupal_render_cache_get().
6294
 * @param $expire
6295
 *   The cache expire time, passed eventually to cache_set().
6296
 * @param $granularity
6297
 *   One or more granularity constants passed to drupal_render_cid_parts().
6298
 *
6299
 * @return
6300
 *   A renderable array with the following keys and values:
6301
 *   - #query: The passed-in $query.
6302
 *   - #pre_render: $function with a _pre_render suffix.
6303
 *   - #cache: An associative array prepared for drupal_render_cache_set().
6304
 */
6305
function drupal_render_cache_by_query($query, $function, $expire = CACHE_TEMPORARY, $granularity = NULL) {
6306
  $cache_keys = array_merge(array($function), drupal_render_cid_parts($granularity));
6307
  $query->preExecute();
6308
  $cache_keys[] = hash('sha256', serialize(array((string) $query, $query->getArguments())));
6309
  return array(
6310
    '#query' => $query,
6311
    '#pre_render' => array($function . '_pre_render'),
6312
    '#cache' => array(
6313
      'keys' => $cache_keys,
6314
      'expire' => $expire,
6315
    ),
6316
  );
6317
}
6318

    
6319
/**
6320
 * Returns cache ID parts for building a cache ID.
6321
 *
6322
 * @param $granularity
6323
 *   One or more cache granularity constants. For example, to cache separately
6324
 *   for each user, use DRUPAL_CACHE_PER_USER. To cache separately for each
6325
 *   page and role, use the expression:
6326
 *   @code
6327
 *   DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE
6328
 *   @endcode
6329
 *
6330
 * @return
6331
 *   An array of cache ID parts, always containing the active theme. If the
6332
 *   locale module is enabled it also contains the active language. If
6333
 *   $granularity was passed in, more parts are added.
6334
 */
6335
function drupal_render_cid_parts($granularity = NULL) {
6336
  global $theme, $base_root, $user;
6337

    
6338
  $cid_parts[] = $theme;
6339
  // If Locale is enabled but we have only one language we do not need it as cid
6340
  // part.
6341
  if (drupal_multilingual()) {
6342
    foreach (language_types_configurable() as $language_type) {
6343
      $cid_parts[] = $GLOBALS[$language_type]->language;
6344
    }
6345
  }
6346

    
6347
  if (!empty($granularity)) {
6348
    $cache_per_role = $granularity & DRUPAL_CACHE_PER_ROLE;
6349
    $cache_per_user = $granularity & DRUPAL_CACHE_PER_USER;
6350
    // User 1 has special permissions outside of the role system, so when
6351
    // caching per role is requested, it should cache per user instead.
6352
    if ($user->uid == 1 && $cache_per_role) {
6353
      $cache_per_user = TRUE;
6354
      $cache_per_role = FALSE;
6355
    }
6356
    // 'PER_ROLE' and 'PER_USER' are mutually exclusive. 'PER_USER' can be a
6357
    // resource drag for sites with many users, so when a module is being
6358
    // equivocal, we favor the less expensive 'PER_ROLE' pattern.
6359
    if ($cache_per_role) {
6360
      $cid_parts[] = 'r.' . implode(',', array_keys($user->roles));
6361
    }
6362
    elseif ($cache_per_user) {
6363
      $cid_parts[] = "u.$user->uid";
6364
    }
6365

    
6366
    if ($granularity & DRUPAL_CACHE_PER_PAGE) {
6367
      $cid_parts[] = $base_root . request_uri();
6368
    }
6369
  }
6370

    
6371
  return $cid_parts;
6372
}
6373

    
6374
/**
6375
 * Creates the cache ID for a renderable element.
6376
 *
6377
 * This creates the cache ID string, either by returning the #cache['cid']
6378
 * property if present or by building the cache ID out of the #cache['keys']
6379
 * and, optionally, the #cache['granularity'] properties.
6380
 *
6381
 * @param $elements
6382
 *   A renderable array.
6383
 *
6384
 * @return
6385
 *   The cache ID string, or FALSE if the element may not be cached.
6386
 */
6387
function drupal_render_cid_create($elements) {
6388
  if (isset($elements['#cache']['cid'])) {
6389
    return $elements['#cache']['cid'];
6390
  }
6391
  elseif (isset($elements['#cache']['keys'])) {
6392
    $granularity = isset($elements['#cache']['granularity']) ? $elements['#cache']['granularity'] : NULL;
6393
    // Merge in additional cache ID parts based provided by drupal_render_cid_parts().
6394
    $cid_parts = array_merge($elements['#cache']['keys'], drupal_render_cid_parts($granularity));
6395
    return implode(':', $cid_parts);
6396
  }
6397
  return FALSE;
6398
}
6399

    
6400
/**
6401
 * Function used by uasort to sort structured arrays by weight.
6402
 */
6403
function element_sort($a, $b) {
6404
  $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
6405
  $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
6406
  if ($a_weight == $b_weight) {
6407
    return 0;
6408
  }
6409
  return ($a_weight < $b_weight) ? -1 : 1;
6410
}
6411

    
6412
/**
6413
 * Array sorting callback; sorts elements by title.
6414
 */
6415
function element_sort_by_title($a, $b) {
6416
  $a_title = (is_array($a) && isset($a['#title'])) ? $a['#title'] : '';
6417
  $b_title = (is_array($b) && isset($b['#title'])) ? $b['#title'] : '';
6418
  return strnatcasecmp($a_title, $b_title);
6419
}
6420

    
6421
/**
6422
 * Retrieves the default properties for the defined element type.
6423
 *
6424
 * @param $type
6425
 *   An element type as defined by hook_element_info().
6426
 */
6427
function element_info($type) {
6428
  // Use the advanced drupal_static() pattern, since this is called very often.
6429
  static $drupal_static_fast;
6430
  if (!isset($drupal_static_fast)) {
6431
    $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__);
6432
  }
6433
  $cache = &$drupal_static_fast['cache'];
6434

    
6435
  if (!isset($cache)) {
6436
    $cache = module_invoke_all('element_info');
6437
    foreach ($cache as $element_type => $info) {
6438
      $cache[$element_type]['#type'] = $element_type;
6439
    }
6440
    // Allow modules to alter the element type defaults.
6441
    drupal_alter('element_info', $cache);
6442
  }
6443

    
6444
  return isset($cache[$type]) ? $cache[$type] : array();
6445
}
6446

    
6447
/**
6448
 * Retrieves a single property for the defined element type.
6449
 *
6450
 * @param $type
6451
 *   An element type as defined by hook_element_info().
6452
 * @param $property_name
6453
 *   The property within the element type that should be returned.
6454
 * @param $default
6455
 *   (Optional) The value to return if the element type does not specify a
6456
 *   value for the property. Defaults to NULL.
6457
 */
6458
function element_info_property($type, $property_name, $default = NULL) {
6459
  return (($info = element_info($type)) && array_key_exists($property_name, $info)) ? $info[$property_name] : $default;
6460
}
6461

    
6462
/**
6463
 * Sorts a structured array by the 'weight' element.
6464
 *
6465
 * Note that the sorting is by the 'weight' array element, not by the render
6466
 * element property '#weight'.
6467
 *
6468
 * Callback for uasort() used in various functions.
6469
 *
6470
 * @param $a
6471
 *   First item for comparison. The compared items should be associative arrays
6472
 *   that optionally include a 'weight' element. For items without a 'weight'
6473
 *   element, a default value of 0 will be used.
6474
 * @param $b
6475
 *   Second item for comparison.
6476
 */
6477
function drupal_sort_weight($a, $b) {
6478
  $a_weight = (is_array($a) && isset($a['weight'])) ? $a['weight'] : 0;
6479
  $b_weight = (is_array($b) && isset($b['weight'])) ? $b['weight'] : 0;
6480
  if ($a_weight == $b_weight) {
6481
    return 0;
6482
  }
6483
  return ($a_weight < $b_weight) ? -1 : 1;
6484
}
6485

    
6486
/**
6487
 * Array sorting callback; sorts elements by 'title' key.
6488
 */
6489
function drupal_sort_title($a, $b) {
6490
  if (!isset($b['title'])) {
6491
    return -1;
6492
  }
6493
  if (!isset($a['title'])) {
6494
    return 1;
6495
  }
6496
  return strcasecmp($a['title'], $b['title']);
6497
}
6498

    
6499
/**
6500
 * Checks if the key is a property.
6501
 */
6502
function element_property($key) {
6503
  return $key[0] == '#';
6504
}
6505

    
6506
/**
6507
 * Gets properties of a structured array element (keys beginning with '#').
6508
 */
6509
function element_properties($element) {
6510
  return array_filter(array_keys((array) $element), 'element_property');
6511
}
6512

    
6513
/**
6514
 * Checks if the key is a child.
6515
 */
6516
function element_child($key) {
6517
  return !isset($key[0]) || $key[0] != '#';
6518
}
6519

    
6520
/**
6521
 * Identifies the children of an element array, optionally sorted by weight.
6522
 *
6523
 * The children of a element array are those key/value pairs whose key does
6524
 * not start with a '#'. See drupal_render() for details.
6525
 *
6526
 * @param $elements
6527
 *   The element array whose children are to be identified.
6528
 * @param $sort
6529
 *   Boolean to indicate whether the children should be sorted by weight.
6530
 *
6531
 * @return
6532
 *   The array keys of the element's children.
6533
 */
6534
function element_children(&$elements, $sort = FALSE) {
6535
  // Do not attempt to sort elements which have already been sorted.
6536
  $sort = isset($elements['#sorted']) ? !$elements['#sorted'] : $sort;
6537

    
6538
  // Filter out properties from the element, leaving only children.
6539
  $children = array();
6540
  $sortable = FALSE;
6541
  foreach ($elements as $key => $value) {
6542
    if ($key === '' || $key[0] !== '#') {
6543
      $children[$key] = $value;
6544
      if (is_array($value) && isset($value['#weight'])) {
6545
        $sortable = TRUE;
6546
      }
6547
    }
6548
  }
6549
  // Sort the children if necessary.
6550
  if ($sort && $sortable) {
6551
    uasort($children, 'element_sort');
6552
    // Put the sorted children back into $elements in the correct order, to
6553
    // preserve sorting if the same element is passed through
6554
    // element_children() twice.
6555
    foreach ($children as $key => $child) {
6556
      unset($elements[$key]);
6557
      $elements[$key] = $child;
6558
    }
6559
    $elements['#sorted'] = TRUE;
6560
  }
6561

    
6562
  return array_keys($children);
6563
}
6564

    
6565
/**
6566
 * Returns the visible children of an element.
6567
 *
6568
 * @param $elements
6569
 *   The parent element.
6570
 *
6571
 * @return
6572
 *   The array keys of the element's visible children.
6573
 */
6574
function element_get_visible_children(array $elements) {
6575
  $visible_children = array();
6576

    
6577
  foreach (element_children($elements) as $key) {
6578
    $child = $elements[$key];
6579

    
6580
    // Skip un-accessible children.
6581
    if (isset($child['#access']) && !$child['#access']) {
6582
      continue;
6583
    }
6584

    
6585
    // Skip value and hidden elements, since they are not rendered.
6586
    if (isset($child['#type']) && in_array($child['#type'], array('value', 'hidden'))) {
6587
      continue;
6588
    }
6589

    
6590
    $visible_children[$key] = $child;
6591
  }
6592

    
6593
  return array_keys($visible_children);
6594
}
6595

    
6596
/**
6597
 * Sets HTML attributes based on element properties.
6598
 *
6599
 * @param $element
6600
 *   The renderable element to process.
6601
 * @param $map
6602
 *   An associative array whose keys are element property names and whose values
6603
 *   are the HTML attribute names to set for corresponding the property; e.g.,
6604
 *   array('#propertyname' => 'attributename'). If both names are identical
6605
 *   except for the leading '#', then an attribute name value is sufficient and
6606
 *   no property name needs to be specified.
6607
 */
6608
function element_set_attributes(array &$element, array $map) {
6609
  foreach ($map as $property => $attribute) {
6610
    // If the key is numeric, the attribute name needs to be taken over.
6611
    if (is_int($property)) {
6612
      $property = '#' . $attribute;
6613
    }
6614
    // Do not overwrite already existing attributes.
6615
    if (isset($element[$property]) && !isset($element['#attributes'][$attribute])) {
6616
      $element['#attributes'][$attribute] = $element[$property];
6617
    }
6618
  }
6619
}
6620

    
6621
/**
6622
 * Recursively computes the difference of arrays with additional index check.
6623
 *
6624
 * This is a version of array_diff_assoc() that supports multidimensional
6625
 * arrays.
6626
 *
6627
 * @param array $array1
6628
 *   The array to compare from.
6629
 * @param array $array2
6630
 *   The array to compare to.
6631
 *
6632
 * @return array
6633
 *   Returns an array containing all the values from array1 that are not present
6634
 *   in array2.
6635
 */
6636
function drupal_array_diff_assoc_recursive($array1, $array2) {
6637
  $difference = array();
6638

    
6639
  foreach ($array1 as $key => $value) {
6640
    if (is_array($value)) {
6641
      if (!array_key_exists($key, $array2) || !is_array($array2[$key])) {
6642
        $difference[$key] = $value;
6643
      }
6644
      else {
6645
        $new_diff = drupal_array_diff_assoc_recursive($value, $array2[$key]);
6646
        if (!empty($new_diff)) {
6647
          $difference[$key] = $new_diff;
6648
        }
6649
      }
6650
    }
6651
    elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
6652
      $difference[$key] = $value;
6653
    }
6654
  }
6655

    
6656
  return $difference;
6657
}
6658

    
6659
/**
6660
 * Sets a value in a nested array with variable depth.
6661
 *
6662
 * This helper function should be used when the depth of the array element you
6663
 * are changing may vary (that is, the number of parent keys is variable). It
6664
 * is primarily used for form structures and renderable arrays.
6665
 *
6666
 * Example:
6667
 * @code
6668
 * // Assume you have a 'signature' element somewhere in a form. It might be:
6669
 * $form['signature_settings']['signature'] = array(
6670
 *   '#type' => 'text_format',
6671
 *   '#title' => t('Signature'),
6672
 * );
6673
 * // Or, it might be further nested:
6674
 * $form['signature_settings']['user']['signature'] = array(
6675
 *   '#type' => 'text_format',
6676
 *   '#title' => t('Signature'),
6677
 * );
6678
 * @endcode
6679
 *
6680
 * To deal with the situation, the code needs to figure out the route to the
6681
 * element, given an array of parents that is either
6682
 * @code array('signature_settings', 'signature') @endcode in the first case or
6683
 * @code array('signature_settings', 'user', 'signature') @endcode in the second
6684
 * case.
6685
 *
6686
 * Without this helper function the only way to set the signature element in one
6687
 * line would be using eval(), which should be avoided:
6688
 * @code
6689
 * // Do not do this! Avoid eval().
6690
 * eval('$form[\'' . implode("']['", $parents) . '\'] = $element;');
6691
 * @endcode
6692
 *
6693
 * Instead, use this helper function:
6694
 * @code
6695
 * drupal_array_set_nested_value($form, $parents, $element);
6696
 * @endcode
6697
 *
6698
 * However if the number of array parent keys is static, the value should always
6699
 * be set directly rather than calling this function. For instance, for the
6700
 * first example we could just do:
6701
 * @code
6702
 * $form['signature_settings']['signature'] = $element;
6703
 * @endcode
6704
 *
6705
 * @param $array
6706
 *   A reference to the array to modify.
6707
 * @param $parents
6708
 *   An array of parent keys, starting with the outermost key.
6709
 * @param $value
6710
 *   The value to set.
6711
 * @param $force
6712
 *   (Optional) If TRUE, the value is forced into the structure even if it
6713
 *   requires the deletion of an already existing non-array parent value. If
6714
 *   FALSE, PHP throws an error if trying to add into a value that is not an
6715
 *   array. Defaults to FALSE.
6716
 *
6717
 * @see drupal_array_get_nested_value()
6718
 */
6719
function drupal_array_set_nested_value(array &$array, array $parents, $value, $force = FALSE) {
6720
  $ref = &$array;
6721
  foreach ($parents as $parent) {
6722
    // PHP auto-creates container arrays and NULL entries without error if $ref
6723
    // is NULL, but throws an error if $ref is set, but not an array.
6724
    if ($force && isset($ref) && !is_array($ref)) {
6725
      $ref = array();
6726
    }
6727
    $ref = &$ref[$parent];
6728
  }
6729
  $ref = $value;
6730
}
6731

    
6732
/**
6733
 * Retrieves a value from a nested array with variable depth.
6734
 *
6735
 * This helper function should be used when the depth of the array element being
6736
 * retrieved may vary (that is, the number of parent keys is variable). It is
6737
 * primarily used for form structures and renderable arrays.
6738
 *
6739
 * Without this helper function the only way to get a nested array value with
6740
 * variable depth in one line would be using eval(), which should be avoided:
6741
 * @code
6742
 * // Do not do this! Avoid eval().
6743
 * // May also throw a PHP notice, if the variable array keys do not exist.
6744
 * eval('$value = $array[\'' . implode("']['", $parents) . "'];");
6745
 * @endcode
6746
 *
6747
 * Instead, use this helper function:
6748
 * @code
6749
 * $value = drupal_array_get_nested_value($form, $parents);
6750
 * @endcode
6751
 *
6752
 * A return value of NULL is ambiguous, and can mean either that the requested
6753
 * key does not exist, or that the actual value is NULL. If it is required to
6754
 * know whether the nested array key actually exists, pass a third argument that
6755
 * is altered by reference:
6756
 * @code
6757
 * $key_exists = NULL;
6758
 * $value = drupal_array_get_nested_value($form, $parents, $key_exists);
6759
 * if ($key_exists) {
6760
 *   // ... do something with $value ...
6761
 * }
6762
 * @endcode
6763
 *
6764
 * However if the number of array parent keys is static, the value should always
6765
 * be retrieved directly rather than calling this function. For instance:
6766
 * @code
6767
 * $value = $form['signature_settings']['signature'];
6768
 * @endcode
6769
 *
6770
 * @param $array
6771
 *   The array from which to get the value.
6772
 * @param $parents
6773
 *   An array of parent keys of the value, starting with the outermost key.
6774
 * @param $key_exists
6775
 *   (optional) If given, an already defined variable that is altered by
6776
 *   reference.
6777
 *
6778
 * @return
6779
 *   The requested nested value. Possibly NULL if the value is NULL or not all
6780
 *   nested parent keys exist. $key_exists is altered by reference and is a
6781
 *   Boolean that indicates whether all nested parent keys exist (TRUE) or not
6782
 *   (FALSE). This allows to distinguish between the two possibilities when NULL
6783
 *   is returned.
6784
 *
6785
 * @see drupal_array_set_nested_value()
6786
 */
6787
function &drupal_array_get_nested_value(array &$array, array $parents, &$key_exists = NULL) {
6788
  $ref = &$array;
6789
  foreach ($parents as $parent) {
6790
    if (is_array($ref) && array_key_exists($parent, $ref)) {
6791
      $ref = &$ref[$parent];
6792
    }
6793
    else {
6794
      $key_exists = FALSE;
6795
      $null = NULL;
6796
      return $null;
6797
    }
6798
  }
6799
  $key_exists = TRUE;
6800
  return $ref;
6801
}
6802

    
6803
/**
6804
 * Determines whether a nested array contains the requested keys.
6805
 *
6806
 * This helper function should be used when the depth of the array element to be
6807
 * checked may vary (that is, the number of parent keys is variable). See
6808
 * drupal_array_set_nested_value() for details. It is primarily used for form
6809
 * structures and renderable arrays.
6810
 *
6811
 * If it is required to also get the value of the checked nested key, use
6812
 * drupal_array_get_nested_value() instead.
6813
 *
6814
 * If the number of array parent keys is static, this helper function is
6815
 * unnecessary and the following code can be used instead:
6816
 * @code
6817
 * $value_exists = isset($form['signature_settings']['signature']);
6818
 * $key_exists = array_key_exists('signature', $form['signature_settings']);
6819
 * @endcode
6820
 *
6821
 * @param $array
6822
 *   The array with the value to check for.
6823
 * @param $parents
6824
 *   An array of parent keys of the value, starting with the outermost key.
6825
 *
6826
 * @return
6827
 *   TRUE if all the parent keys exist, FALSE otherwise.
6828
 *
6829
 * @see drupal_array_get_nested_value()
6830
 */
6831
function drupal_array_nested_key_exists(array $array, array $parents) {
6832
  // Although this function is similar to PHP's array_key_exists(), its
6833
  // arguments should be consistent with drupal_array_get_nested_value().
6834
  $key_exists = NULL;
6835
  drupal_array_get_nested_value($array, $parents, $key_exists);
6836
  return $key_exists;
6837
}
6838

    
6839
/**
6840
 * Provides theme registration for themes across .inc files.
6841
 */
6842
function drupal_common_theme() {
6843
  return array(
6844
    // From theme.inc.
6845
    'html' => array(
6846
      'render element' => 'page',
6847
      'template' => 'html',
6848
    ),
6849
    'page' => array(
6850
      'render element' => 'page',
6851
      'template' => 'page',
6852
    ),
6853
    'region' => array(
6854
      'render element' => 'elements',
6855
      'template' => 'region',
6856
    ),
6857
    'status_messages' => array(
6858
      'variables' => array('display' => NULL),
6859
    ),
6860
    'link' => array(
6861
      'variables' => array('text' => NULL, 'path' => NULL, 'options' => array()),
6862
    ),
6863
    'links' => array(
6864
      'variables' => array('links' => NULL, 'attributes' => array('class' => array('links')), 'heading' => array()),
6865
    ),
6866
    'image' => array(
6867
      // HTML 4 and XHTML 1.0 always require an alt attribute. The HTML 5 draft
6868
      // allows the alt attribute to be omitted in some cases. Therefore,
6869
      // default the alt attribute to an empty string, but allow code calling
6870
      // theme('image') to pass explicit NULL for it to be omitted. Usually,
6871
      // neither omission nor an empty string satisfies accessibility
6872
      // requirements, so it is strongly encouraged for code calling
6873
      // theme('image') to pass a meaningful value for the alt variable.
6874
      // - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
6875
      // - http://www.w3.org/TR/xhtml1/dtds.html
6876
      // - http://dev.w3.org/html5/spec/Overview.html#alt
6877
      // The title attribute is optional in all cases, so it is omitted by
6878
      // default.
6879
      'variables' => array('path' => NULL, 'width' => NULL, 'height' => NULL, 'alt' => '', 'title' => NULL, 'attributes' => array()),
6880
    ),
6881
    'breadcrumb' => array(
6882
      'variables' => array('breadcrumb' => NULL),
6883
    ),
6884
    'help' => array(
6885
      'variables' => array(),
6886
    ),
6887
    'table' => array(
6888
      'variables' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL, 'colgroups' => array(), 'sticky' => TRUE, 'empty' => ''),
6889
    ),
6890
    'tablesort_indicator' => array(
6891
      'variables' => array('style' => NULL),
6892
    ),
6893
    'mark' => array(
6894
      'variables' => array('type' => MARK_NEW),
6895
    ),
6896
    'item_list' => array(
6897
      'variables' => array('items' => array(), 'title' => NULL, 'type' => 'ul', 'attributes' => array()),
6898
    ),
6899
    'more_help_link' => array(
6900
      'variables' => array('url' => NULL),
6901
    ),
6902
    'feed_icon' => array(
6903
      'variables' => array('url' => NULL, 'title' => NULL),
6904
    ),
6905
    'more_link' => array(
6906
      'variables' => array('url' => NULL, 'title' => NULL)
6907
    ),
6908
    'username' => array(
6909
      'variables' => array('account' => NULL),
6910
    ),
6911
    'progress_bar' => array(
6912
      'variables' => array('percent' => NULL, 'message' => NULL),
6913
    ),
6914
    'indentation' => array(
6915
      'variables' => array('size' => 1),
6916
    ),
6917
    'html_tag' => array(
6918
      'render element' => 'element',
6919
    ),
6920
    // From theme.maintenance.inc.
6921
    'maintenance_page' => array(
6922
      'variables' => array('content' => NULL, 'show_messages' => TRUE),
6923
      'template' => 'maintenance-page',
6924
    ),
6925
    'update_page' => array(
6926
      'variables' => array('content' => NULL, 'show_messages' => TRUE),
6927
    ),
6928
    'install_page' => array(
6929
      'variables' => array('content' => NULL),
6930
    ),
6931
    'task_list' => array(
6932
      'variables' => array('items' => NULL, 'active' => NULL),
6933
    ),
6934
    'authorize_message' => array(
6935
      'variables' => array('message' => NULL, 'success' => TRUE),
6936
    ),
6937
    'authorize_report' => array(
6938
      'variables' => array('messages' => array()),
6939
    ),
6940
    // From pager.inc.
6941
    'pager' => array(
6942
      'variables' => array('tags' => array(), 'element' => 0, 'parameters' => array(), 'quantity' => 9),
6943
    ),
6944
    'pager_first' => array(
6945
      'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
6946
    ),
6947
    'pager_previous' => array(
6948
      'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
6949
    ),
6950
    'pager_next' => array(
6951
      'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
6952
    ),
6953
    'pager_last' => array(
6954
      'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
6955
    ),
6956
    'pager_link' => array(
6957
      'variables' => array('text' => NULL, 'page_new' => NULL, 'element' => NULL, 'parameters' => array(), 'attributes' => array()),
6958
    ),
6959
    // From menu.inc.
6960
    'menu_link' => array(
6961
      'render element' => 'element',
6962
    ),
6963
    'menu_tree' => array(
6964
      'render element' => 'tree',
6965
    ),
6966
    'menu_local_task' => array(
6967
      'render element' => 'element',
6968
    ),
6969
    'menu_local_action' => array(
6970
      'render element' => 'element',
6971
    ),
6972
    'menu_local_tasks' => array(
6973
      'variables' => array('primary' => array(), 'secondary' => array()),
6974
    ),
6975
    // From form.inc.
6976
    'select' => array(
6977
      'render element' => 'element',
6978
    ),
6979
    'fieldset' => array(
6980
      'render element' => 'element',
6981
    ),
6982
    'radio' => array(
6983
      'render element' => 'element',
6984
    ),
6985
    'radios' => array(
6986
      'render element' => 'element',
6987
    ),
6988
    'date' => array(
6989
      'render element' => 'element',
6990
    ),
6991
    'exposed_filters' => array(
6992
      'render element' => 'form',
6993
    ),
6994
    'checkbox' => array(
6995
      'render element' => 'element',
6996
    ),
6997
    'checkboxes' => array(
6998
      'render element' => 'element',
6999
    ),
7000
    'button' => array(
7001
      'render element' => 'element',
7002
    ),
7003
    'image_button' => array(
7004
      'render element' => 'element',
7005
    ),
7006
    'hidden' => array(
7007
      'render element' => 'element',
7008
    ),
7009
    'textfield' => array(
7010
      'render element' => 'element',
7011
    ),
7012
    'form' => array(
7013
      'render element' => 'element',
7014
    ),
7015
    'textarea' => array(
7016
      'render element' => 'element',
7017
    ),
7018
    'password' => array(
7019
      'render element' => 'element',
7020
    ),
7021
    'file' => array(
7022
      'render element' => 'element',
7023
    ),
7024
    'tableselect' => array(
7025
      'render element' => 'element',
7026
    ),
7027
    'form_element' => array(
7028
      'render element' => 'element',
7029
    ),
7030
    'form_required_marker' => array(
7031
      'render element' => 'element',
7032
    ),
7033
    'form_element_label' => array(
7034
      'render element' => 'element',
7035
    ),
7036
    'vertical_tabs' => array(
7037
      'render element' => 'element',
7038
    ),
7039
    'container' => array(
7040
      'render element' => 'element',
7041
    ),
7042
  );
7043
}
7044

    
7045
/**
7046
 * @addtogroup schemaapi
7047
 * @{
7048
 */
7049

    
7050
/**
7051
 * Creates all tables defined in a module's hook_schema().
7052
 *
7053
 * Note: This function does not pass the module's schema through
7054
 * hook_schema_alter(). The module's tables will be created exactly as the
7055
 * module defines them.
7056
 *
7057
 * @param $module
7058
 *   The module for which the tables will be created.
7059
 */
7060
function drupal_install_schema($module) {
7061
  $schema = drupal_get_schema_unprocessed($module);
7062
  _drupal_schema_initialize($schema, $module, FALSE);
7063

    
7064
  foreach ($schema as $name => $table) {
7065
    db_create_table($name, $table);
7066
  }
7067
}
7068

    
7069
/**
7070
 * Removes all tables defined in a module's hook_schema().
7071
 *
7072
 * Note: This function does not pass the module's schema through
7073
 * hook_schema_alter(). The module's tables will be created exactly as the
7074
 * module defines them.
7075
 *
7076
 * @param $module
7077
 *   The module for which the tables will be removed.
7078
 *
7079
 * @return
7080
 *   An array of arrays with the following key/value pairs:
7081
 *    - success: a boolean indicating whether the query succeeded.
7082
 *    - query: the SQL query(s) executed, passed through check_plain().
7083
 */
7084
function drupal_uninstall_schema($module) {
7085
  $schema = drupal_get_schema_unprocessed($module);
7086
  _drupal_schema_initialize($schema, $module, FALSE);
7087

    
7088
  foreach ($schema as $table) {
7089
    if (db_table_exists($table['name'])) {
7090
      db_drop_table($table['name']);
7091
    }
7092
  }
7093
}
7094

    
7095
/**
7096
 * Returns the unprocessed and unaltered version of a module's schema.
7097
 *
7098
 * Use this function only if you explicitly need the original
7099
 * specification of a schema, as it was defined in a module's
7100
 * hook_schema(). No additional default values will be set,
7101
 * hook_schema_alter() is not invoked and these unprocessed
7102
 * definitions won't be cached. To retrieve the schema after
7103
 * hook_schema_alter() has been invoked use drupal_get_schema().
7104
 *
7105
 * This function can be used to retrieve a schema specification in
7106
 * hook_schema(), so it allows you to derive your tables from existing
7107
 * specifications.
7108
 *
7109
 * It is also used by drupal_install_schema() and
7110
 * drupal_uninstall_schema() to ensure that a module's tables are
7111
 * created exactly as specified without any changes introduced by a
7112
 * module that implements hook_schema_alter().
7113
 *
7114
 * @param $module
7115
 *   The module to which the table belongs.
7116
 * @param $table
7117
 *   The name of the table. If not given, the module's complete schema
7118
 *   is returned.
7119
 */
7120
function drupal_get_schema_unprocessed($module, $table = NULL) {
7121
  // Load the .install file to get hook_schema.
7122
  module_load_install($module);
7123
  $schema = module_invoke($module, 'schema');
7124

    
7125
  if (isset($table) && isset($schema[$table])) {
7126
    return $schema[$table];
7127
  }
7128
  elseif (!empty($schema)) {
7129
    return $schema;
7130
  }
7131
  return array();
7132
}
7133

    
7134
/**
7135
 * Fills in required default values for table definitions from hook_schema().
7136
 *
7137
 * @param $schema
7138
 *   The schema definition array as it was returned by the module's
7139
 *   hook_schema().
7140
 * @param $module
7141
 *   The module for which hook_schema() was invoked.
7142
 * @param $remove_descriptions
7143
 *   (optional) Whether to additionally remove 'description' keys of all tables
7144
 *   and fields to improve performance of serialize() and unserialize().
7145
 *   Defaults to TRUE.
7146
 */
7147
function _drupal_schema_initialize(&$schema, $module, $remove_descriptions = TRUE) {
7148
  // Set the name and module key for all tables.
7149
  foreach ($schema as $name => &$table) {
7150
    if (empty($table['module'])) {
7151
      $table['module'] = $module;
7152
    }
7153
    if (!isset($table['name'])) {
7154
      $table['name'] = $name;
7155
    }
7156
    if ($remove_descriptions) {
7157
      unset($table['description']);
7158
      foreach ($table['fields'] as &$field) {
7159
        unset($field['description']);
7160
      }
7161
    }
7162
  }
7163
}
7164

    
7165
/**
7166
 * Retrieves the type for every field in a table schema.
7167
 *
7168
 * @param $table
7169
 *   The name of the table from which to retrieve type information.
7170
 *
7171
 * @return
7172
 *   An array of types, keyed by field name.
7173
 */
7174
function drupal_schema_field_types($table) {
7175
  $table_schema = drupal_get_schema($table);
7176
  $field_types = array();
7177
  foreach ($table_schema['fields'] as $field_name => $field_info) {
7178
    $field_types[$field_name] = isset($field_info['type']) ? $field_info['type'] : NULL;
7179
  }
7180
  return $field_types;
7181
}
7182

    
7183
/**
7184
 * Retrieves a list of fields from a table schema.
7185
 *
7186
 * The returned list is suitable for use in an SQL query.
7187
 *
7188
 * @param $table
7189
 *   The name of the table from which to retrieve fields.
7190
 * @param
7191
 *   An optional prefix to to all fields.
7192
 *
7193
 * @return An array of fields.
7194
 */
7195
function drupal_schema_fields_sql($table, $prefix = NULL) {
7196
  $schema = drupal_get_schema($table);
7197
  $fields = array_keys($schema['fields']);
7198
  if ($prefix) {
7199
    $columns = array();
7200
    foreach ($fields as $field) {
7201
      $columns[] = "$prefix.$field";
7202
    }
7203
    return $columns;
7204
  }
7205
  else {
7206
    return $fields;
7207
  }
7208
}
7209

    
7210
/**
7211
 * Saves (inserts or updates) a record to the database based upon the schema.
7212
 *
7213
 * Do not use drupal_write_record() within hook_update_N() functions, since the
7214
 * database schema cannot be relied upon when a user is running a series of
7215
 * updates. Instead, use db_insert() or db_update() to save the record.
7216
 *
7217
 * @param $table
7218
 *   The name of the table; this must be defined by a hook_schema()
7219
 *   implementation.
7220
 * @param $record
7221
 *   An object or array representing the record to write, passed in by
7222
 *   reference. If inserting a new record, values not provided in $record will
7223
 *   be populated in $record and in the database with the default values from
7224
 *   the schema, as well as a single serial (auto-increment) field (if present).
7225
 *   If updating an existing record, only provided values are updated in the
7226
 *   database, and $record is not modified.
7227
 * @param $primary_keys
7228
 *   To indicate that this is a new record to be inserted, omit this argument.
7229
 *   If this is an update, this argument specifies the primary keys' field
7230
 *   names. If there is only 1 field in the key, you may pass in a string; if
7231
 *   there are multiple fields in the key, pass in an array.
7232
 *
7233
 * @return
7234
 *   If the record insert or update failed, returns FALSE. If it succeeded,
7235
 *   returns SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
7236
 */
7237
function drupal_write_record($table, &$record, $primary_keys = array()) {
7238
  // Standardize $primary_keys to an array.
7239
  if (is_string($primary_keys)) {
7240
    $primary_keys = array($primary_keys);
7241
  }
7242

    
7243
  $schema = drupal_get_schema($table);
7244
  if (empty($schema)) {
7245
    return FALSE;
7246
  }
7247

    
7248
  $object = (object) $record;
7249
  $fields = array();
7250

    
7251
  // Go through the schema to determine fields to write.
7252
  foreach ($schema['fields'] as $field => $info) {
7253
    if ($info['type'] == 'serial') {
7254
      // Skip serial types if we are updating.
7255
      if (!empty($primary_keys)) {
7256
        continue;
7257
      }
7258
      // Track serial field so we can helpfully populate them after the query.
7259
      // NOTE: Each table should come with one serial field only.
7260
      $serial = $field;
7261
    }
7262

    
7263
    // Skip field if it is in $primary_keys as it is unnecessary to update a
7264
    // field to the value it is already set to.
7265
    if (in_array($field, $primary_keys)) {
7266
      continue;
7267
    }
7268

    
7269
    if (!property_exists($object, $field)) {
7270
      // Skip fields that are not provided, default values are already known
7271
      // by the database.
7272
      continue;
7273
    }
7274

    
7275
    // Build array of fields to update or insert.
7276
    if (empty($info['serialize'])) {
7277
      $fields[$field] = $object->$field;
7278
    }
7279
    else {
7280
      $fields[$field] = serialize($object->$field);
7281
    }
7282

    
7283
    // Type cast to proper datatype, except when the value is NULL and the
7284
    // column allows this.
7285
    //
7286
    // MySQL PDO silently casts e.g. FALSE and '' to 0 when inserting the value
7287
    // into an integer column, but PostgreSQL PDO does not. Also type cast NULL
7288
    // when the column does not allow this.
7289
    if (isset($object->$field) || !empty($info['not null'])) {
7290
      if ($info['type'] == 'int' || $info['type'] == 'serial') {
7291
        $fields[$field] = (int) $fields[$field];
7292
      }
7293
      elseif ($info['type'] == 'float') {
7294
        $fields[$field] = (float) $fields[$field];
7295
      }
7296
      else {
7297
        $fields[$field] = (string) $fields[$field];
7298
      }
7299
    }
7300
  }
7301

    
7302
  if (empty($fields)) {
7303
    return;
7304
  }
7305

    
7306
  // Build the SQL.
7307
  if (empty($primary_keys)) {
7308
    // We are doing an insert.
7309
    $options = array('return' => Database::RETURN_INSERT_ID);
7310
    if (isset($serial) && isset($fields[$serial])) {
7311
      // If the serial column has been explicitly set with an ID, then we don't
7312
      // require the database to return the last insert id.
7313
      if ($fields[$serial]) {
7314
        $options['return'] = Database::RETURN_AFFECTED;
7315
      }
7316
      // If a serial column does exist with no value (i.e. 0) then remove it as
7317
      // the database will insert the correct value for us.
7318
      else {
7319
        unset($fields[$serial]);
7320
      }
7321
    }
7322
    $query = db_insert($table, $options)->fields($fields);
7323
    $return = SAVED_NEW;
7324
  }
7325
  else {
7326
    $query = db_update($table)->fields($fields);
7327
    foreach ($primary_keys as $key) {
7328
      $query->condition($key, $object->$key);
7329
    }
7330
    $return = SAVED_UPDATED;
7331
  }
7332

    
7333
  // Execute the SQL.
7334
  if ($query_return = $query->execute()) {
7335
    if (isset($serial)) {
7336
      // If the database was not told to return the last insert id, it will be
7337
      // because we already know it.
7338
      if (isset($options) && $options['return'] != Database::RETURN_INSERT_ID) {
7339
        $object->$serial = $fields[$serial];
7340
      }
7341
      else {
7342
        $object->$serial = $query_return;
7343
      }
7344
    }
7345
  }
7346
  // If we have a single-field primary key but got no insert ID, the
7347
  // query failed. Note that we explicitly check for FALSE, because
7348
  // a valid update query which doesn't change any values will return
7349
  // zero (0) affected rows.
7350
  elseif ($query_return === FALSE && count($primary_keys) == 1) {
7351
    $return = FALSE;
7352
  }
7353

    
7354
  // If we are inserting, populate empty fields with default values.
7355
  if (empty($primary_keys)) {
7356
    foreach ($schema['fields'] as $field => $info) {
7357
      if (isset($info['default']) && !property_exists($object, $field)) {
7358
        $object->$field = $info['default'];
7359
      }
7360
    }
7361
  }
7362

    
7363
  // If we began with an array, convert back.
7364
  if (is_array($record)) {
7365
    $record = (array) $object;
7366
  }
7367

    
7368
  return $return;
7369
}
7370

    
7371
/**
7372
 * @} End of "addtogroup schemaapi".
7373
 */
7374

    
7375
/**
7376
 * Parses Drupal module and theme .info files.
7377
 *
7378
 * Info files are NOT for placing arbitrary theme and module-specific settings.
7379
 * Use variable_get() and variable_set() for that.
7380
 *
7381
 * Information stored in a module .info file:
7382
 * - name: The real name of the module for display purposes.
7383
 * - description: A brief description of the module.
7384
 * - dependencies: An array of dependency strings. Each is in the form
7385
 *   'project:module (versions)'; with the following meanings:
7386
 *   - project: (optional) Project shortname, recommended to ensure uniqueness,
7387
 *     if the module is part of a project hosted on drupal.org. If omitted,
7388
 *     also omit the : that follows. The project name is currently ignored by
7389
 *     Drupal core but is used for automated testing.
7390
 *   - module: (required) Module shortname within the project.
7391
 *   - (versions): Optional version information, consisting of one or more
7392
 *     comma-separated operator/value pairs or simply version numbers, which
7393
 *     can contain "x" as a wildcard. Examples: (>=7.22, <7.28), (7.x-3.x).
7394
 * - package: The name of the package of modules this module belongs to.
7395
 *
7396
 * See forum.info for an example of a module .info file.
7397
 *
7398
 * Information stored in a theme .info file:
7399
 * - name: The real name of the theme for display purposes.
7400
 * - description: Brief description.
7401
 * - screenshot: Path to screenshot relative to the theme's .info file.
7402
 * - engine: Theme engine; typically phptemplate.
7403
 * - base: Name of a base theme, if applicable; e.g., base = zen.
7404
 * - regions: Listed regions; e.g., region[left] = Left sidebar.
7405
 * - features: Features available; e.g., features[] = logo.
7406
 * - stylesheets: Theme stylesheets; e.g., stylesheets[all][] = my-style.css.
7407
 * - scripts: Theme scripts; e.g., scripts[] = my-script.js.
7408
 *
7409
 * See bartik.info for an example of a theme .info file.
7410
 *
7411
 * @param $filename
7412
 *   The file we are parsing. Accepts file with relative or absolute path.
7413
 *
7414
 * @return
7415
 *   The info array.
7416
 *
7417
 * @see drupal_parse_info_format()
7418
 */
7419
function drupal_parse_info_file($filename) {
7420
  $info = &drupal_static(__FUNCTION__, array());
7421

    
7422
  if (!isset($info[$filename])) {
7423
    if (!file_exists($filename)) {
7424
      $info[$filename] = array();
7425
    }
7426
    else {
7427
      $data = file_get_contents($filename);
7428
      $info[$filename] = drupal_parse_info_format($data);
7429
    }
7430
  }
7431
  return $info[$filename];
7432
}
7433

    
7434
/**
7435
 * Parses data in Drupal's .info format.
7436
 *
7437
 * Data should be in an .ini-like format to specify values. White-space
7438
 * generally doesn't matter, except inside values:
7439
 * @code
7440
 *   key = value
7441
 *   key = "value"
7442
 *   key = 'value'
7443
 *   key = "multi-line
7444
 *   value"
7445
 *   key = 'multi-line
7446
 *   value'
7447
 *   key
7448
 *   =
7449
 *   'value'
7450
 * @endcode
7451
 *
7452
 * Arrays are created using a HTTP GET alike syntax:
7453
 * @code
7454
 *   key[] = "numeric array"
7455
 *   key[index] = "associative array"
7456
 *   key[index][] = "nested numeric array"
7457
 *   key[index][index] = "nested associative array"
7458
 * @endcode
7459
 *
7460
 * PHP constants are substituted in, but only when used as the entire value.
7461
 * Comments should start with a semi-colon at the beginning of a line.
7462
 *
7463
 * @param $data
7464
 *   A string to parse.
7465
 *
7466
 * @return
7467
 *   The info array.
7468
 *
7469
 * @see drupal_parse_info_file()
7470
 */
7471
function drupal_parse_info_format($data) {
7472
  $info = array();
7473

    
7474
  if (preg_match_all('
7475
    @^\s*                           # Start at the beginning of a line, ignoring leading whitespace
7476
    ((?:
7477
      [^=;\[\]]|                    # Key names cannot contain equal signs, semi-colons or square brackets,
7478
      \[[^\[\]]*\]                  # unless they are balanced and not nested
7479
    )+?)
7480
    \s*=\s*                         # Key/value pairs are separated by equal signs (ignoring white-space)
7481
    (?:
7482
      ("(?:[^"]|(?<=\\\\)")*")|     # Double-quoted string, which may contain slash-escaped quotes/slashes
7483
      (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
7484
      ([^\r\n]*?)                   # Non-quoted string
7485
    )\s*$                           # Stop at the next end of a line, ignoring trailing whitespace
7486
    @msx', $data, $matches, PREG_SET_ORDER)) {
7487
    foreach ($matches as $match) {
7488
      // Fetch the key and value string.
7489
      $i = 0;
7490
      foreach (array('key', 'value1', 'value2', 'value3') as $var) {
7491
        $$var = isset($match[++$i]) ? $match[$i] : '';
7492
      }
7493
      $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
7494

    
7495
      // Parse array syntax.
7496
      $keys = preg_split('/\]?\[/', rtrim($key, ']'));
7497
      $last = array_pop($keys);
7498
      $parent = &$info;
7499

    
7500
      // Create nested arrays.
7501
      foreach ($keys as $key) {
7502
        if ($key == '') {
7503
          $key = count($parent);
7504
        }
7505
        if (!isset($parent[$key]) || !is_array($parent[$key])) {
7506
          $parent[$key] = array();
7507
        }
7508
        $parent = &$parent[$key];
7509
      }
7510

    
7511
      // Handle PHP constants.
7512
      if (preg_match('/^\w+$/i', $value) && defined($value)) {
7513
        $value = constant($value);
7514
      }
7515

    
7516
      // Insert actual value.
7517
      if ($last == '') {
7518
        $last = count($parent);
7519
      }
7520
      $parent[$last] = $value;
7521
    }
7522
  }
7523

    
7524
  return $info;
7525
}
7526

    
7527
/**
7528
 * Returns a list of severity levels, as defined in RFC 3164.
7529
 *
7530
 * @return
7531
 *   Array of the possible severity levels for log messages.
7532
 *
7533
 * @see http://www.ietf.org/rfc/rfc3164.txt
7534
 * @see watchdog()
7535
 * @ingroup logging_severity_levels
7536
 */
7537
function watchdog_severity_levels() {
7538
  return array(
7539
    WATCHDOG_EMERGENCY => t('emergency'),
7540
    WATCHDOG_ALERT     => t('alert'),
7541
    WATCHDOG_CRITICAL  => t('critical'),
7542
    WATCHDOG_ERROR     => t('error'),
7543
    WATCHDOG_WARNING   => t('warning'),
7544
    WATCHDOG_NOTICE    => t('notice'),
7545
    WATCHDOG_INFO      => t('info'),
7546
    WATCHDOG_DEBUG     => t('debug'),
7547
  );
7548
}
7549

    
7550

    
7551
/**
7552
 * Explodes a string of tags into an array.
7553
 *
7554
 * @see drupal_implode_tags()
7555
 */
7556
function drupal_explode_tags($tags) {
7557
  // This regexp allows the following types of user input:
7558
  // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
7559
  $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
7560
  preg_match_all($regexp, $tags, $matches);
7561
  $typed_tags = array_unique($matches[1]);
7562

    
7563
  $tags = array();
7564
  foreach ($typed_tags as $tag) {
7565
    // If a user has escaped a term (to demonstrate that it is a group,
7566
    // or includes a comma or quote character), we remove the escape
7567
    // formatting so to save the term into the database as the user intends.
7568
    $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
7569
    if ($tag != "") {
7570
      $tags[] = $tag;
7571
    }
7572
  }
7573

    
7574
  return $tags;
7575
}
7576

    
7577
/**
7578
 * Implodes an array of tags into a string.
7579
 *
7580
 * @see drupal_explode_tags()
7581
 */
7582
function drupal_implode_tags($tags) {
7583
  $encoded_tags = array();
7584
  foreach ($tags as $tag) {
7585
    // Commas and quotes in tag names are special cases, so encode them.
7586
    if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
7587
      $tag = '"' . str_replace('"', '""', $tag) . '"';
7588
    }
7589

    
7590
    $encoded_tags[] = $tag;
7591
  }
7592
  return implode(', ', $encoded_tags);
7593
}
7594

    
7595
/**
7596
 * Flushes all cached data on the site.
7597
 *
7598
 * Empties cache tables, rebuilds the menu cache and theme registries, and
7599
 * invokes a hook so that other modules' cache data can be cleared as well.
7600
 */
7601
function drupal_flush_all_caches() {
7602
  // Change query-strings on css/js files to enforce reload for all users.
7603
  _drupal_flush_css_js();
7604

    
7605
  registry_rebuild();
7606
  drupal_clear_css_cache();
7607
  drupal_clear_js_cache();
7608

    
7609
  // Rebuild the theme data. Note that the module data is rebuilt above, as
7610
  // part of registry_rebuild().
7611
  system_rebuild_theme_data();
7612
  drupal_theme_rebuild();
7613

    
7614
  entity_info_cache_clear();
7615
  node_types_rebuild();
7616
  // node_menu() defines menu items based on node types so it needs to come
7617
  // after node types are rebuilt.
7618
  menu_rebuild();
7619

    
7620
  // Synchronize to catch any actions that were added or removed.
7621
  actions_synchronize();
7622

    
7623
  // Don't clear cache_form - in-progress form submissions may break.
7624
  // Ordered so clearing the page cache will always be the last action.
7625
  $core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
7626
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
7627
  foreach ($cache_tables as $table) {
7628
    cache_clear_all('*', $table, TRUE);
7629
  }
7630

    
7631
  // Rebuild the bootstrap module list. We do this here so that developers
7632
  // can get new hook_boot() implementations registered without having to
7633
  // write a hook_update_N() function.
7634
  _system_update_bootstrap_status();
7635
}
7636

    
7637
/**
7638
 * Changes the dummy query string added to all CSS and JavaScript files.
7639
 *
7640
 * Changing the dummy query string appended to CSS and JavaScript files forces
7641
 * all browsers to reload fresh files.
7642
 */
7643
function _drupal_flush_css_js() {
7644
  // The timestamp is converted to base 36 in order to make it more compact.
7645
  variable_set('css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
7646
}
7647

    
7648
/**
7649
 * Outputs debug information.
7650
 *
7651
 * The debug information is passed on to trigger_error() after being converted
7652
 * to a string using _drupal_debug_message().
7653
 *
7654
 * @param $data
7655
 *   Data to be output.
7656
 * @param $label
7657
 *   Label to prefix the data.
7658
 * @param $print_r
7659
 *   Flag to switch between print_r() and var_export() for data conversion to
7660
 *   string. Set $print_r to TRUE when dealing with a recursive data structure
7661
 *   as var_export() will generate an error.
7662
 */
7663
function debug($data, $label = NULL, $print_r = FALSE) {
7664
  // Print $data contents to string.
7665
  $string = check_plain($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
7666

    
7667
  // Display values with pre-formatting to increase readability.
7668
  $string = '<pre>' . $string . '</pre>';
7669

    
7670
  trigger_error(trim($label ? "$label: $string" : $string));
7671
}
7672

    
7673
/**
7674
 * Parses a dependency for comparison by drupal_check_incompatibility().
7675
 *
7676
 * @param $dependency
7677
 *   A dependency string, which specifies a module dependency, and optionally
7678
 *   the project it comes from and versions that are supported. Supported
7679
 *   formats include:
7680
 *   - 'module'
7681
 *   - 'project:module'
7682
 *   - 'project:module (>=version, version)'
7683
 *
7684
 * @return
7685
 *   An associative array with three keys:
7686
 *   - 'name' includes the name of the thing to depend on (e.g. 'foo').
7687
 *   - 'original_version' contains the original version string (which can be
7688
 *     used in the UI for reporting incompatibilities).
7689
 *   - 'versions' is a list of associative arrays, each containing the keys
7690
 *     'op' and 'version'. 'op' can be one of: '=', '==', '!=', '<>', '<',
7691
 *     '<=', '>', or '>='. 'version' is one piece like '4.5-beta3'.
7692
 *   Callers should pass this structure to drupal_check_incompatibility().
7693
 *
7694
 * @see drupal_check_incompatibility()
7695
 */
7696
function drupal_parse_dependency($dependency) {
7697
  $value = array();
7698
  // Split out the optional project name.
7699
  if (strpos($dependency, ':')) {
7700
    list($project_name, $dependency) = explode(':', $dependency);
7701
    $value['project'] = $project_name;
7702
  }
7703
  // We use named subpatterns and support every op that version_compare
7704
  // supports. Also, op is optional and defaults to equals.
7705
  $p_op = '(?P<operation>!=|==|=|<|<=|>|>=|<>)?';
7706
  // Core version is always optional: 7.x-2.x and 2.x is treated the same.
7707
  $p_core = '(?:' . preg_quote(DRUPAL_CORE_COMPATIBILITY) . '-)?';
7708
  $p_major = '(?P<major>\d+)';
7709
  // By setting the minor version to x, branches can be matched.
7710
  $p_minor = '(?P<minor>(?:\d+|x)(?:-[A-Za-z]+\d+)?)';
7711
  $parts = explode('(', $dependency, 2);
7712
  $value['name'] = trim($parts[0]);
7713
  if (isset($parts[1])) {
7714
    $value['original_version'] = ' (' . $parts[1];
7715
    foreach (explode(',', $parts[1]) as $version) {
7716
      if (preg_match("/^\s*$p_op\s*$p_core$p_major\.$p_minor/", $version, $matches)) {
7717
        $op = !empty($matches['operation']) ? $matches['operation'] : '=';
7718
        if ($matches['minor'] == 'x') {
7719
          // Drupal considers "2.x" to mean any version that begins with
7720
          // "2" (e.g. 2.0, 2.9 are all "2.x"). PHP's version_compare(),
7721
          // on the other hand, treats "x" as a string; so to
7722
          // version_compare(), "2.x" is considered less than 2.0. This
7723
          // means that >=2.x and <2.x are handled by version_compare()
7724
          // as we need, but > and <= are not.
7725
          if ($op == '>' || $op == '<=') {
7726
            $matches['major']++;
7727
          }
7728
          // Equivalence can be checked by adding two restrictions.
7729
          if ($op == '=' || $op == '==') {
7730
            $value['versions'][] = array('op' => '<', 'version' => ($matches['major'] + 1) . '.x');
7731
            $op = '>=';
7732
          }
7733
        }
7734
        $value['versions'][] = array('op' => $op, 'version' => $matches['major'] . '.' . $matches['minor']);
7735
      }
7736
    }
7737
  }
7738
  return $value;
7739
}
7740

    
7741
/**
7742
 * Checks whether a version is compatible with a given dependency.
7743
 *
7744
 * @param $v
7745
 *   The parsed dependency structure from drupal_parse_dependency().
7746
 * @param $current_version
7747
 *   The version to check against (like 4.2).
7748
 *
7749
 * @return
7750
 *   NULL if compatible, otherwise the original dependency version string that
7751
 *   caused the incompatibility.
7752
 *
7753
 * @see drupal_parse_dependency()
7754
 */
7755
function drupal_check_incompatibility($v, $current_version) {
7756
  if (!empty($v['versions'])) {
7757
    foreach ($v['versions'] as $required_version) {
7758
      if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
7759
        return $v['original_version'];
7760
      }
7761
    }
7762
  }
7763
}
7764

    
7765
/**
7766
 * Get the entity info array of an entity type.
7767
 *
7768
 * @param $entity_type
7769
 *   The entity type, e.g. node, for which the info shall be returned, or NULL
7770
 *   to return an array with info about all types.
7771
 *
7772
 * @see hook_entity_info()
7773
 * @see hook_entity_info_alter()
7774
 */
7775
function entity_get_info($entity_type = NULL) {
7776
  global $language;
7777

    
7778
  // Use the advanced drupal_static() pattern, since this is called very often.
7779
  static $drupal_static_fast;
7780
  if (!isset($drupal_static_fast)) {
7781
    $drupal_static_fast['entity_info'] = &drupal_static(__FUNCTION__);
7782
  }
7783
  $entity_info = &$drupal_static_fast['entity_info'];
7784

    
7785
  // hook_entity_info() includes translated strings, so each language is cached
7786
  // separately.
7787
  $langcode = $language->language;
7788

    
7789
  if (empty($entity_info)) {
7790
    if ($cache = cache_get("entity_info:$langcode")) {
7791
      $entity_info = $cache->data;
7792
    }
7793
    else {
7794
      $entity_info = module_invoke_all('entity_info');
7795
      // Merge in default values.
7796
      foreach ($entity_info as $name => $data) {
7797
        $entity_info[$name] += array(
7798
          'fieldable' => FALSE,
7799
          'controller class' => 'DrupalDefaultEntityController',
7800
          'static cache' => TRUE,
7801
          'field cache' => TRUE,
7802
          'load hook' => $name . '_load',
7803
          'bundles' => array(),
7804
          'view modes' => array(),
7805
          'entity keys' => array(),
7806
          'translation' => array(),
7807
        );
7808
        $entity_info[$name]['entity keys'] += array(
7809
          'revision' => '',
7810
          'bundle' => '',
7811
        );
7812
        foreach ($entity_info[$name]['view modes'] as $view_mode => $view_mode_info) {
7813
          $entity_info[$name]['view modes'][$view_mode] += array(
7814
            'custom settings' => FALSE,
7815
          );
7816
        }
7817
        // If no bundle key is provided, assume a single bundle, named after
7818
        // the entity type.
7819
        if (empty($entity_info[$name]['entity keys']['bundle']) && empty($entity_info[$name]['bundles'])) {
7820
          $entity_info[$name]['bundles'] = array($name => array('label' => $entity_info[$name]['label']));
7821
        }
7822
        // Prepare entity schema fields SQL info for
7823
        // DrupalEntityControllerInterface::buildQuery().
7824
        if (isset($entity_info[$name]['base table'])) {
7825
          $entity_info[$name]['base table field types'] = drupal_schema_field_types($entity_info[$name]['base table']);
7826
          $entity_info[$name]['schema_fields_sql']['base table'] = drupal_schema_fields_sql($entity_info[$name]['base table']);
7827
          if (isset($entity_info[$name]['revision table'])) {
7828
            $entity_info[$name]['schema_fields_sql']['revision table'] = drupal_schema_fields_sql($entity_info[$name]['revision table']);
7829
          }
7830
        }
7831
      }
7832
      // Let other modules alter the entity info.
7833
      drupal_alter('entity_info', $entity_info);
7834
      cache_set("entity_info:$langcode", $entity_info);
7835
    }
7836
  }
7837

    
7838
  if (empty($entity_type)) {
7839
    return $entity_info;
7840
  }
7841
  elseif (isset($entity_info[$entity_type])) {
7842
    return $entity_info[$entity_type];
7843
  }
7844
}
7845

    
7846
/**
7847
 * Resets the cached information about entity types.
7848
 */
7849
function entity_info_cache_clear() {
7850
  drupal_static_reset('entity_get_info');
7851
  // Clear all languages.
7852
  cache_clear_all('entity_info:', 'cache', TRUE);
7853
}
7854

    
7855
/**
7856
 * Helper function to extract id, vid, and bundle name from an entity.
7857
 *
7858
 * @param $entity_type
7859
 *   The entity type; e.g. 'node' or 'user'.
7860
 * @param $entity
7861
 *   The entity from which to extract values.
7862
 *
7863
 * @return
7864
 *   A numerically indexed array (not a hash table) containing these
7865
 *   elements:
7866
 *   - 0: Primary ID of the entity.
7867
 *   - 1: Revision ID of the entity, or NULL if $entity_type is not versioned.
7868
 *   - 2: Bundle name of the entity, or NULL if $entity_type has no bundles.
7869
 */
7870
function entity_extract_ids($entity_type, $entity) {
7871
  $info = entity_get_info($entity_type);
7872

    
7873
  // Objects being created might not have id/vid yet.
7874
  $id = isset($entity->{$info['entity keys']['id']}) ? $entity->{$info['entity keys']['id']} : NULL;
7875
  $vid = ($info['entity keys']['revision'] && isset($entity->{$info['entity keys']['revision']})) ? $entity->{$info['entity keys']['revision']} : NULL;
7876

    
7877
  if (!empty($info['entity keys']['bundle'])) {
7878
    // Explicitly fail for malformed entities missing the bundle property.
7879
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
7880
      throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
7881
    }
7882
    $bundle = $entity->{$info['entity keys']['bundle']};
7883
  }
7884
  else {
7885
    // The entity type provides no bundle key: assume a single bundle, named
7886
    // after the entity type.
7887
    $bundle = $entity_type;
7888
  }
7889

    
7890
  return array($id, $vid, $bundle);
7891
}
7892

    
7893
/**
7894
 * Helper function to assemble an object structure with initial ids.
7895
 *
7896
 * This function can be seen as reciprocal to entity_extract_ids().
7897
 *
7898
 * @param $entity_type
7899
 *   The entity type; e.g. 'node' or 'user'.
7900
 * @param $ids
7901
 *   A numerically indexed array, as returned by entity_extract_ids().
7902
 *
7903
 * @return
7904
 *   An entity structure, initialized with the ids provided.
7905
 *
7906
 * @see entity_extract_ids()
7907
 */
7908
function entity_create_stub_entity($entity_type, $ids) {
7909
  $entity = new stdClass();
7910
  $info = entity_get_info($entity_type);
7911
  $entity->{$info['entity keys']['id']} = $ids[0];
7912
  if (!empty($info['entity keys']['revision']) && isset($ids[1])) {
7913
    $entity->{$info['entity keys']['revision']} = $ids[1];
7914
  }
7915
  if (!empty($info['entity keys']['bundle']) && isset($ids[2])) {
7916
    $entity->{$info['entity keys']['bundle']} = $ids[2];
7917
  }
7918
  return $entity;
7919
}
7920

    
7921
/**
7922
 * Load entities from the database.
7923
 *
7924
 * The entities are stored in a static memory cache, and will not require
7925
 * database access if loaded again during the same page request.
7926
 *
7927
 * The actual loading is done through a class that has to implement the
7928
 * DrupalEntityControllerInterface interface. By default,
7929
 * DrupalDefaultEntityController is used. Entity types can specify that a
7930
 * different class should be used by setting the 'controller class' key in
7931
 * hook_entity_info(). These classes can either implement the
7932
 * DrupalEntityControllerInterface interface, or, most commonly, extend the
7933
 * DrupalDefaultEntityController class. See node_entity_info() and the
7934
 * NodeController in node.module as an example.
7935
 *
7936
 * @param $entity_type
7937
 *   The entity type to load, e.g. node or user.
7938
 * @param $ids
7939
 *   An array of entity IDs, or FALSE to load all entities.
7940
 * @param $conditions
7941
 *   (deprecated) An associative array of conditions on the base table, where
7942
 *   the keys are the database fields and the values are the values those
7943
 *   fields must have. Instead, it is preferable to use EntityFieldQuery to
7944
 *   retrieve a list of entity IDs loadable by this function.
7945
 * @param $reset
7946
 *   Whether to reset the internal cache for the requested entity type.
7947
 *
7948
 * @return
7949
 *   An array of entity objects indexed by their ids. When no results are
7950
 *   found, an empty array is returned.
7951
 *
7952
 * @todo Remove $conditions in Drupal 8.
7953
 *
7954
 * @see hook_entity_info()
7955
 * @see DrupalEntityControllerInterface
7956
 * @see DrupalDefaultEntityController
7957
 * @see EntityFieldQuery
7958
 */
7959
function entity_load($entity_type, $ids = FALSE, $conditions = array(), $reset = FALSE) {
7960
  if ($reset) {
7961
    entity_get_controller($entity_type)->resetCache();
7962
  }
7963
  return entity_get_controller($entity_type)->load($ids, $conditions);
7964
}
7965

    
7966
/**
7967
 * Loads the unchanged, i.e. not modified, entity from the database.
7968
 *
7969
 * Unlike entity_load() this function ensures the entity is directly loaded from
7970
 * the database, thus bypassing any static cache. In particular, this function
7971
 * is useful to determine changes by comparing the entity being saved to the
7972
 * stored entity.
7973
 *
7974
 * @param $entity_type
7975
 *   The entity type to load, e.g. node or user.
7976
 * @param $id
7977
 *   The ID of the entity to load.
7978
 *
7979
 * @return
7980
 *   The unchanged entity, or FALSE if the entity cannot be loaded.
7981
 */
7982
function entity_load_unchanged($entity_type, $id) {
7983
  entity_get_controller($entity_type)->resetCache(array($id));
7984
  $result = entity_get_controller($entity_type)->load(array($id));
7985
  return reset($result);
7986
}
7987

    
7988
/**
7989
 * Gets the entity controller for an entity type.
7990
 *
7991
 * @return DrupalEntityControllerInterface
7992
 *   The entity controller object for the specified entity type.
7993
 */
7994
function entity_get_controller($entity_type) {
7995
  $controllers = &drupal_static(__FUNCTION__, array());
7996
  if (!isset($controllers[$entity_type])) {
7997
    $type_info = entity_get_info($entity_type);
7998
    $class = $type_info['controller class'];
7999
    $controllers[$entity_type] = new $class($entity_type);
8000
  }
8001
  return $controllers[$entity_type];
8002
}
8003

    
8004
/**
8005
 * Invoke hook_entity_prepare_view().
8006
 *
8007
 * If adding a new entity similar to nodes, comments or users, you should
8008
 * invoke this function during the ENTITY_build_content() or
8009
 * ENTITY_view_multiple() phases of rendering to allow other modules to alter
8010
 * the objects during this phase. This is needed for situations where
8011
 * information needs to be loaded outside of ENTITY_load() - particularly
8012
 * when loading entities into one another - i.e. a user object into a node, due
8013
 * to the potential for unwanted side-effects such as caching and infinite
8014
 * recursion. By convention, entity_prepare_view() is called after
8015
 * field_attach_prepare_view() to allow entity level hooks to act on content
8016
 * loaded by field API.
8017
 *
8018
 * @param $entity_type
8019
 *   The type of entity, i.e. 'node', 'user'.
8020
 * @param $entities
8021
 *   The entity objects which are being prepared for view, keyed by object ID.
8022
 * @param $langcode
8023
 *   (optional) A language code to be used for rendering. Defaults to the global
8024
 *   content language of the current request.
8025
 *
8026
 * @see hook_entity_prepare_view()
8027
 */
8028
function entity_prepare_view($entity_type, $entities, $langcode = NULL) {
8029
  if (!isset($langcode)) {
8030
    $langcode = $GLOBALS['language_content']->language;
8031
  }
8032

    
8033
  // To ensure hooks are only run once per entity, check for an
8034
  // entity_view_prepared flag and only process items without it.
8035
  // @todo: resolve this more generally for both entity and field level hooks.
8036
  $prepare = array();
8037
  foreach ($entities as $id => $entity) {
8038
    if (empty($entity->entity_view_prepared)) {
8039
      // Add this entity to the items to be prepared.
8040
      $prepare[$id] = $entity;
8041

    
8042
      // Mark this item as prepared.
8043
      $entity->entity_view_prepared = TRUE;
8044
    }
8045
  }
8046

    
8047
  if (!empty($prepare)) {
8048
    module_invoke_all('entity_prepare_view', $prepare, $entity_type, $langcode);
8049
  }
8050
}
8051

    
8052
/**
8053
 * Invoke hook_entity_view_mode_alter().
8054
 *
8055
 * If adding a new entity similar to nodes, comments or users, you should invoke
8056
 * this function during the ENTITY_build_content() or ENTITY_view_multiple()
8057
 * phases of rendering to allow other modules to alter the view mode during this
8058
 * phase. This function needs to be called before field_attach_prepare_view() to
8059
 * ensure that the correct content is loaded by field API.
8060
 *
8061
 * @param $entity_type
8062
 *   The type of entity, i.e. 'node', 'user'.
8063
 * @param $entities
8064
 *   The entity objects which are being prepared for view, keyed by object ID.
8065
 * @param $view_mode
8066
 *   The original view mode e.g. 'full', 'teaser'...
8067
 * @param $langcode
8068
 *   (optional) A language code to be used for rendering. Defaults to the global
8069
 *   content language of the current request.
8070
 * @return
8071
 *   An associative array with arrays of entities keyed by view mode.
8072
 *
8073
 * @see hook_entity_view_mode_alter()
8074
 */
8075
function entity_view_mode_prepare($entity_type, $entities, $view_mode, $langcode = NULL) {
8076
  if (!isset($langcode)) {
8077
    $langcode = $GLOBALS['language_content']->language;
8078
  }
8079

    
8080
  // To ensure hooks are never run after field_attach_prepare_view() only
8081
  // process items without the entity_view_prepared flag.
8082
  $entities_by_view_mode = array();
8083
  foreach ($entities as $id => $entity) {
8084
    $entity_view_mode = $view_mode;
8085
    if (empty($entity->entity_view_prepared)) {
8086

    
8087
      // Allow modules to change the view mode.
8088
      $context = array(
8089
        'entity_type' => $entity_type,
8090
        'entity' => $entity,
8091
        'langcode' => $langcode,
8092
      );
8093
      drupal_alter('entity_view_mode', $entity_view_mode, $context);
8094
    }
8095

    
8096
    $entities_by_view_mode[$entity_view_mode][$id] = $entity;
8097
  }
8098

    
8099
  return $entities_by_view_mode;
8100
}
8101

    
8102
/**
8103
 * Returns the URI elements of an entity.
8104
 *
8105
 * @param $entity_type
8106
 *   The entity type; e.g. 'node' or 'user'.
8107
 * @param $entity
8108
 *   The entity for which to generate a path.
8109
 * @return
8110
 *   An array containing the 'path' and 'options' keys used to build the URI of
8111
 *   the entity, and matching the signature of url(). NULL if the entity has no
8112
 *   URI of its own.
8113
 */
8114
function entity_uri($entity_type, $entity) {
8115
  $info = entity_get_info($entity_type);
8116
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
8117

    
8118
  // A bundle-specific callback takes precedence over the generic one for the
8119
  // entity type.
8120
  if (isset($info['bundles'][$bundle]['uri callback'])) {
8121
    $uri_callback = $info['bundles'][$bundle]['uri callback'];
8122
  }
8123
  elseif (isset($info['uri callback'])) {
8124
    $uri_callback = $info['uri callback'];
8125
  }
8126
  else {
8127
    return NULL;
8128
  }
8129

    
8130
  // Invoke the callback to get the URI. If there is no callback, return NULL.
8131
  if (isset($uri_callback) && function_exists($uri_callback)) {
8132
    $uri = $uri_callback($entity);
8133
    // Pass the entity data to url() so that alter functions do not need to
8134
    // lookup this entity again.
8135
    $uri['options']['entity_type'] = $entity_type;
8136
    $uri['options']['entity'] = $entity;
8137
    return $uri;
8138
  }
8139
}
8140

    
8141
/**
8142
 * Returns the label of an entity.
8143
 *
8144
 * See the 'label callback' component of the hook_entity_info() return value
8145
 * for more information.
8146
 *
8147
 * @param $entity_type
8148
 *   The entity type; e.g., 'node' or 'user'.
8149
 * @param $entity
8150
 *   The entity for which to generate the label.
8151
 *
8152
 * @return
8153
 *   The entity label, or FALSE if not found.
8154
 */
8155
function entity_label($entity_type, $entity) {
8156
  $label = FALSE;
8157
  $info = entity_get_info($entity_type);
8158
  if (isset($info['label callback']) && function_exists($info['label callback'])) {
8159
    $label = $info['label callback']($entity, $entity_type);
8160
  }
8161
  elseif (!empty($info['entity keys']['label']) && isset($entity->{$info['entity keys']['label']})) {
8162
    $label = $entity->{$info['entity keys']['label']};
8163
  }
8164

    
8165
  return $label;
8166
}
8167

    
8168
/**
8169
 * Returns the language of an entity.
8170
 *
8171
 * @param $entity_type
8172
 *   The entity type; e.g., 'node' or 'user'.
8173
 * @param $entity
8174
 *   The entity for which to get the language.
8175
 *
8176
 * @return
8177
 *   A valid language code or NULL if the entity has no language support.
8178
 */
8179
function entity_language($entity_type, $entity) {
8180
  $info = entity_get_info($entity_type);
8181

    
8182
  // Invoke the callback to get the language. If there is no callback, try to
8183
  // get it from a property of the entity, otherwise NULL.
8184
  if (isset($info['language callback']) && function_exists($info['language callback'])) {
8185
    $langcode = $info['language callback']($entity_type, $entity);
8186
  }
8187
  elseif (!empty($info['entity keys']['language']) && isset($entity->{$info['entity keys']['language']})) {
8188
    $langcode = $entity->{$info['entity keys']['language']};
8189
  }
8190
  else {
8191
    // The value returned in D8 would be LANGUAGE_NONE, we cannot use it here to
8192
    // preserve backward compatibility. In fact this function has been
8193
    // introduced very late in the D7 life cycle, mainly as the proper default
8194
    // for field_attach_form(). By returning LANGUAGE_NONE when no language
8195
    // information is available, we would introduce a potentially BC-breaking
8196
    // API change, since field_attach_form() defaults to the default language
8197
    // instead of LANGUAGE_NONE. Moreover this allows us to distinguish between
8198
    // entities that have no language specified from ones that do not have
8199
    // language support at all.
8200
    $langcode = NULL;
8201
  }
8202

    
8203
  return $langcode;
8204
}
8205

    
8206
/**
8207
 * Attaches field API validation to entity forms.
8208
 */
8209
function entity_form_field_validate($entity_type, $form, &$form_state) {
8210
  // All field attach API functions act on an entity object, but during form
8211
  // validation, we don't have one. $form_state contains the entity as it was
8212
  // prior to processing the current form submission, and we must not update it
8213
  // until we have fully validated the submitted input. Therefore, for
8214
  // validation, act on a pseudo entity created out of the form values.
8215
  $pseudo_entity = (object) $form_state['values'];
8216
  field_attach_form_validate($entity_type, $pseudo_entity, $form, $form_state);
8217
}
8218

    
8219
/**
8220
 * Copies submitted values to entity properties for simple entity forms.
8221
 *
8222
 * During the submission handling of an entity form's "Save", "Preview", and
8223
 * possibly other buttons, the form state's entity needs to be updated with the
8224
 * submitted form values. Each entity form implements its own builder function
8225
 * for doing this, appropriate for the particular entity and form, whereas
8226
 * modules may specify additional builder functions in $form['#entity_builders']
8227
 * for copying the form values of added form elements to entity properties.
8228
 * Many of the main entity builder functions can call this helper function to
8229
 * re-use its logic of copying $form_state['values'][PROPERTY] values to
8230
 * $entity->PROPERTY for all entries in $form_state['values'] that are not field
8231
 * data, and calling field_attach_submit() to copy field data. Apart from that
8232
 * this helper invokes any additional builder functions that have been specified
8233
 * in $form['#entity_builders'].
8234
 *
8235
 * For some entity forms (e.g., forms with complex non-field data and forms that
8236
 * simultaneously edit multiple entities), this behavior may be inappropriate,
8237
 * so the builder function for such forms needs to implement the required
8238
 * functionality instead of calling this function.
8239
 */
8240
function entity_form_submit_build_entity($entity_type, $entity, $form, &$form_state) {
8241
  $info = entity_get_info($entity_type);
8242
  list(, , $bundle) = entity_extract_ids($entity_type, $entity);
8243

    
8244
  // Copy top-level form values that are not for fields to entity properties,
8245
  // without changing existing entity properties that are not being edited by
8246
  // this form. Copying field values must be done using field_attach_submit().
8247
  $values_excluding_fields = $info['fieldable'] ? array_diff_key($form_state['values'], field_info_instances($entity_type, $bundle)) : $form_state['values'];
8248
  foreach ($values_excluding_fields as $key => $value) {
8249
    $entity->$key = $value;
8250
  }
8251

    
8252
  // Invoke all specified builders for copying form values to entity properties.
8253
  if (isset($form['#entity_builders'])) {
8254
    foreach ($form['#entity_builders'] as $function) {
8255
      $function($entity_type, $entity, $form, $form_state);
8256
    }
8257
  }
8258

    
8259
  // Copy field values to the entity.
8260
  if ($info['fieldable']) {
8261
    field_attach_submit($entity_type, $entity, $form, $form_state);
8262
  }
8263
}
8264

    
8265
/**
8266
 * Performs one or more XML-RPC request(s).
8267
 *
8268
 * Usage example:
8269
 * @code
8270
 * $result = xmlrpc('http://example.com/xmlrpc.php', array(
8271
 *   'service.methodName' => array($parameter, $second, $third),
8272
 * ));
8273
 * @endcode
8274
 *
8275
 * @param $url
8276
 *   An absolute URL of the XML-RPC endpoint.
8277
 * @param $args
8278
 *   An associative array whose keys are the methods to call and whose values
8279
 *   are the arguments to pass to the respective method. If multiple methods
8280
 *   are specified, a system.multicall is performed.
8281
 * @param $options
8282
 *   (optional) An array of options to pass along to drupal_http_request().
8283
 *
8284
 * @return
8285
 *   For one request:
8286
 *     Either the return value of the method on success, or FALSE.
8287
 *     If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
8288
 *   For multiple requests:
8289
 *     An array of results. Each result will either be the result
8290
 *     returned by the method called, or an xmlrpc_error object if the call
8291
 *     failed. See xmlrpc_error().
8292
 */
8293
function xmlrpc($url, $args, $options = array()) {
8294
  require_once DRUPAL_ROOT . '/includes/xmlrpc.inc';
8295
  return _xmlrpc($url, $args, $options);
8296
}
8297

    
8298
/**
8299
 * Retrieves a list of all available archivers.
8300
 *
8301
 * @see hook_archiver_info()
8302
 * @see hook_archiver_info_alter()
8303
 */
8304
function archiver_get_info() {
8305
  $archiver_info = &drupal_static(__FUNCTION__, array());
8306

    
8307
  if (empty($archiver_info)) {
8308
    $cache = cache_get('archiver_info');
8309
    if ($cache === FALSE) {
8310
      // Rebuild the cache and save it.
8311
      $archiver_info = module_invoke_all('archiver_info');
8312
      drupal_alter('archiver_info', $archiver_info);
8313
      uasort($archiver_info, 'drupal_sort_weight');
8314
      cache_set('archiver_info', $archiver_info);
8315
    }
8316
    else {
8317
      $archiver_info = $cache->data;
8318
    }
8319
  }
8320

    
8321
  return $archiver_info;
8322
}
8323

    
8324
/**
8325
 * Returns a string of supported archive extensions.
8326
 *
8327
 * @return
8328
 *   A space-separated string of extensions suitable for use by the file
8329
 *   validation system.
8330
 */
8331
function archiver_get_extensions() {
8332
  $valid_extensions = array();
8333
  foreach (archiver_get_info() as $archive) {
8334
    foreach ($archive['extensions'] as $extension) {
8335
      foreach (explode('.', $extension) as $part) {
8336
        if (!in_array($part, $valid_extensions)) {
8337
          $valid_extensions[] = $part;
8338
        }
8339
      }
8340
    }
8341
  }
8342
  return implode(' ', $valid_extensions);
8343
}
8344

    
8345
/**
8346
 * Creates the appropriate archiver for the specified file.
8347
 *
8348
 * @param $file
8349
 *   The full path of the archive file. Note that stream wrapper paths are
8350
 *   supported, but not remote ones.
8351
 *
8352
 * @return
8353
 *   A newly created instance of the archiver class appropriate
8354
 *   for the specified file, already bound to that file.
8355
 *   If no appropriate archiver class was found, will return FALSE.
8356
 */
8357
function archiver_get_archiver($file) {
8358
  // Archivers can only work on local paths
8359
  $filepath = drupal_realpath($file);
8360
  if (!is_file($filepath)) {
8361
    throw new Exception(t('Archivers can only operate on local files: %file not supported', array('%file' => $file)));
8362
  }
8363
  $archiver_info = archiver_get_info();
8364

    
8365
  foreach ($archiver_info as $implementation) {
8366
    foreach ($implementation['extensions'] as $extension) {
8367
      // Because extensions may be multi-part, such as .tar.gz,
8368
      // we cannot use simpler approaches like substr() or pathinfo().
8369
      // This method isn't quite as clean but gets the job done.
8370
      // Also note that the file may not yet exist, so we cannot rely
8371
      // on fileinfo() or other disk-level utilities.
8372
      if (strrpos($filepath, '.' . $extension) === strlen($filepath) - strlen('.' . $extension)) {
8373
        return new $implementation['class']($filepath);
8374
      }
8375
    }
8376
  }
8377
}
8378

    
8379
/**
8380
 * Assembles the Drupal Updater registry.
8381
 *
8382
 * An Updater is a class that knows how to update various parts of the Drupal
8383
 * file system, for example to update modules that have newer releases, or to
8384
 * install a new theme.
8385
 *
8386
 * @return
8387
 *   The Drupal Updater class registry.
8388
 *
8389
 * @see hook_updater_info()
8390
 * @see hook_updater_info_alter()
8391
 */
8392
function drupal_get_updaters() {
8393
  $updaters = &drupal_static(__FUNCTION__);
8394
  if (!isset($updaters)) {
8395
    $updaters = module_invoke_all('updater_info');
8396
    drupal_alter('updater_info', $updaters);
8397
    uasort($updaters, 'drupal_sort_weight');
8398
  }
8399
  return $updaters;
8400
}
8401

    
8402
/**
8403
 * Assembles the Drupal FileTransfer registry.
8404
 *
8405
 * @return
8406
 *   The Drupal FileTransfer class registry.
8407
 *
8408
 * @see FileTransfer
8409
 * @see hook_filetransfer_info()
8410
 * @see hook_filetransfer_info_alter()
8411
 */
8412
function drupal_get_filetransfer_info() {
8413
  $info = &drupal_static(__FUNCTION__);
8414
  if (!isset($info)) {
8415
    // Since we have to manually set the 'file path' default for each
8416
    // module separately, we can't use module_invoke_all().
8417
    $info = array();
8418
    foreach (module_implements('filetransfer_info') as $module) {
8419
      $function = $module . '_filetransfer_info';
8420
      if (function_exists($function)) {
8421
        $result = $function();
8422
        if (isset($result) && is_array($result)) {
8423
          foreach ($result as &$values) {
8424
            if (empty($values['file path'])) {
8425
              $values['file path'] = drupal_get_path('module', $module);
8426
            }
8427
          }
8428
          $info = array_merge_recursive($info, $result);
8429
        }
8430
      }
8431
    }
8432
    drupal_alter('filetransfer_info', $info);
8433
    uasort($info, 'drupal_sort_weight');
8434
  }
8435
  return $info;
8436
}