Projet

Général

Profil

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

root / drupal7 / includes / common.inc @ 27e02aed

1
<?php
2

    
3
/**
4
 * @file
5
 * Common functions that many Drupal modules will need to reference.
6
 *
7
 * The functions that are critical and need to be available even when serving
8
 * a cached page are instead located in bootstrap.inc.
9
 */
10

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
232
  return $profile;
233
}
234

    
235

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

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

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

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

    
262
  return $breadcrumb;
263
}
264

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
445
  return $params;
446
}
447

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

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

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

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

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

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

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

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

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

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

    
621
  return $options;
622
}
623

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

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

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

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

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

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

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

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

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

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

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

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

    
802
  $result = new stdClass();
803

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

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

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

    
819
  timer_start(__FUNCTION__);
820

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

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

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

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

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

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

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

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

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

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

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

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

    
925
    return $result;
926
  }
927

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

    
934
  // Convert array $options['data'] to query string.
935
  if (is_array($options['data'])) {
936
    $options['data'] = drupal_http_build_query($options['data']);
937
  }
938

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

    
948
  // If the server URL has a user then attempt to use basic authentication.
949
  if (isset($uri['user'])) {
950
    $options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ':'));
951
  }
952

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

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

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

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

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

    
1010
  // Parse the response status line.
1011
  $response_status_array = _drupal_parse_response_status(trim(array_shift($response)));
1012
  $result->protocol = $response_status_array['http_version'];
1013
  $result->status_message = $response_status_array['reason_phrase'];
1014
  $code = $response_status_array['response_code'];
1015

    
1016
  $result->headers = array();
1017

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

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

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

    
1104
        // We need to unset the 'Host' header
1105
        // as we are redirecting to a new location.
1106
        unset($options['headers']['Host']);
1107

    
1108
        $result = drupal_http_request($location, $options);
1109
        $result->redirect_code = $code;
1110
      }
1111
      if (!isset($result->redirect_url)) {
1112
        $result->redirect_url = $location;
1113
      }
1114
      break;
1115
    default:
1116
      $result->error = $result->status_message;
1117
  }
1118

    
1119
  return $result;
1120
}
1121

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

    
1153
/**
1154
 * Helper function for determining hosts excluded from needing a proxy.
1155
 *
1156
 * @return
1157
 *   TRUE if a proxy should be used for this host.
1158
 */
1159
function _drupal_http_use_proxy($host) {
1160
  $proxy_exceptions = variable_get('proxy_exceptions', array('localhost', '127.0.0.1'));
1161
  return !in_array(strtolower($host), $proxy_exceptions, TRUE);
1162
}
1163

    
1164
/**
1165
 * @} End of "HTTP handling".
1166
 */
1167

    
1168
/**
1169
 * Strips slashes from a string or array of strings.
1170
 *
1171
 * Callback for array_walk() within fix_gpx_magic().
1172
 *
1173
 * @param $item
1174
 *   An individual string or array of strings from superglobals.
1175
 */
1176
function _fix_gpc_magic(&$item) {
1177
  if (is_array($item)) {
1178
    array_walk($item, '_fix_gpc_magic');
1179
  }
1180
  else {
1181
    $item = stripslashes($item);
1182
  }
1183
}
1184

    
1185
/**
1186
 * Strips slashes from $_FILES items.
1187
 *
1188
 * Callback for array_walk() within fix_gpc_magic().
1189
 *
1190
 * The tmp_name key is skipped keys since PHP generates single backslashes for
1191
 * file paths on Windows systems.
1192
 *
1193
 * @param $item
1194
 *   An item from $_FILES.
1195
 * @param $key
1196
 *   The key for the item within $_FILES.
1197
 *
1198
 * @see http://php.net/manual/features.file-upload.php#42280
1199
 */
1200
function _fix_gpc_magic_files(&$item, $key) {
1201
  if ($key != 'tmp_name') {
1202
    if (is_array($item)) {
1203
      array_walk($item, '_fix_gpc_magic_files');
1204
    }
1205
    else {
1206
      $item = stripslashes($item);
1207
    }
1208
  }
1209
}
1210

    
1211
/**
1212
 * Fixes double-escaping caused by "magic quotes" in some PHP installations.
1213
 *
1214
 * @see _fix_gpc_magic()
1215
 * @see _fix_gpc_magic_files()
1216
 */
1217
function fix_gpc_magic() {
1218
  static $fixed = FALSE;
1219
  if (!$fixed && ini_get('magic_quotes_gpc')) {
1220
    array_walk($_GET, '_fix_gpc_magic');
1221
    array_walk($_POST, '_fix_gpc_magic');
1222
    array_walk($_COOKIE, '_fix_gpc_magic');
1223
    array_walk($_REQUEST, '_fix_gpc_magic');
1224
    array_walk($_FILES, '_fix_gpc_magic_files');
1225
  }
1226
  $fixed = TRUE;
1227
}
1228

    
1229
/**
1230
 * @defgroup validation Input validation
1231
 * @{
1232
 * Functions to validate user input.
1233
 */
1234

    
1235
/**
1236
 * Verifies the syntax of the given e-mail address.
1237
 *
1238
 * This uses the
1239
 * @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
1240
 *
1241
 * @param $mail
1242
 *   A string containing an e-mail address.
1243
 *
1244
 * @return
1245
 *   TRUE if the address is in a valid format.
1246
 */
1247
function valid_email_address($mail) {
1248
  return (bool)filter_var($mail, FILTER_VALIDATE_EMAIL);
1249
}
1250

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

    
1289
/**
1290
 * @} End of "defgroup validation".
1291
 */
1292

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

    
1320
/**
1321
 * Makes the flood control mechanism forget an event for the current visitor.
1322
 *
1323
 * @param $name
1324
 *   The name of an event.
1325
 * @param $identifier
1326
 *   Optional identifier (defaults to the current user's IP address).
1327
 */
1328
function flood_clear_event($name, $identifier = NULL) {
1329
  if (!isset($identifier)) {
1330
    $identifier = ip_address();
1331
  }
1332
  db_delete('flood')
1333
    ->condition('event', $name)
1334
    ->condition('identifier', $identifier)
1335
    ->execute();
1336
}
1337

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

    
1371
/**
1372
 * @defgroup sanitization Sanitization functions
1373
 * @{
1374
 * Functions to sanitize values.
1375
 *
1376
 * See http://drupal.org/writing-secure-code for information
1377
 * on writing secure code.
1378
 */
1379

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

    
1404
  if (!isset($allowed_protocols)) {
1405
    $allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal')));
1406
  }
1407

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

    
1429
  return $uri;
1430
}
1431

    
1432
/**
1433
 * Strips dangerous protocols from a URI and encodes it for output to HTML.
1434
 *
1435
 * @param $uri
1436
 *   A plain-text URI that might contain dangerous protocols.
1437
 *
1438
 * @return
1439
 *   A URI stripped of dangerous protocols and encoded for output to an HTML
1440
 *   attribute value. Because it is already encoded, it should not be set as a
1441
 *   value within a $attributes array passed to drupal_attributes(), because
1442
 *   drupal_attributes() expects those values to be plain-text strings. To pass
1443
 *   a filtered URI to drupal_attributes(), call
1444
 *   drupal_strip_dangerous_protocols() instead.
1445
 *
1446
 * @see drupal_strip_dangerous_protocols()
1447
 */
1448
function check_url($uri) {
1449
  return check_plain(drupal_strip_dangerous_protocols($uri));
1450
}
1451

    
1452
/**
1453
 * Applies a very permissive XSS/HTML filter for admin-only use.
1454
 *
1455
 * Use only for fields where it is impractical to use the
1456
 * whole filter system, but where some (mainly inline) mark-up
1457
 * is desired (so check_plain() is not acceptable).
1458
 *
1459
 * Allows all tags that can be used inside an HTML body, save
1460
 * for scripts and styles.
1461
 */
1462
function filter_xss_admin($string) {
1463
  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'));
1464
}
1465

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

    
1504
  // Defuse all HTML entities.
1505
  $string = str_replace('&', '&amp;', $string);
1506
  // Change back only well-formed entities in our whitelist:
1507
  // Decimal numeric entities.
1508
  $string = preg_replace('/&amp;#([0-9]+;)/', '&#\1', $string);
1509
  // Hexadecimal numeric entities.
1510
  $string = preg_replace('/&amp;#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\1', $string);
1511
  // Named entities.
1512
  $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string);
1513

    
1514
  return preg_replace_callback('%
1515
    (
1516
    <(?=[^a-zA-Z!/])  # a lone <
1517
    |                 # or
1518
    <!--.*?-->        # a comment
1519
    |                 # or
1520
    <[^>]*(>|$)       # a string that starts with a <, up until the > or the end of the string
1521
    |                 # or
1522
    >                 # just a >
1523
    )%x', '_filter_xss_split', $string);
1524
}
1525

    
1526
/**
1527
 * Processes an HTML tag.
1528
 *
1529
 * @param $m
1530
 *   An array with various meaning depending on the value of $store.
1531
 *   If $store is TRUE then the array contains the allowed tags.
1532
 *   If $store is FALSE then the array has one element, the HTML tag to process.
1533
 * @param $store
1534
 *   Whether to store $m.
1535
 *
1536
 * @return
1537
 *   If the element isn't allowed, an empty string. Otherwise, the cleaned up
1538
 *   version of the HTML element.
1539
 */
1540
function _filter_xss_split($m, $store = FALSE) {
1541
  static $allowed_html;
1542

    
1543
  if ($store) {
1544
    $allowed_html = array_flip($m);
1545
    return;
1546
  }
1547

    
1548
  $string = $m[1];
1549

    
1550
  if (substr($string, 0, 1) != '<') {
1551
    // We matched a lone ">" character.
1552
    return '&gt;';
1553
  }
1554
  elseif (strlen($string) == 1) {
1555
    // We matched a lone "<" character.
1556
    return '&lt;';
1557
  }
1558

    
1559
  if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9\-]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
1560
    // Seriously malformed.
1561
    return '';
1562
  }
1563

    
1564
  $slash = trim($matches[1]);
1565
  $elem = &$matches[2];
1566
  $attrlist = &$matches[3];
1567
  $comment = &$matches[4];
1568

    
1569
  if ($comment) {
1570
    $elem = '!--';
1571
  }
1572

    
1573
  if (!isset($allowed_html[strtolower($elem)])) {
1574
    // Disallowed HTML element.
1575
    return '';
1576
  }
1577

    
1578
  if ($comment) {
1579
    return $comment;
1580
  }
1581

    
1582
  if ($slash != '') {
1583
    return "</$elem>";
1584
  }
1585

    
1586
  // Is there a closing XHTML slash at the end of the attributes?
1587
  $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
1588
  $xhtml_slash = $count ? ' /' : '';
1589

    
1590
  // Clean up attributes.
1591
  $attr2 = implode(' ', _filter_xss_attributes($attrlist));
1592
  $attr2 = preg_replace('/[<>]/', '', $attr2);
1593
  $attr2 = strlen($attr2) ? ' ' . $attr2 : '';
1594

    
1595
  return "<$elem$attr2$xhtml_slash>";
1596
}
1597

    
1598
/**
1599
 * Processes a string of HTML attributes.
1600
 *
1601
 * @return
1602
 *   Cleaned up version of the HTML attributes.
1603
 */
1604
function _filter_xss_attributes($attr) {
1605
  $attrarr = array();
1606
  $mode = 0;
1607
  $attrname = '';
1608

    
1609
  while (strlen($attr) != 0) {
1610
    // Was the last operation successful?
1611
    $working = 0;
1612

    
1613
    switch ($mode) {
1614
      case 0:
1615
        // Attribute name, href for instance.
1616
        if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
1617
          $attrname = strtolower($match[1]);
1618
          $skip = ($attrname == 'style' || substr($attrname, 0, 2) == 'on');
1619
          $working = $mode = 1;
1620
          $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
1621
        }
1622
        break;
1623

    
1624
      case 1:
1625
        // Equals sign or valueless ("selected").
1626
        if (preg_match('/^\s*=\s*/', $attr)) {
1627
          $working = 1; $mode = 2;
1628
          $attr = preg_replace('/^\s*=\s*/', '', $attr);
1629
          break;
1630
        }
1631

    
1632
        if (preg_match('/^\s+/', $attr)) {
1633
          $working = 1; $mode = 0;
1634
          if (!$skip) {
1635
            $attrarr[] = $attrname;
1636
          }
1637
          $attr = preg_replace('/^\s+/', '', $attr);
1638
        }
1639
        break;
1640

    
1641
      case 2:
1642
        // Attribute value, a URL after href= for instance.
1643
        if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
1644
          $thisval = filter_xss_bad_protocol($match[1]);
1645

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

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

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

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

    
1669
          if (!$skip) {
1670
            $attrarr[] = "$attrname=\"$thisval\"";
1671
          }
1672
          $working = 1; $mode = 0;
1673
          $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
1674
        }
1675
        break;
1676
    }
1677

    
1678
    if ($working == 0) {
1679
      // Not well formed; remove and try again.
1680
      $attr = preg_replace('/
1681
        ^
1682
        (
1683
        "[^"]*("|$)     # - a string that starts with a double quote, up until the next double quote or the end of the string
1684
        |               # or
1685
        \'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
1686
        |               # or
1687
        \S              # - a non-whitespace character
1688
        )*              # any number of the above three
1689
        \s*             # any number of whitespaces
1690
        /x', '', $attr);
1691
      $mode = 0;
1692
    }
1693
  }
1694

    
1695
  // The attribute list ends with a valueless attribute like "selected".
1696
  if ($mode == 1 && !$skip) {
1697
    $attrarr[] = $attrname;
1698
  }
1699
  return $attrarr;
1700
}
1701

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

    
1725
    $string = decode_entities($string);
1726
  }
1727
  return check_plain(drupal_strip_dangerous_protocols($string));
1728
}
1729

    
1730
/**
1731
 * @} End of "defgroup sanitization".
1732
 */
1733

    
1734
/**
1735
 * @defgroup format Formatting
1736
 * @{
1737
 * Functions to format numbers, strings, dates, etc.
1738
 */
1739

    
1740
/**
1741
 * Formats an RSS channel.
1742
 *
1743
 * Arbitrary elements may be added using the $args associative array.
1744
 */
1745
function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
1746
  global $language_content;
1747
  $langcode = $langcode ? $langcode : $language_content->language;
1748

    
1749
  $output = "<channel>\n";
1750
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1751
  $output .= ' <link>' . check_url($link) . "</link>\n";
1752

    
1753
  // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
1754
  // We strip all HTML tags, but need to prevent double encoding from properly
1755
  // escaped source data (such as &amp becoming &amp;amp;).
1756
  $output .= ' <description>' . check_plain(decode_entities(strip_tags($description))) . "</description>\n";
1757
  $output .= ' <language>' . check_plain($langcode) . "</language>\n";
1758
  $output .= format_xml_elements($args);
1759
  $output .= $items;
1760
  $output .= "</channel>\n";
1761

    
1762
  return $output;
1763
}
1764

    
1765
/**
1766
 * Formats a single RSS item.
1767
 *
1768
 * Arbitrary elements may be added using the $args associative array.
1769
 */
1770
function format_rss_item($title, $link, $description, $args = array()) {
1771
  $output = "<item>\n";
1772
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1773
  $output .= ' <link>' . check_url($link) . "</link>\n";
1774
  $output .= ' <description>' . check_plain($description) . "</description>\n";
1775
  $output .= format_xml_elements($args);
1776
  $output .= "</item>\n";
1777

    
1778
  return $output;
1779
}
1780

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

    
1811
        if (isset($value['value']) && $value['value'] != '') {
1812
          $output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : (!empty($value['encoded']) ? $value['value'] : check_plain($value['value']))) . '</' . $value['key'] . ">\n";
1813
        }
1814
        else {
1815
          $output .= " />\n";
1816
        }
1817
      }
1818
    }
1819
    else {
1820
      $output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</$key>\n";
1821
    }
1822
  }
1823
  return $output;
1824
}
1825

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

    
1877
  // Get the plural index through the gettext formula.
1878
  $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, isset($options['langcode']) ? $options['langcode'] : NULL) : -1;
1879
  // If the index cannot be computed, use the plural as a fallback (which
1880
  // allows for most flexiblity with the replaceable @count value).
1881
  if ($index < 0) {
1882
    return t($plural, $args, $options);
1883
  }
1884
  else {
1885
    switch ($index) {
1886
      case "0":
1887
        return t($singular, $args, $options);
1888
      case "1":
1889
        return t($plural, $args, $options);
1890
      default:
1891
        unset($args['@count']);
1892
        $args['@count[' . $index . ']'] = $count;
1893
        return t(strtr($plural, array('@count' => '@count[' . $index . ']')), $args, $options);
1894
    }
1895
  }
1896
}
1897

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

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

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

    
1993
    if ($granularity == 0) {
1994
      break;
1995
    }
1996
  }
1997
  return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
1998
}
1999

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

    
2036
  if (!isset($timezone)) {
2037
    $timezone = date_default_timezone_get();
2038
  }
2039
  // Store DateTimeZone objects in an array rather than repeatedly
2040
  // constructing identical objects over the life of a request.
2041
  if (!isset($timezones[$timezone])) {
2042
    $timezones[$timezone] = timezone_open($timezone);
2043
  }
2044

    
2045
  // Use the default langcode if none is set.
2046
  global $language;
2047
  if (empty($langcode)) {
2048
    $langcode = isset($language->language) ? $language->language : 'en';
2049
  }
2050

    
2051
  switch ($type) {
2052
    case 'short':
2053
      $format = variable_get('date_format_short', 'm/d/Y - H:i');
2054
      break;
2055

    
2056
    case 'long':
2057
      $format = variable_get('date_format_long', 'l, F j, Y - H:i');
2058
      break;
2059

    
2060
    case 'custom':
2061
      // No change to format.
2062
      break;
2063

    
2064
    case 'medium':
2065
    default:
2066
      // Retrieve the format of the custom $type passed.
2067
      if ($type != 'medium') {
2068
        $format = variable_get('date_format_' . $type, '');
2069
      }
2070
      // Fall back to 'medium'.
2071
      if ($format === '') {
2072
        $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
2073
      }
2074
      break;
2075
  }
2076

    
2077
  // Create a DateTime object from the timestamp.
2078
  $date_time = date_create('@' . $timestamp);
2079
  // Set the time zone for the DateTime object.
2080
  date_timezone_set($date_time, $timezones[$timezone]);
2081

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

    
2089
  // Call date_format().
2090
  $format = date_format($date_time, $format);
2091

    
2092
  // Pass the langcode to _format_date_callback().
2093
  _format_date_callback(NULL, $langcode);
2094

    
2095
  // Translate the marked sequences.
2096
  return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);
2097
}
2098

    
2099
/**
2100
 * Returns an ISO8601 formatted date based on the given date.
2101
 *
2102
 * Callback for use within hook_rdf_mapping() implementations.
2103
 *
2104
 * @param $date
2105
 *   A UNIX timestamp.
2106
 *
2107
 * @return string
2108
 *   An ISO8601 formatted date.
2109
 */
2110
function date_iso8601($date) {
2111
  // The DATE_ISO8601 constant cannot be used here because it does not match
2112
  // date('c') and produces invalid RDF markup.
2113
  return date('c', $date);
2114
}
2115

    
2116
/**
2117
 * Translates a formatted date string.
2118
 *
2119
 * Callback for preg_replace_callback() within format_date().
2120
 */
2121
function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
2122
  // We cache translations to avoid redundant and rather costly calls to t().
2123
  static $cache, $langcode;
2124

    
2125
  if (!isset($matches)) {
2126
    $langcode = $new_langcode;
2127
    return;
2128
  }
2129

    
2130
  $code = $matches[1];
2131
  $string = $matches[2];
2132

    
2133
  if (!isset($cache[$langcode][$code][$string])) {
2134
    $options = array(
2135
      'langcode' => $langcode,
2136
    );
2137

    
2138
    if ($code == 'F') {
2139
      $options['context'] = 'Long month name';
2140
    }
2141

    
2142
    if ($code == '') {
2143
      $cache[$langcode][$code][$string] = $string;
2144
    }
2145
    else {
2146
      $cache[$langcode][$code][$string] = t($string, array(), $options);
2147
    }
2148
  }
2149
  return $cache[$langcode][$code][$string];
2150
}
2151

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

    
2178
/**
2179
 * @} End of "defgroup format".
2180
 */
2181

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

    
2257
  // Determine whether this is an external link, but ensure that the current
2258
  // path is always treated as internal by default (to prevent external link
2259
  // injection vulnerabilities).
2260
  if (!isset($options['external'])) {
2261
    $options['external'] = $path === $_GET['q'] ? FALSE : url_is_external($path);
2262
  }
2263

    
2264
  // Preserve the original path before altering or aliasing.
2265
  $original_path = $path;
2266

    
2267
  // Allow other modules to alter the outbound URL and options.
2268
  drupal_alter('url_outbound', $path, $options, $original_path);
2269

    
2270
  if (isset($options['fragment']) && $options['fragment'] !== '') {
2271
    $options['fragment'] = '#' . $options['fragment'];
2272
  }
2273

    
2274
  if ($options['external']) {
2275
    // Split off the fragment.
2276
    if (strpos($path, '#') !== FALSE) {
2277
      list($path, $old_fragment) = explode('#', $path, 2);
2278
      // If $options contains no fragment, take it over from the path.
2279
      if (isset($old_fragment) && !$options['fragment']) {
2280
        $options['fragment'] = '#' . $old_fragment;
2281
      }
2282
    }
2283
    // Append the query.
2284
    if ($options['query']) {
2285
      $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($options['query']);
2286
    }
2287
    if (isset($options['https']) && variable_get('https', FALSE)) {
2288
      if ($options['https'] === TRUE) {
2289
        $path = str_replace('http://', 'https://', $path);
2290
      }
2291
      elseif ($options['https'] === FALSE) {
2292
        $path = str_replace('https://', 'http://', $path);
2293
      }
2294
    }
2295
    // Reassemble.
2296
    return $path . $options['fragment'];
2297
  }
2298

    
2299
  // Strip leading slashes from internal paths to prevent them becoming external
2300
  // URLs without protocol. /example.com should not be turned into
2301
  // //example.com.
2302
  $path = ltrim($path, '/');
2303

    
2304
  global $base_url, $base_secure_url, $base_insecure_url;
2305

    
2306
  // The base_url might be rewritten from the language rewrite in domain mode.
2307
  if (!isset($options['base_url'])) {
2308
    if (isset($options['https']) && variable_get('https', FALSE)) {
2309
      if ($options['https'] === TRUE) {
2310
        $options['base_url'] = $base_secure_url;
2311
        $options['absolute'] = TRUE;
2312
      }
2313
      elseif ($options['https'] === FALSE) {
2314
        $options['base_url'] = $base_insecure_url;
2315
        $options['absolute'] = TRUE;
2316
      }
2317
    }
2318
    else {
2319
      $options['base_url'] = $base_url;
2320
    }
2321
  }
2322

    
2323
  // The special path '<front>' links to the default front page.
2324
  if ($path == '<front>') {
2325
    $path = '';
2326
  }
2327
  elseif (!empty($path) && !$options['alias']) {
2328
    $language = isset($options['language']) && isset($options['language']->language) ? $options['language']->language : '';
2329
    $alias = drupal_get_path_alias($original_path, $language);
2330
    if ($alias != $original_path) {
2331
      // Strip leading slashes from internal path aliases to prevent them
2332
      // becoming external URLs without protocol. /example.com should not be
2333
      // turned into //example.com.
2334
      $path = ltrim($alias, '/');
2335
    }
2336
  }
2337

    
2338
  $base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
2339
  $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
2340

    
2341
  // With Clean URLs.
2342
  if (!empty($GLOBALS['conf']['clean_url'])) {
2343
    $path = drupal_encode_path($prefix . $path);
2344
    if ($options['query']) {
2345
      return $base . $path . '?' . drupal_http_build_query($options['query']) . $options['fragment'];
2346
    }
2347
    else {
2348
      return $base . $path . $options['fragment'];
2349
    }
2350
  }
2351
  // Without Clean URLs.
2352
  else {
2353
    $path = $prefix . $path;
2354
    $query = array();
2355
    if (!empty($path)) {
2356
      $query['q'] = $path;
2357
    }
2358
    if ($options['query']) {
2359
      // We do not use array_merge() here to prevent overriding $path via query
2360
      // parameters.
2361
      $query += $options['query'];
2362
    }
2363
    $query = $query ? ('?' . drupal_http_build_query($query)) : '';
2364
    $script = isset($options['script']) ? $options['script'] : '';
2365
    return $base . $script . $query . $options['fragment'];
2366
  }
2367
}
2368

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

    
2401
/**
2402
 * Formats an attribute string for an HTTP header.
2403
 *
2404
 * @param $attributes
2405
 *   An associative array of attributes such as 'rel'.
2406
 *
2407
 * @return
2408
 *   A ; separated string ready for insertion in a HTTP header. No escaping is
2409
 *   performed for HTML entities, so this string is not safe to be printed.
2410
 *
2411
 * @see drupal_add_http_header()
2412
 */
2413
function drupal_http_header_attributes(array $attributes = array()) {
2414
  foreach ($attributes as $attribute => &$data) {
2415
    if (is_array($data)) {
2416
      $data = implode(' ', $data);
2417
    }
2418
    $data = $attribute . '="' . $data . '"';
2419
  }
2420
  return $attributes ? ' ' . implode('; ', $attributes) : '';
2421
}
2422

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

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

    
2518
  // Merge in defaults.
2519
  $options += array(
2520
    'attributes' => array(),
2521
    'html' => FALSE,
2522
  );
2523

    
2524
  // Append active class.
2525
  if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
2526
      (empty($options['language']) || $options['language']->language == $language_url->language)) {
2527
    $options['attributes']['class'][] = 'active';
2528
  }
2529

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

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

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

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

    
2676
  // Send appropriate HTTP-Header for browsers and search engines.
2677
  global $language;
2678
  drupal_add_http_header('Content-Language', $language->language);
2679

    
2680
  // By default, do not allow the site to be rendered in an iframe on another
2681
  // domain, but provide a variable to override this. If the code running for
2682
  // this page request already set the X-Frame-Options header earlier, don't
2683
  // overwrite it here.
2684
  $frame_options = variable_get('x_frame_options', 'SAMEORIGIN');
2685
  if ($frame_options && is_null(drupal_get_http_header('X-Frame-Options'))) {
2686
    drupal_add_http_header('X-Frame-Options', $frame_options);
2687
  }
2688

    
2689
  // Menu status constants are integers; page content is a string or array.
2690
  if (is_int($page_callback_result)) {
2691
    // @todo: Break these up into separate functions?
2692
    switch ($page_callback_result) {
2693
      case MENU_NOT_FOUND:
2694
        // Print a 404 page.
2695
        drupal_add_http_header('Status', '404 Not Found');
2696

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

    
2699
        // Check for and return a fast 404 page if configured.
2700
        drupal_fast_404();
2701

    
2702
        // Keep old path for reference, and to allow forms to redirect to it.
2703
        if (!isset($_GET['destination'])) {
2704
          // Make sure that the current path is not interpreted as external URL.
2705
          if (!url_is_external($_GET['q'])) {
2706
            $_GET['destination'] = $_GET['q'];
2707
          }
2708
        }
2709

    
2710
        $path = drupal_get_normal_path(variable_get('site_404', ''));
2711
        if ($path && $path != $_GET['q']) {
2712
          // Custom 404 handler. Set the active item in case there are tabs to
2713
          // display, or other dependencies on the path.
2714
          menu_set_active_item($path);
2715
          $return = menu_execute_active_handler($path, FALSE);
2716
        }
2717

    
2718
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2719
          // Standard 404 handler.
2720
          drupal_set_title(t('Page not found'));
2721
          $return = t('The requested page "@path" could not be found.', array('@path' => request_uri()));
2722
        }
2723

    
2724
        drupal_set_page_content($return);
2725
        $page = element_info('page');
2726
        print drupal_render_page($page);
2727
        break;
2728

    
2729
      case MENU_ACCESS_DENIED:
2730
        // Print a 403 page.
2731
        drupal_add_http_header('Status', '403 Forbidden');
2732
        watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
2733

    
2734
        // Keep old path for reference, and to allow forms to redirect to it.
2735
        if (!isset($_GET['destination'])) {
2736
          // Make sure that the current path is not interpreted as external URL.
2737
          if (!url_is_external($_GET['q'])) {
2738
            $_GET['destination'] = $_GET['q'];
2739
          }
2740
        }
2741

    
2742
        $path = drupal_get_normal_path(variable_get('site_403', ''));
2743
        if ($path && $path != $_GET['q']) {
2744
          // Custom 403 handler. Set the active item in case there are tabs to
2745
          // display or other dependencies on the path.
2746
          menu_set_active_item($path);
2747
          $return = menu_execute_active_handler($path, FALSE);
2748
        }
2749

    
2750
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2751
          // Standard 403 handler.
2752
          drupal_set_title(t('Access denied'));
2753
          $return = t('You are not authorized to access this page.');
2754
        }
2755

    
2756
        print drupal_render_page($return);
2757
        break;
2758

    
2759
      case MENU_SITE_OFFLINE:
2760
        // Print a 503 page.
2761
        drupal_maintenance_theme();
2762
        drupal_add_http_header('Status', '503 Service unavailable');
2763
        drupal_set_title(t('Site under maintenance'));
2764
        print theme('maintenance_page', array('content' => filter_xss_admin(variable_get('maintenance_mode_message',
2765
          t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))))));
2766
        break;
2767
    }
2768
  }
2769
  elseif (isset($page_callback_result)) {
2770
    // Print anything besides a menu constant, assuming it's not NULL or
2771
    // undefined.
2772
    print drupal_render_page($page_callback_result);
2773
  }
2774

    
2775
  // Perform end-of-request tasks.
2776
  drupal_page_footer();
2777
}
2778

    
2779
/**
2780
 * Performs end-of-request tasks.
2781
 *
2782
 * This function sets the page cache if appropriate, and allows modules to
2783
 * react to the closing of the page by calling hook_exit().
2784
 */
2785
function drupal_page_footer() {
2786
  global $user;
2787

    
2788
  module_invoke_all('exit');
2789

    
2790
  // Commit the user session, if needed.
2791
  drupal_session_commit();
2792

    
2793
  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
2794
    drupal_serve_page_from_cache($cache);
2795
  }
2796
  else {
2797
    ob_flush();
2798
  }
2799

    
2800
  _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
2801
  drupal_cache_system_paths();
2802
  module_implements_write_cache();
2803
  drupal_file_scan_write_cache();
2804
  system_run_automated_cron();
2805
}
2806

    
2807
/**
2808
 * Performs end-of-request tasks.
2809
 *
2810
 * In some cases page requests need to end without calling drupal_page_footer().
2811
 * In these cases, call drupal_exit() instead. There should rarely be a reason
2812
 * to call exit instead of drupal_exit();
2813
 *
2814
 * @param $destination
2815
 *   If this function is called from drupal_goto(), then this argument
2816
 *   will be a fully-qualified URL that is the destination of the redirect.
2817
 *   This should be passed along to hook_exit() implementations.
2818
 */
2819
function drupal_exit($destination = NULL) {
2820
  if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL) {
2821
    if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
2822
      module_invoke_all('exit', $destination);
2823
    }
2824
    drupal_session_commit();
2825
  }
2826
  exit;
2827
}
2828

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

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

    
2894
/**
2895
 * Returns the path to a system item (module, theme, etc.).
2896
 *
2897
 * @param $type
2898
 *   The type of the item (i.e. theme, theme_engine, module, profile).
2899
 * @param $name
2900
 *   The name of the item for which the path is requested.
2901
 *
2902
 * @return
2903
 *   The path to the requested item or an empty string if the item is not found.
2904
 */
2905
function drupal_get_path($type, $name) {
2906
  return dirname(drupal_get_filename($type, $name));
2907
}
2908

    
2909
/**
2910
 * Returns the base URL path (i.e., directory) of the Drupal installation.
2911
 *
2912
 * base_path() adds a "/" to the beginning and end of the returned path if the
2913
 * path is not empty. At the very least, this will return "/".
2914
 *
2915
 * Examples:
2916
 * - http://example.com returns "/" because the path is empty.
2917
 * - http://example.com/drupal/folder returns "/drupal/folder/".
2918
 */
2919
function base_path() {
2920
  return $GLOBALS['base_path'];
2921
}
2922

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

    
2943
  if ($header) {
2944
    // Also add a HTTP header "Link:".
2945
    $href = '<' . check_plain($attributes['href']) . '>;';
2946
    unset($attributes['href']);
2947
    $element['#attached']['drupal_add_http_header'][] = array('Link',  $href . drupal_http_header_attributes($attributes), TRUE);
2948
  }
2949

    
2950
  drupal_add_html_head($element, 'drupal_add_html_head_link:' . $attributes['rel'] . ':' . $href);
2951
}
2952

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

    
3073
  // If the $css variable has been reset with drupal_static_reset(), there is
3074
  // no longer any CSS being tracked, so set the counter back to 0 also.
3075
  if (count($css) === 0) {
3076
    $count = 0;
3077
  }
3078

    
3079
  // Construct the options, taking the defaults into consideration.
3080
  if (isset($options)) {
3081
    if (!is_array($options)) {
3082
      $options = array('type' => $options);
3083
    }
3084
  }
3085
  else {
3086
    $options = array();
3087
  }
3088

    
3089
  // Create an array of CSS files for each media type first, since each type needs to be served
3090
  // to the browser differently.
3091
  if (isset($data)) {
3092
    $options += array(
3093
      'type' => 'file',
3094
      'group' => CSS_DEFAULT,
3095
      'weight' => 0,
3096
      'every_page' => FALSE,
3097
      'media' => 'all',
3098
      'preprocess' => TRUE,
3099
      'data' => $data,
3100
      'browsers' => array(),
3101
    );
3102
    $options['browsers'] += array(
3103
      'IE' => TRUE,
3104
      '!IE' => TRUE,
3105
    );
3106

    
3107
    // Files with a query string cannot be preprocessed.
3108
    if ($options['type'] === 'file' && $options['preprocess'] && strpos($options['data'], '?') !== FALSE) {
3109
      $options['preprocess'] = FALSE;
3110
    }
3111

    
3112
    // Always add a tiny value to the weight, to conserve the insertion order.
3113
    $options['weight'] += $count / 1000;
3114
    $count++;
3115

    
3116
    // Add the data to the CSS array depending on the type.
3117
    switch ($options['type']) {
3118
      case 'inline':
3119
        // For inline stylesheets, we don't want to use the $data as the array
3120
        // key as $data could be a very long string of CSS.
3121
        $css[] = $options;
3122
        break;
3123
      default:
3124
        // Local and external files must keep their name as the associative key
3125
        // so the same CSS file is not be added twice.
3126
        $css[$data] = $options;
3127
    }
3128
  }
3129

    
3130
  return $css;
3131
}
3132

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

    
3167
  // Allow modules and themes to alter the CSS items.
3168
  if (!$skip_alter) {
3169
    drupal_alter('css', $css);
3170
  }
3171

    
3172
  // Sort CSS items, so that they appear in the correct order.
3173
  uasort($css, 'drupal_sort_css_js');
3174

    
3175
  // Provide the page with information about the individual CSS files used,
3176
  // information not otherwise available when CSS aggregation is enabled. The
3177
  // setting is attached later in this function, but is set here, so that CSS
3178
  // files removed below are still considered "used" and prevented from being
3179
  // added in a later AJAX request.
3180
  // Skip if no files were added to the page or jQuery.extend() will overwrite
3181
  // the Drupal.settings.ajaxPageState.css object with an empty array.
3182
  if (!empty($css)) {
3183
    // Cast the array to an object to be on the safe side even if not empty.
3184
    $setting['ajaxPageState']['css'] = (object) array_fill_keys(array_keys($css), 1);
3185
  }
3186

    
3187
  // Remove the overridden CSS files. Later CSS files override former ones.
3188
  $previous_item = array();
3189
  foreach ($css as $key => $item) {
3190
    if ($item['type'] == 'file') {
3191
      // If defined, force a unique basename for this file.
3192
      $basename = isset($item['basename']) ? $item['basename'] : drupal_basename($item['data']);
3193
      if (isset($previous_item[$basename])) {
3194
        // Remove the previous item that shared the same base name.
3195
        unset($css[$previous_item[$basename]]);
3196
      }
3197
      $previous_item[$basename] = $key;
3198
    }
3199
  }
3200

    
3201
  // Render the HTML needed to load the CSS.
3202
  $styles = array(
3203
    '#type' => 'styles',
3204
    '#items' => $css,
3205
  );
3206

    
3207
  if (!empty($setting)) {
3208
    $styles['#attached']['js'][] = array('type' => 'setting', 'data' => $setting);
3209
  }
3210

    
3211
  return drupal_render($styles);
3212
}
3213

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

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

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

    
3346
    // If the group keys don't match the most recent group we're working with,
3347
    // then a new group must be made.
3348
    if ($group_keys !== $current_group_keys) {
3349
      $i++;
3350
      // Initialize the new group with the same properties as the first item
3351
      // being placed into it. The item's 'data' and 'weight' properties are
3352
      // unique to the item and should not be carried over to the group.
3353
      $groups[$i] = $item;
3354
      unset($groups[$i]['data'], $groups[$i]['weight']);
3355
      $groups[$i]['items'] = array();
3356
      $current_group_keys = $group_keys ? $group_keys : NULL;
3357
    }
3358

    
3359
    // Add the item to the current group.
3360
    $groups[$i]['items'][] = $item;
3361
  }
3362
  return $groups;
3363
}
3364

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

    
3387
  // For each group that needs aggregation, aggregate its items.
3388
  foreach ($css_groups as $key => $group) {
3389
    switch ($group['type']) {
3390
      // If a file group can be aggregated into a single file, do so, and set
3391
      // the group's data property to the file path of the aggregate file.
3392
      case 'file':
3393
        if ($group['preprocess'] && $preprocess_css) {
3394
          $css_groups[$key]['data'] = drupal_build_css_cache($group['items']);
3395
        }
3396
        break;
3397
      // Aggregate all inline CSS content into the group's data property.
3398
      case 'inline':
3399
        $css_groups[$key]['data'] = '';
3400
        foreach ($group['items'] as $item) {
3401
          $css_groups[$key]['data'] .= drupal_load_stylesheet_content($item['data'], $item['preprocess']);
3402
        }
3403
        break;
3404
    }
3405
  }
3406
}
3407

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

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

    
3484
  // For inline CSS to validate as XHTML, all CSS containing XHTML needs to be
3485
  // wrapped in CDATA. To make that backwards compatible with HTML 4, we need to
3486
  // comment out the CDATA-tag.
3487
  $embed_prefix = "\n<!--/*--><![CDATA[/*><!--*/\n";
3488
  $embed_suffix = "\n/*]]>*/-->\n";
3489

    
3490
  // Defaults for LINK and STYLE elements.
3491
  $link_element_defaults = array(
3492
    '#type' => 'html_tag',
3493
    '#tag' => 'link',
3494
    '#attributes' => array(
3495
      'type' => 'text/css',
3496
      'rel' => 'stylesheet',
3497
    ),
3498
  );
3499
  $style_element_defaults = array(
3500
    '#type' => 'html_tag',
3501
    '#tag' => 'style',
3502
    '#attributes' => array(
3503
      'type' => 'text/css',
3504
    ),
3505
  );
3506

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

    
3633
  return $elements;
3634
}
3635

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

    
3675
  if (empty($uri) || !file_exists($uri)) {
3676
    // Build aggregate CSS file.
3677
    foreach ($css as $stylesheet) {
3678
      // Only 'file' stylesheets can be aggregated.
3679
      if ($stylesheet['type'] == 'file') {
3680
        $contents = drupal_load_stylesheet($stylesheet['data'], TRUE);
3681

    
3682
        // Build the base URL of this CSS file: start with the full URL.
3683
        $css_base_url = file_create_url($stylesheet['data']);
3684
        // Move to the parent.
3685
        $css_base_url = substr($css_base_url, 0, strrpos($css_base_url, '/'));
3686
        // Simplify to a relative URL if the stylesheet URL starts with the
3687
        // base URL of the website.
3688
        if (substr($css_base_url, 0, strlen($GLOBALS['base_root'])) == $GLOBALS['base_root']) {
3689
          $css_base_url = substr($css_base_url, strlen($GLOBALS['base_root']));
3690
        }
3691

    
3692
        _drupal_build_css_path(NULL, $css_base_url . '/');
3693
        // Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
3694
        $data .= preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);
3695
      }
3696
    }
3697

    
3698
    // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
3699
    // @import rules must proceed any other style, so we move those to the top.
3700
    $regexp = '/@import[^;]+;/i';
3701
    preg_match_all($regexp, $data, $matches);
3702
    $data = preg_replace($regexp, '', $data);
3703
    $data = implode('', $matches[0]) . $data;
3704

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

    
3732
/**
3733
 * Prefixes all paths within a CSS file for drupal_build_css_cache().
3734
 */
3735
function _drupal_build_css_path($matches, $base = NULL) {
3736
  $_base = &drupal_static(__FUNCTION__);
3737
  // Store base path for preg_replace_callback.
3738
  if (isset($base)) {
3739
    $_base = $base;
3740
  }
3741

    
3742
  // Prefix with base and remove '../' segments where possible.
3743
  $path = $_base . $matches[1];
3744
  $last = '';
3745
  while ($path != $last) {
3746
    $last = $path;
3747
    $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
3748
  }
3749
  return 'url(' . $path . ')';
3750
}
3751

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

    
3785
  // Stylesheets are relative one to each other. Start by adding a base path
3786
  // prefix provided by the parent stylesheet (if necessary).
3787
  if ($basepath && !file_uri_scheme($file)) {
3788
    $file = $basepath . '/' . $file;
3789
  }
3790
  // Store the parent base path to restore it later.
3791
  $parent_base_path = $basepath;
3792
  // Set the current base path to process possible child imports.
3793
  $basepath = dirname($file);
3794

    
3795
  // Load the CSS stylesheet. We suppress errors because themes may specify
3796
  // stylesheets in their .info file that don't exist in the theme's path,
3797
  // but are merely there to disable certain module CSS files.
3798
  $content = '';
3799
  if ($contents = @file_get_contents($file)) {
3800
    // Return the processed stylesheet.
3801
    $content = drupal_load_stylesheet_content($contents, $_optimize);
3802
  }
3803

    
3804
  // Restore the parent base path as the file and its childen are processed.
3805
  $basepath = $parent_base_path;
3806
  return $content;
3807
}
3808

    
3809
/**
3810
 * Processes the contents of a stylesheet for aggregation.
3811
 *
3812
 * @param $contents
3813
 *   The contents of the stylesheet.
3814
 * @param $optimize
3815
 *   (optional) Boolean whether CSS contents should be minified. Defaults to
3816
 *   FALSE.
3817
 *
3818
 * @return
3819
 *   Contents of the stylesheet including the imported stylesheets.
3820
 */
3821
function drupal_load_stylesheet_content($contents, $optimize = FALSE) {
3822
  // Remove multiple charset declarations for standards compliance (and fixing Safari problems).
3823
  $contents = preg_replace('/^@charset\s+[\'"](\S*?)\b[\'"];/i', '', $contents);
3824

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

    
3865
  // Replaces @import commands with the actual stylesheet content.
3866
  // This happens recursively but omits external files.
3867
  $contents = preg_replace_callback('/@import\s*(?:url\(\s*)?[\'"]?(?![a-z]+:)(?!\/\/)([^\'"\()]+)[\'"]?\s*\)?\s*;/', '_drupal_load_stylesheet', $contents);
3868
  return $contents;
3869
}
3870

    
3871
/**
3872
 * Loads stylesheets recursively and returns contents with corrected paths.
3873
 *
3874
 * This function is used for recursive loading of stylesheets and
3875
 * returns the stylesheet content with all url() paths corrected.
3876
 */
3877
function _drupal_load_stylesheet($matches) {
3878
  $filename = $matches[1];
3879
  // Load the imported stylesheet and replace @import commands in there as well.
3880
  $file = drupal_load_stylesheet($filename, NULL, FALSE);
3881

    
3882
  // Determine the file's directory.
3883
  $directory = dirname($filename);
3884
  // If the file is in the current directory, make sure '.' doesn't appear in
3885
  // the url() path.
3886
  $directory = $directory == '.' ? '' : $directory .'/';
3887

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

    
3894
/**
3895
 * Deletes old cached CSS files.
3896
 */
3897
function drupal_clear_css_cache() {
3898
  variable_del('drupal_css_cache_files');
3899
  file_scan_directory('public://css', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
3900
}
3901

    
3902
/**
3903
 * Callback to delete files modified more than a set time ago.
3904
 */
3905
function drupal_delete_file_if_stale($uri) {
3906
  // Default stale file threshold is 30 days.
3907
  if (REQUEST_TIME - filemtime($uri) > variable_get('drupal_stale_file_threshold', 2592000)) {
3908
    file_unmanaged_delete($uri);
3909
  }
3910
}
3911

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

    
3937
  // Preserve BEM-style double-underscores depending on custom setting.
3938
  if ($allow_css_double_underscores) {
3939
    $filter['__'] = '__';
3940
  }
3941

    
3942
  // By default, we filter using Drupal's coding standards.
3943
  $identifier = strtr($identifier, $filter);
3944

    
3945
  // Valid characters in a CSS identifier are:
3946
  // - the hyphen (U+002D)
3947
  // - a-z (U+0030 - U+0039)
3948
  // - A-Z (U+0041 - U+005A)
3949
  // - the underscore (U+005F)
3950
  // - 0-9 (U+0061 - U+007A)
3951
  // - ISO 10646 characters U+00A1 and higher
3952
  // We strip out any character not in the above list.
3953
  $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);
3954

    
3955
  return $identifier;
3956
}
3957

    
3958
/**
3959
 * Prepares a string for use as a valid class name.
3960
 *
3961
 * Do not pass one string containing multiple classes as they will be
3962
 * incorrectly concatenated with dashes, i.e. "one two" will become "one-two".
3963
 *
3964
 * @param $class
3965
 *   The class name to clean.
3966
 *
3967
 * @return
3968
 *   The cleaned class name.
3969
 */
3970
function drupal_html_class($class) {
3971
  // The output of this function will never change, so this uses a normal
3972
  // static instead of drupal_static().
3973
  static $classes = array();
3974

    
3975
  if (!isset($classes[$class])) {
3976
    $classes[$class] = drupal_clean_css_identifier(drupal_strtolower($class));
3977
  }
3978
  return $classes[$class];
3979
}
3980

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

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

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

    
4077
  // Removing multiple consecutive hyphens.
4078
  $id = preg_replace('/\-+/', '-', $id);
4079
  // Ensure IDs are unique by appending a counter after the first occurrence.
4080
  // The counter needs to be appended with a delimiter that does not exist in
4081
  // the base ID. Requiring a unique delimiter helps ensure that we really do
4082
  // return unique IDs and also helps us re-create the $seen_ids array during
4083
  // Ajax requests.
4084
  if (isset($seen_ids[$id])) {
4085
    $id = $id . '--' . ++$seen_ids[$id];
4086
  }
4087
  else {
4088
    $seen_ids[$id] = 1;
4089
  }
4090

    
4091
  return $id;
4092
}
4093

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

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

    
4275
  // If the $javascript variable has been reset with drupal_static_reset(),
4276
  // jQuery and related files will have been removed from the list, so set the
4277
  // variable back to FALSE to indicate they have not yet been added.
4278
  if (empty($javascript)) {
4279
    $jquery_added = FALSE;
4280
  }
4281

    
4282
  // Construct the options, taking the defaults into consideration.
4283
  if (isset($options)) {
4284
    if (!is_array($options)) {
4285
      $options = array('type' => $options);
4286
    }
4287
  }
4288
  else {
4289
    $options = array();
4290
  }
4291
  if (isset($options['type']) && $options['type'] == 'setting') {
4292
    $options += array('requires_jquery' => FALSE);
4293
  }
4294
  $options += drupal_js_defaults($data);
4295

    
4296
  // Preprocess can only be set if caching is enabled.
4297
  $options['preprocess'] = $options['cache'] ? $options['preprocess'] : FALSE;
4298

    
4299
  // Tweak the weight so that files of the same weight are included in the
4300
  // order of the calls to drupal_add_js().
4301
  $options['weight'] += count($javascript) / 1000;
4302

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

    
4346
    switch ($options['type']) {
4347
      case 'setting':
4348
        // All JavaScript settings are placed in the header of the page with
4349
        // the library weight so that inline scripts appear afterwards.
4350
        $javascript['settings']['data'][] = $data;
4351
        break;
4352

    
4353
      case 'inline':
4354
        $javascript[] = $options;
4355
        break;
4356

    
4357
      default: // 'file' and 'external'
4358
        // Local and external files must keep their name as the associative key
4359
        // so the same JavaScript file is not added twice.
4360
        $javascript[$options['data']] = $options;
4361
    }
4362
  }
4363
  return $javascript;
4364
}
4365

    
4366
/**
4367
 * Constructs an array of the defaults that are used for JavaScript items.
4368
 *
4369
 * @param $data
4370
 *   (optional) The default data parameter for the JavaScript item array.
4371
 *
4372
 * @see drupal_get_js()
4373
 * @see drupal_add_js()
4374
 */
4375
function drupal_js_defaults($data = NULL) {
4376
  return array(
4377
    'type' => 'file',
4378
    'group' => JS_DEFAULT,
4379
    'every_page' => FALSE,
4380
    'weight' => 0,
4381
    'requires_jquery' => TRUE,
4382
    'scope' => 'header',
4383
    'cache' => TRUE,
4384
    'defer' => FALSE,
4385
    'preprocess' => TRUE,
4386
    'version' => NULL,
4387
    'data' => $data,
4388
  );
4389
}
4390

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

    
4429
  // If no JavaScript items have been added, or if the only JavaScript items
4430
  // that have been added are JavaScript settings (which don't do anything
4431
  // without any JavaScript code to use them), then no JavaScript code should
4432
  // be added to the page.
4433
  if (empty($javascript) || (isset($javascript['settings']) && count($javascript) == 1)) {
4434
    return '';
4435
  }
4436

    
4437
  // Allow modules to alter the JavaScript.
4438
  if (!$skip_alter) {
4439
    drupal_alter('js', $javascript);
4440
  }
4441

    
4442
  // Filter out elements of the given scope.
4443
  $items = array();
4444
  foreach ($javascript as $key => $item) {
4445
    if ($item['scope'] == $scope) {
4446
      $items[$key] = $item;
4447
    }
4448
  }
4449

    
4450
  // Sort the JavaScript so that it appears in the correct order.
4451
  uasort($items, 'drupal_sort_css_js');
4452

    
4453
  // Provide the page with information about the individual JavaScript files
4454
  // used, information not otherwise available when aggregation is enabled.
4455
  $setting['ajaxPageState']['js'] = array_fill_keys(array_keys($items), 1);
4456
  unset($setting['ajaxPageState']['js']['settings']);
4457
  drupal_add_js($setting, 'setting');
4458

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

    
4469
  $elements = array(
4470
    '#type' => 'scripts',
4471
    '#items' => $items,
4472
  );
4473

    
4474
  return drupal_render($elements);
4475
}
4476

    
4477
/**
4478
 * The #pre_render callback for the "scripts" element.
4479
 *
4480
 * This callback adds elements needed for <script> tags to be rendered.
4481
 *
4482
 * @param array $elements
4483
 *   A render array containing:
4484
 *   - '#items': The JS items as returned by drupal_add_js() and altered by
4485
 *     drupal_get_js().
4486
 *
4487
 * @return array
4488
 *   The $elements variable passed as argument with two more children keys:
4489
 *     - "scripts": contains the Javascript items
4490
 *     - "settings": contains the Javascript settings items.
4491
 *   If those keys are already existing, then the items will be appended and
4492
 *   their keys will be preserved.
4493
 *
4494
 * @see drupal_get_js()
4495
 * @see drupal_add_js()
4496
 */
4497
function drupal_pre_render_scripts(array $elements) {
4498
  $preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
4499

    
4500
  // A dummy query-string is added to filenames, to gain control over
4501
  // browser-caching. The string changes on every update or full cache
4502
  // flush, forcing browsers to load a new copy of the files, as the
4503
  // URL changed. Files that should not be cached (see drupal_add_js())
4504
  // get REQUEST_TIME as query-string instead, to enforce reload on every
4505
  // page request.
4506
  $default_query_string = variable_get('css_js_query_string', '0');
4507

    
4508
  // For inline JavaScript to validate as XHTML, all JavaScript containing
4509
  // XHTML needs to be wrapped in CDATA. To make that backwards compatible
4510
  // with HTML 4, we need to comment out the CDATA-tag.
4511
  $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
4512
  $embed_suffix = "\n//--><!]]>\n";
4513

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

    
4518
  $files = array();
4519

    
4520
  $scripts = isset($elements['scripts']) ? $elements['scripts'] : array();
4521
  $scripts += array('#weight' => 0);
4522

    
4523
  $settings = isset($elements['settings']) ? $elements['settings'] : array();
4524
  $settings += array('#weight' => $scripts['#weight'] + 10);
4525

    
4526
  // The index counter is used to keep aggregated and non-aggregated files in
4527
  // order by weight. Use existing scripts count as a starting point.
4528
  $index = count(element_children($scripts)) + 1;
4529

    
4530
  // Loop through the JavaScript to construct the rendered output.
4531
  $element = array(
4532
    '#type' => 'html_tag',
4533
    '#tag' => 'script',
4534
    '#value' => '',
4535
    '#attributes' => array(
4536
      'type' => 'text/javascript',
4537
    ),
4538
  );
4539

    
4540
  foreach ($elements['#items'] as $item) {
4541
    $query_string =  empty($item['version']) ? $default_query_string : $js_version_string . $item['version'];
4542

    
4543
    switch ($item['type']) {
4544
      case 'setting':
4545
        $js_element = $element;
4546
        $js_element['#value_prefix'] = $embed_prefix;
4547
        $js_element['#value'] = 'jQuery.extend(Drupal.settings, ' . drupal_json_encode(drupal_array_merge_deep_array($item['data'])) . ");";
4548
        $js_element['#value_suffix'] = $embed_suffix;
4549
        $settings[] = $js_element;
4550
        break;
4551

    
4552
      case 'inline':
4553
        $js_element = $element;
4554
        if ($item['defer']) {
4555
          $js_element['#attributes']['defer'] = 'defer';
4556
        }
4557
        $js_element['#value_prefix'] = $embed_prefix;
4558
        $js_element['#value'] = $item['data'];
4559
        $js_element['#value_suffix'] = $embed_suffix;
4560
        $scripts[$index++] = $js_element;
4561
        break;
4562

    
4563
      case 'file':
4564
        $js_element = $element;
4565
        if (!$item['preprocess'] || !$preprocess_js) {
4566
          if ($item['defer']) {
4567
            $js_element['#attributes']['defer'] = 'defer';
4568
          }
4569
          $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
4570
          $js_element['#attributes']['src'] = file_create_url($item['data']) . $query_string_separator . ($item['cache'] ? $query_string : REQUEST_TIME);
4571
          $scripts[$index++] = $js_element;
4572
        }
4573
        else {
4574
          // By increasing the index for each aggregated file, we maintain
4575
          // the relative ordering of JS by weight. We also set the key such
4576
          // that groups are split by items sharing the same 'group' value and
4577
          // 'every_page' flag. While this potentially results in more aggregate
4578
          // files, it helps make each one more reusable across a site visit,
4579
          // leading to better front-end performance of a website as a whole.
4580
          // See drupal_add_js() for details.
4581
          $key = 'aggregate_' . $item['group'] . '_' . $item['every_page'] . '_' . $index;
4582
          $scripts[$key] = '';
4583
          $files[$key][$item['data']] = $item;
4584
        }
4585
        break;
4586

    
4587
      case 'external':
4588
        $js_element = $element;
4589
        // Preprocessing for external JavaScript files is ignored.
4590
        if ($item['defer']) {
4591
          $js_element['#attributes']['defer'] = 'defer';
4592
        }
4593
        $js_element['#attributes']['src'] = $item['data'];
4594
        $scripts[$index++] = $js_element;
4595
        break;
4596
    }
4597
  }
4598

    
4599
  // Aggregate any remaining JS files that haven't already been output.
4600
  if ($preprocess_js && count($files) > 0) {
4601
    foreach ($files as $key => $file_set) {
4602
      $uri = drupal_build_js_cache($file_set);
4603
      // Only include the file if was written successfully. Errors are logged
4604
      // using watchdog.
4605
      if ($uri) {
4606
        $preprocess_file = file_create_url($uri);
4607
        $js_element = $element;
4608
        $js_element['#attributes']['src'] = $preprocess_file;
4609
        $scripts[$key] = $js_element;
4610
      }
4611
    }
4612
  }
4613

    
4614
  // Keep the order of JS files consistent as some are preprocessed and others
4615
  // are not. Make sure any inline or JS setting variables appear last after
4616
  // libraries have loaded.
4617
  $element['scripts'] = $scripts;
4618
  $element['settings'] = $settings;
4619

    
4620
  return $element;
4621
}
4622

    
4623
/**
4624
 * Adds attachments to a render() structure.
4625
 *
4626
 * Libraries, JavaScript, CSS and other types of custom structures are attached
4627
 * to elements using the #attached property. The #attached property is an
4628
 * associative array, where the keys are the attachment types and the values are
4629
 * the attached data. For example:
4630
 * @code
4631
 * $build['#attached'] = array(
4632
 *   'js' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.js'),
4633
 *   'css' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.css'),
4634
 * );
4635
 * @endcode
4636
 *
4637
 * 'js', 'css', and 'library' are types that get special handling. For any
4638
 * other kind of attached data, the array key must be the full name of the
4639
 * callback function and each value an array of arguments. For example:
4640
 * @code
4641
 * $build['#attached']['drupal_add_http_header'] = array(
4642
 *   array('Content-Type', 'application/rss+xml; charset=utf-8'),
4643
 * );
4644
 * @endcode
4645
 *
4646
 * External 'js' and 'css' files can also be loaded. For example:
4647
 * @code
4648
 * $build['#attached']['js'] = array(
4649
 *   'http://code.jquery.com/jquery-1.4.2.min.js' => array(
4650
 *     'type' => 'external',
4651
 *   ),
4652
 * );
4653
 * @endcode
4654
 *
4655
 * @param $elements
4656
 *   The structured array describing the data being rendered.
4657
 * @param $group
4658
 *   The default group of JavaScript and CSS being added. This is only applied
4659
 *   to the stylesheets and JavaScript items that don't have an explicit group
4660
 *   assigned to them.
4661
 * @param $dependency_check
4662
 *   When TRUE, will exit if a given library's dependencies are missing. When
4663
 *   set to FALSE, will continue to add the libraries, even though one or more
4664
 *   dependencies are missing. Defaults to FALSE.
4665
 * @param $every_page
4666
 *   Set to TRUE to indicate that the attachments are added to every page on the
4667
 *   site. Only attachments with the every_page flag set to TRUE can participate
4668
 *   in JavaScript/CSS aggregation.
4669
 *
4670
 * @return
4671
 *   FALSE if there were any missing library dependencies; TRUE if all library
4672
 *   dependencies were met.
4673
 *
4674
 * @see drupal_add_library()
4675
 * @see drupal_add_js()
4676
 * @see drupal_add_css()
4677
 * @see drupal_render()
4678
 */
4679
function drupal_process_attached($elements, $group = JS_DEFAULT, $dependency_check = FALSE, $every_page = NULL) {
4680
  // Add defaults to the special attached structures that should be processed differently.
4681
  $elements['#attached'] += array(
4682
    'library' => array(),
4683
    'js' => array(),
4684
    'css' => array(),
4685
  );
4686

    
4687
  // Add the libraries first.
4688
  $success = TRUE;
4689
  foreach ($elements['#attached']['library'] as $library) {
4690
    if (drupal_add_library($library[0], $library[1], $every_page) === FALSE) {
4691
      $success = FALSE;
4692
      // Exit if the dependency is missing.
4693
      if ($dependency_check) {
4694
        return $success;
4695
      }
4696
    }
4697
  }
4698
  unset($elements['#attached']['library']);
4699

    
4700
  // Add both the JavaScript and the CSS.
4701
  // The parameters for drupal_add_js() and drupal_add_css() require special
4702
  // handling.
4703
  foreach (array('js', 'css') as $type) {
4704
    foreach ($elements['#attached'][$type] as $data => $options) {
4705
      // If the value is not an array, it's a filename and passed as first
4706
      // (and only) argument.
4707
      if (!is_array($options)) {
4708
        $data = $options;
4709
        $options = NULL;
4710
      }
4711
      // In some cases, the first parameter ($data) is an array. Arrays can't be
4712
      // passed as keys in PHP, so we have to get $data from the value array.
4713
      if (is_numeric($data)) {
4714
        $data = $options['data'];
4715
        unset($options['data']);
4716
      }
4717
      // Apply the default group if it isn't explicitly given.
4718
      if (!isset($options['group'])) {
4719
        $options['group'] = $group;
4720
      }
4721
      // Set the every_page flag if one was passed.
4722
      if (isset($every_page)) {
4723
        $options['every_page'] = $every_page;
4724
      }
4725
      call_user_func('drupal_add_' . $type, $data, $options);
4726
    }
4727
    unset($elements['#attached'][$type]);
4728
  }
4729

    
4730
  // Add additional types of attachments specified in the render() structure.
4731
  // Libraries, JavaScript and CSS have been added already, as they require
4732
  // special handling.
4733
  foreach ($elements['#attached'] as $callback => $options) {
4734
    if (function_exists($callback)) {
4735
      foreach ($elements['#attached'][$callback] as $args) {
4736
        call_user_func_array($callback, $args);
4737
      }
4738
    }
4739
  }
4740

    
4741
  return $success;
4742
}
4743

    
4744
/**
4745
 * Adds JavaScript to change the state of an element based on another element.
4746
 *
4747
 * A "state" means a certain property on a DOM element, such as "visible" or
4748
 * "checked". A state can be applied to an element, depending on the state of
4749
 * another element on the page. In general, states depend on HTML attributes and
4750
 * DOM element properties, which change due to user interaction.
4751
 *
4752
 * Since states are driven by JavaScript only, it is important to understand
4753
 * that all states are applied on presentation only, none of the states force
4754
 * any server-side logic, and that they will not be applied for site visitors
4755
 * without JavaScript support. All modules implementing states have to make
4756
 * sure that the intended logic also works without JavaScript being enabled.
4757
 *
4758
 * #states is an associative array in the form of:
4759
 * @code
4760
 * array(
4761
 *   STATE1 => CONDITIONS_ARRAY1,
4762
 *   STATE2 => CONDITIONS_ARRAY2,
4763
 *   ...
4764
 * )
4765
 * @endcode
4766
 * Each key is the name of a state to apply to the element, such as 'visible'.
4767
 * Each value is a list of conditions that denote when the state should be
4768
 * applied.
4769
 *
4770
 * Multiple different states may be specified to act on complex conditions:
4771
 * @code
4772
 * array(
4773
 *   'visible' => CONDITIONS,
4774
 *   'checked' => OTHER_CONDITIONS,
4775
 * )
4776
 * @endcode
4777
 *
4778
 * Every condition is a key/value pair, whose key is a jQuery selector that
4779
 * denotes another element on the page, and whose value is an array of
4780
 * conditions, which must bet met on that element:
4781
 * @code
4782
 * array(
4783
 *   'visible' => array(
4784
 *     JQUERY_SELECTOR => REMOTE_CONDITIONS,
4785
 *     JQUERY_SELECTOR => REMOTE_CONDITIONS,
4786
 *     ...
4787
 *   ),
4788
 * )
4789
 * @endcode
4790
 * All conditions must be met for the state to be applied.
4791
 *
4792
 * Each remote condition is a key/value pair specifying conditions on the other
4793
 * element that need to be met to apply the state to the element:
4794
 * @code
4795
 * array(
4796
 *   'visible' => array(
4797
 *     ':input[name="remote_checkbox"]' => array('checked' => TRUE),
4798
 *   ),
4799
 * )
4800
 * @endcode
4801
 *
4802
 * For example, to show a textfield only when a checkbox is checked:
4803
 * @code
4804
 * $form['toggle_me'] = array(
4805
 *   '#type' => 'checkbox',
4806
 *   '#title' => t('Tick this box to type'),
4807
 * );
4808
 * $form['settings'] = array(
4809
 *   '#type' => 'textfield',
4810
 *   '#states' => array(
4811
 *     // Only show this field when the 'toggle_me' checkbox is enabled.
4812
 *     'visible' => array(
4813
 *       ':input[name="toggle_me"]' => array('checked' => TRUE),
4814
 *     ),
4815
 *   ),
4816
 * );
4817
 * @endcode
4818
 *
4819
 * The following states may be applied to an element:
4820
 * - enabled
4821
 * - disabled
4822
 * - required
4823
 * - optional
4824
 * - visible
4825
 * - invisible
4826
 * - checked
4827
 * - unchecked
4828
 * - expanded
4829
 * - collapsed
4830
 *
4831
 * The following states may be used in remote conditions:
4832
 * - empty
4833
 * - filled
4834
 * - checked
4835
 * - unchecked
4836
 * - expanded
4837
 * - collapsed
4838
 * - value
4839
 *
4840
 * The following states exist for both elements and remote conditions, but are
4841
 * not fully implemented and may not change anything on the element:
4842
 * - relevant
4843
 * - irrelevant
4844
 * - valid
4845
 * - invalid
4846
 * - touched
4847
 * - untouched
4848
 * - readwrite
4849
 * - readonly
4850
 *
4851
 * When referencing select lists and radio buttons in remote conditions, a
4852
 * 'value' condition must be used:
4853
 * @code
4854
 *   '#states' => array(
4855
 *     // Show the settings if 'bar' has been selected for 'foo'.
4856
 *     'visible' => array(
4857
 *       ':input[name="foo"]' => array('value' => 'bar'),
4858
 *     ),
4859
 *   ),
4860
 * @endcode
4861
 *
4862
 * @param $elements
4863
 *   A renderable array element having a #states property as described above.
4864
 *
4865
 * @see form_example_states_form()
4866
 */
4867
function drupal_process_states(&$elements) {
4868
  $elements['#attached']['library'][] = array('system', 'drupal.states');
4869
  $elements['#attached']['js'][] = array(
4870
    'type' => 'setting',
4871
    'data' => array('states' => array('#' . $elements['#id'] => $elements['#states'])),
4872
  );
4873
}
4874

    
4875
/**
4876
 * Adds multiple JavaScript or CSS files at the same time.
4877
 *
4878
 * A library defines a set of JavaScript and/or CSS files, optionally using
4879
 * settings, and optionally requiring another library. For example, a library
4880
 * can be a jQuery plugin, a JavaScript framework, or a CSS framework. This
4881
 * function allows modules to load a library defined/shipped by itself or a
4882
 * depending module, without having to add all files of the library separately.
4883
 * Each library is only loaded once.
4884
 *
4885
 * @param $module
4886
 *   The name of the module that registered the library.
4887
 * @param $name
4888
 *   The name of the library to add.
4889
 * @param $every_page
4890
 *   Set to TRUE if this library is added to every page on the site. Only items
4891
 *   with the every_page flag set to TRUE can participate in aggregation.
4892
 *
4893
 * @return
4894
 *   TRUE if the library was successfully added; FALSE if the library or one of
4895
 *   its dependencies could not be added.
4896
 *
4897
 * @see drupal_get_library()
4898
 * @see hook_library()
4899
 * @see hook_library_alter()
4900
 */
4901
function drupal_add_library($module, $name, $every_page = NULL) {
4902
  $added = &drupal_static(__FUNCTION__, array());
4903

    
4904
  // Only process the library if it exists and it was not added already.
4905
  if (!isset($added[$module][$name])) {
4906
    if ($library = drupal_get_library($module, $name)) {
4907
      // Add all components within the library.
4908
      $elements['#attached'] = array(
4909
        'library' => $library['dependencies'],
4910
        'js' => $library['js'],
4911
        'css' => $library['css'],
4912
      );
4913
      $added[$module][$name] = drupal_process_attached($elements, JS_LIBRARY, TRUE, $every_page);
4914
    }
4915
    else {
4916
      // Requested library does not exist.
4917
      $added[$module][$name] = FALSE;
4918
    }
4919
  }
4920

    
4921
  return $added[$module][$name];
4922
}
4923

    
4924
/**
4925
 * Retrieves information for a JavaScript/CSS library.
4926
 *
4927
 * Library information is statically cached. Libraries are keyed by module for
4928
 * several reasons:
4929
 * - Libraries are not unique. Multiple modules might ship with the same library
4930
 *   in a different version or variant. This registry cannot (and does not
4931
 *   attempt to) prevent library conflicts.
4932
 * - Modules implementing and thereby depending on a library that is registered
4933
 *   by another module can only rely on that module's library.
4934
 * - Two (or more) modules can still register the same library and use it
4935
 *   without conflicts in case the libraries are loaded on certain pages only.
4936
 *
4937
 * @param $module
4938
 *   The name of a module that registered a library.
4939
 * @param $name
4940
 *   (optional) The name of a registered library to retrieve. By default, all
4941
 *   libraries registered by $module are returned.
4942
 *
4943
 * @return
4944
 *   The definition of the requested library, if $name was passed and it exists,
4945
 *   or FALSE if it does not exist. If no $name was passed, an associative array
4946
 *   of libraries registered by $module is returned (which may be empty).
4947
 *
4948
 * @see drupal_add_library()
4949
 * @see hook_library()
4950
 * @see hook_library_alter()
4951
 *
4952
 * @todo The purpose of drupal_get_*() is completely different to other page
4953
 *   requisite API functions; find and use a different name.
4954
 */
4955
function drupal_get_library($module, $name = NULL) {
4956
  $libraries = &drupal_static(__FUNCTION__, array());
4957

    
4958
  if (!isset($libraries[$module])) {
4959
    // Retrieve all libraries associated with the module.
4960
    $module_libraries = module_invoke($module, 'library');
4961
    if (empty($module_libraries)) {
4962
      $module_libraries = array();
4963
    }
4964
    // Allow modules to alter the module's registered libraries.
4965
    drupal_alter('library', $module_libraries, $module);
4966

    
4967
    foreach ($module_libraries as $key => $data) {
4968
      if (is_array($data)) {
4969
        // Add default elements to allow for easier processing.
4970
        $module_libraries[$key] += array('dependencies' => array(), 'js' => array(), 'css' => array());
4971
        foreach ($module_libraries[$key]['js'] as $file => $options) {
4972
          $module_libraries[$key]['js'][$file]['version'] = $module_libraries[$key]['version'];
4973
        }
4974
      }
4975
    }
4976
    $libraries[$module] = $module_libraries;
4977
  }
4978
  if (isset($name)) {
4979
    if (!isset($libraries[$module][$name])) {
4980
      $libraries[$module][$name] = FALSE;
4981
    }
4982
    return $libraries[$module][$name];
4983
  }
4984
  return $libraries[$module];
4985
}
4986

    
4987
/**
4988
 * Assists in adding the tableDrag JavaScript behavior to a themed table.
4989
 *
4990
 * Draggable tables should be used wherever an outline or list of sortable items
4991
 * needs to be arranged by an end-user. Draggable tables are very flexible and
4992
 * can manipulate the value of form elements placed within individual columns.
4993
 *
4994
 * To set up a table to use drag and drop in place of weight select-lists or in
4995
 * place of a form that contains parent relationships, the form must be themed
4996
 * into a table. The table must have an ID attribute set. If using
4997
 * theme_table(), the ID may be set as follows:
4998
 * @code
4999
 * $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'my-module-table')));
5000
 * return $output;
5001
 * @endcode
5002
 *
5003
 * In the theme function for the form, a special class must be added to each
5004
 * form element within the same column, "grouping" them together.
5005
 *
5006
 * In a situation where a single weight column is being sorted in the table, the
5007
 * classes could be added like this (in the theme function):
5008
 * @code
5009
 * $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
5010
 * @endcode
5011
 *
5012
 * Each row of the table must also have a class of "draggable" in order to
5013
 * enable the drag handles:
5014
 * @code
5015
 * $row = array(...);
5016
 * $rows[] = array(
5017
 *   'data' => $row,
5018
 *   'class' => array('draggable'),
5019
 * );
5020
 * @endcode
5021
 *
5022
 * When tree relationships are present, the two additional classes
5023
 * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
5024
 * - Rows with the 'tabledrag-leaf' class cannot have child rows.
5025
 * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
5026
 *
5027
 * Calling drupal_add_tabledrag() would then be written as such:
5028
 * @code
5029
 * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
5030
 * @endcode
5031
 *
5032
 * In a more complex case where there are several groups in one column (such as
5033
 * the block regions on the admin/structure/block page), a separate subgroup
5034
 * class must also be added to differentiate the groups.
5035
 * @code
5036
 * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
5037
 * @endcode
5038
 *
5039
 * $group is still 'my-element-weight', and the additional $subgroup variable
5040
 * will be passed in as 'my-elements-weight-' . $region. This also means that
5041
 * you'll need to call drupal_add_tabledrag() once for every region added.
5042
 *
5043
 * @code
5044
 * foreach ($regions as $region) {
5045
 *   drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight', 'my-elements-weight-' . $region);
5046
 * }
5047
 * @endcode
5048
 *
5049
 * In a situation where tree relationships are present, adding multiple
5050
 * subgroups is not necessary, because the table will contain indentations that
5051
 * provide enough information about the sibling and parent relationships. See
5052
 * theme_menu_overview_form() for an example creating a table containing parent
5053
 * relationships.
5054
 *
5055
 * Note that this function should be called from the theme layer, such as in a
5056
 * .tpl.php file, theme_ function, or in a template_preprocess function, not in
5057
 * a form declaration. Though the same JavaScript could be added to the page
5058
 * using drupal_add_js() directly, this function helps keep template files
5059
 * clean and readable. It also prevents tabledrag.js from being added twice
5060
 * accidentally.
5061
 *
5062
 * @param $table_id
5063
 *   String containing the target table's id attribute. If the table does not
5064
 *   have an id, one will need to be set, such as <table id="my-module-table">.
5065
 * @param $action
5066
 *   String describing the action to be done on the form item. Either 'match'
5067
 *   'depth', or 'order'. Match is typically used for parent relationships.
5068
 *   Order is typically used to set weights on other form elements with the same
5069
 *   group. Depth updates the target element with the current indentation.
5070
 * @param $relationship
5071
 *   String describing where the $action variable should be performed. Either
5072
 *   'parent', 'sibling', 'group', or 'self'. Parent will only look for fields
5073
 *   up the tree. Sibling will look for fields in the same group in rows above
5074
 *   and below it. Self affects the dragged row itself. Group affects the
5075
 *   dragged row, plus any children below it (the entire dragged group).
5076
 * @param $group
5077
 *   A class name applied on all related form elements for this action.
5078
 * @param $subgroup
5079
 *   (optional) If the group has several subgroups within it, this string should
5080
 *   contain the class name identifying fields in the same subgroup.
5081
 * @param $source
5082
 *   (optional) If the $action is 'match', this string should contain the class
5083
 *   name identifying what field will be used as the source value when matching
5084
 *   the value in $subgroup.
5085
 * @param $hidden
5086
 *   (optional) The column containing the field elements may be entirely hidden
5087
 *   from view dynamically when the JavaScript is loaded. Set to FALSE if the
5088
 *   column should not be hidden.
5089
 * @param $limit
5090
 *   (optional) Limit the maximum amount of parenting in this table.
5091
 * @see block-admin-display-form.tpl.php
5092
 * @see theme_menu_overview_form()
5093
 */
5094
function drupal_add_tabledrag($table_id, $action, $relationship, $group, $subgroup = NULL, $source = NULL, $hidden = TRUE, $limit = 0) {
5095
  $js_added = &drupal_static(__FUNCTION__, FALSE);
5096
  if (!$js_added) {
5097
    // Add the table drag JavaScript to the page before the module JavaScript
5098
    // to ensure that table drag behaviors are registered before any module
5099
    // uses it.
5100
    drupal_add_library('system', 'jquery.cookie');
5101
    drupal_add_js('misc/tabledrag.js', array('weight' => -1));
5102
    $js_added = TRUE;
5103
  }
5104

    
5105
  // If a subgroup or source isn't set, assume it is the same as the group.
5106
  $target = isset($subgroup) ? $subgroup : $group;
5107
  $source = isset($source) ? $source : $target;
5108
  $settings['tableDrag'][$table_id][$group][] = array(
5109
    'target' => $target,
5110
    'source' => $source,
5111
    'relationship' => $relationship,
5112
    'action' => $action,
5113
    'hidden' => $hidden,
5114
    'limit' => $limit,
5115
  );
5116
  drupal_add_js($settings, 'setting');
5117
}
5118

    
5119
/**
5120
 * Aggregates JavaScript files into a cache file in the files directory.
5121
 *
5122
 * The file name for the JavaScript cache file is generated from the hash of
5123
 * the aggregated contents of the files in $files. This forces proxies and
5124
 * browsers to download new JavaScript when the JavaScript changes.
5125
 *
5126
 * The cache file name is retrieved on a page load via a lookup variable that
5127
 * contains an associative array. The array key is the hash of the names in
5128
 * $files while the value is the cache file name. The cache file is generated
5129
 * in two cases. First, if there is no file name value for the key, which will
5130
 * happen if a new file name has been added to $files or after the lookup
5131
 * variable is emptied to force a rebuild of the cache. Second, the cache file
5132
 * is generated if it is missing on disk. Old cache files are not deleted
5133
 * immediately when the lookup variable is emptied, but are deleted after a set
5134
 * period by drupal_delete_file_if_stale(). This ensures that files referenced
5135
 * by a cached page will still be available.
5136
 *
5137
 * @param $files
5138
 *   An array of JavaScript files to aggregate and compress into one file.
5139
 *
5140
 * @return
5141
 *   The URI of the cache file, or FALSE if the file could not be saved.
5142
 */
5143
function drupal_build_js_cache($files) {
5144
  $contents = '';
5145
  $uri = '';
5146
  $map = variable_get('drupal_js_cache_files', array());
5147
  // Create a new array so that only the file names are used to create the hash.
5148
  // This prevents new aggregates from being created unnecessarily.
5149
  $js_data = array();
5150
  foreach ($files as $file) {
5151
    $js_data[] = $file['data'];
5152
  }
5153
  $key = hash('sha256', serialize($js_data));
5154
  if (isset($map[$key])) {
5155
    $uri = $map[$key];
5156
  }
5157

    
5158
  if (empty($uri) || !file_exists($uri)) {
5159
    // Build aggregate JS file.
5160
    foreach ($files as $path => $info) {
5161
      if ($info['preprocess']) {
5162
        // Append a ';' and a newline after each JS file to prevent them from running together.
5163
        $contents .= file_get_contents($path) . ";\n";
5164
      }
5165
    }
5166
    // Prefix filename to prevent blocking by firewalls which reject files
5167
    // starting with "ad*".
5168
    $filename = 'js_' . drupal_hash_base64($contents) . '.js';
5169
    // Create the js/ within the files folder.
5170
    $jspath = 'public://js';
5171
    $uri = $jspath . '/' . $filename;
5172
    // Create the JS file.
5173
    file_prepare_directory($jspath, FILE_CREATE_DIRECTORY);
5174
    if (!file_exists($uri) && !file_unmanaged_save_data($contents, $uri, FILE_EXISTS_REPLACE)) {
5175
      return FALSE;
5176
    }
5177
    // If JS gzip compression is enabled, clean URLs are enabled (which means
5178
    // that rewrite rules are working) and the zlib extension is available then
5179
    // create a gzipped version of this file. This file is served conditionally
5180
    // to browsers that accept gzip using .htaccess rules.
5181
    if (variable_get('js_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
5182
      if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($contents, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
5183
        return FALSE;
5184
      }
5185
    }
5186
    $map[$key] = $uri;
5187
    variable_set('drupal_js_cache_files', $map);
5188
  }
5189
  return $uri;
5190
}
5191

    
5192
/**
5193
 * Deletes old cached JavaScript files and variables.
5194
 */
5195
function drupal_clear_js_cache() {
5196
  variable_del('javascript_parsed');
5197
  variable_del('drupal_js_cache_files');
5198
  file_scan_directory('public://js', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
5199
}
5200

    
5201
/**
5202
 * Converts a PHP variable into its JavaScript equivalent.
5203
 *
5204
 * We use HTML-safe strings, with several characters escaped.
5205
 *
5206
 * @see drupal_json_decode()
5207
 * @see drupal_json_encode_helper()
5208
 * @ingroup php_wrappers
5209
 */
5210
function drupal_json_encode($var) {
5211
  // The PHP version cannot change within a request.
5212
  static $php530;
5213

    
5214
  if (!isset($php530)) {
5215
    $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
5216
  }
5217

    
5218
  if ($php530) {
5219
    // Encode <, >, ', &, and " using the json_encode() options parameter.
5220
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
5221
  }
5222

    
5223
  // json_encode() escapes <, >, ', &, and " using its options parameter, but
5224
  // does not support this parameter prior to PHP 5.3.0.  Use a helper instead.
5225
  include_once DRUPAL_ROOT . '/includes/json-encode.inc';
5226
  return drupal_json_encode_helper($var);
5227
}
5228

    
5229
/**
5230
 * Converts an HTML-safe JSON string into its PHP equivalent.
5231
 *
5232
 * @see drupal_json_encode()
5233
 * @ingroup php_wrappers
5234
 */
5235
function drupal_json_decode($var) {
5236
  return json_decode($var, TRUE);
5237
}
5238

    
5239
/**
5240
 * Returns data in JSON format.
5241
 *
5242
 * This function should be used for JavaScript callback functions returning
5243
 * data in JSON format. It sets the header for JavaScript output.
5244
 *
5245
 * @param $var
5246
 *   (optional) If set, the variable will be converted to JSON and output.
5247
 */
5248
function drupal_json_output($var = NULL) {
5249
  // We are returning JSON, so tell the browser.
5250
  drupal_add_http_header('Content-Type', 'application/json');
5251

    
5252
  if (isset($var)) {
5253
    echo drupal_json_encode($var);
5254
  }
5255
}
5256

    
5257
/**
5258
 * Ensures the private key variable used to generate tokens is set.
5259
 *
5260
 * @return
5261
 *   The private key.
5262
 */
5263
function drupal_get_private_key() {
5264
  if (!($key = variable_get('drupal_private_key', 0))) {
5265
    $key = drupal_random_key();
5266
    variable_set('drupal_private_key', $key);
5267
  }
5268
  return $key;
5269
}
5270

    
5271
/**
5272
 * Generates a token based on $value, the user session, and the private key.
5273
 *
5274
 * @param $value
5275
 *   An additional value to base the token on.
5276
 *
5277
 * The generated token is based on the session ID of the current user. Normally,
5278
 * anonymous users do not have a session, so the generated token will be
5279
 * different on every page request. To generate a token for users without a
5280
 * session, manually start a session prior to calling this function.
5281
 *
5282
 * @return string
5283
 *   A 43-character URL-safe token for validation, based on the user session ID,
5284
 *   the hash salt provided from drupal_get_hash_salt(), and the
5285
 *   'drupal_private_key' configuration variable.
5286
 *
5287
 * @see drupal_get_hash_salt()
5288
 */
5289
function drupal_get_token($value = '') {
5290
  return drupal_hmac_base64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());
5291
}
5292

    
5293
/**
5294
 * Validates a token based on $value, the user session, and the private key.
5295
 *
5296
 * @param $token
5297
 *   The token to be validated.
5298
 * @param $value
5299
 *   An additional value to base the token on.
5300
 * @param $skip_anonymous
5301
 *   Set to true to skip token validation for anonymous users.
5302
 *
5303
 * @return
5304
 *   True for a valid token, false for an invalid token. When $skip_anonymous
5305
 *   is true, the return value will always be true for anonymous users.
5306
 */
5307
function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
5308
  global $user;
5309
  return (($skip_anonymous && $user->uid == 0) || ($token === drupal_get_token($value)));
5310
}
5311

    
5312
function _drupal_bootstrap_full() {
5313
  static $called = FALSE;
5314

    
5315
  if ($called) {
5316
    return;
5317
  }
5318
  $called = TRUE;
5319
  require_once DRUPAL_ROOT . '/' . variable_get('path_inc', 'includes/path.inc');
5320
  require_once DRUPAL_ROOT . '/includes/theme.inc';
5321
  require_once DRUPAL_ROOT . '/includes/pager.inc';
5322
  require_once DRUPAL_ROOT . '/' . variable_get('menu_inc', 'includes/menu.inc');
5323
  require_once DRUPAL_ROOT . '/includes/tablesort.inc';
5324
  require_once DRUPAL_ROOT . '/includes/file.inc';
5325
  require_once DRUPAL_ROOT . '/includes/unicode.inc';
5326
  require_once DRUPAL_ROOT . '/includes/image.inc';
5327
  require_once DRUPAL_ROOT . '/includes/form.inc';
5328
  require_once DRUPAL_ROOT . '/includes/mail.inc';
5329
  require_once DRUPAL_ROOT . '/includes/actions.inc';
5330
  require_once DRUPAL_ROOT . '/includes/ajax.inc';
5331
  require_once DRUPAL_ROOT . '/includes/token.inc';
5332
  require_once DRUPAL_ROOT . '/includes/errors.inc';
5333

    
5334
  // Detect string handling method
5335
  unicode_check();
5336
  // Undo magic quotes
5337
  fix_gpc_magic();
5338
  // Load all enabled modules
5339
  module_load_all();
5340
  // Reset drupal_alter() and module_implements() static caches as these
5341
  // include implementations for vital modules only when called early on
5342
  // in the bootstrap.
5343
  drupal_static_reset('drupal_alter');
5344
  drupal_static_reset('module_implements');
5345
  // Make sure all stream wrappers are registered.
5346
  file_get_stream_wrappers();
5347
  // Ensure mt_rand is reseeded, to prevent random values from one page load
5348
  // being exploited to predict random values in subsequent page loads.
5349
  $seed = unpack("L", drupal_random_bytes(4));
5350
  mt_srand($seed[1]);
5351

    
5352
  $test_info = &$GLOBALS['drupal_test_info'];
5353
  if (!empty($test_info['in_child_site'])) {
5354
    // Running inside the simpletest child site, log fatal errors to test
5355
    // specific file directory.
5356
    ini_set('log_errors', 1);
5357
    ini_set('error_log', 'public://error.log');
5358
  }
5359

    
5360
  // Initialize $_GET['q'] prior to invoking hook_init().
5361
  drupal_path_initialize();
5362

    
5363
  // Let all modules take action before the menu system handles the request.
5364
  // We do not want this while running update.php.
5365
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
5366
    // Prior to invoking hook_init(), initialize the theme (potentially a custom
5367
    // one for this page), so that:
5368
    // - Modules with hook_init() implementations that call theme() or
5369
    //   theme_get_registry() don't initialize the incorrect theme.
5370
    // - The theme can have hook_*_alter() implementations affect page building
5371
    //   (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
5372
    //   ahead of when rendering starts.
5373
    menu_set_custom_theme();
5374
    drupal_theme_initialize();
5375
    module_invoke_all('init');
5376
  }
5377
}
5378

    
5379
/**
5380
 * Stores the current page in the cache.
5381
 *
5382
 * If page_compression is enabled, a gzipped version of the page is stored in
5383
 * the cache to avoid compressing the output on each request. The cache entry
5384
 * is unzipped in the relatively rare event that the page is requested by a
5385
 * client without gzip support.
5386
 *
5387
 * Page compression requires the PHP zlib extension
5388
 * (http://php.net/manual/ref.zlib.php).
5389
 *
5390
 * @see drupal_page_header()
5391
 */
5392
function drupal_page_set_cache() {
5393
  global $base_root;
5394

    
5395
  if (drupal_page_is_cacheable()) {
5396

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

    
5400
    $cache = (object) array(
5401
      'cid' => $base_root . request_uri(),
5402
      'data' => array(
5403
        'path' => $_GET['q'],
5404
        'body' => ob_get_clean(),
5405
        'title' => drupal_get_title(),
5406
        'headers' => array(),
5407
        // We need to store whether page was compressed or not,
5408
        // because by the time it is read, the configuration might change.
5409
        'page_compressed' => $page_compressed,
5410
      ),
5411
      'expire' => CACHE_TEMPORARY,
5412
      'created' => REQUEST_TIME,
5413
    );
5414

    
5415
    // Restore preferred header names based on the lower-case names returned
5416
    // by drupal_get_http_header().
5417
    $header_names = _drupal_set_preferred_header_name();
5418
    foreach (drupal_get_http_header() as $name_lower => $value) {
5419
      $cache->data['headers'][$header_names[$name_lower]] = $value;
5420
      if ($name_lower == 'expires') {
5421
        // Use the actual timestamp from an Expires header if available.
5422
        $cache->expire = strtotime($value);
5423
      }
5424
    }
5425

    
5426
    if ($cache->data['body']) {
5427
      if ($page_compressed) {
5428
        $cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
5429
      }
5430
      cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire);
5431
    }
5432
    return $cache;
5433
  }
5434
}
5435

    
5436
/**
5437
 * Executes a cron run when called.
5438
 *
5439
 * Do not call this function from a test. Use $this->cronRun() instead.
5440
 *
5441
 * @return bool
5442
 *   TRUE if cron ran successfully and FALSE if cron is already running.
5443
 */
5444
function drupal_cron_run() {
5445
  // Allow execution to continue even if the request gets canceled.
5446
  @ignore_user_abort(TRUE);
5447

    
5448
  // Prevent session information from being saved while cron is running.
5449
  $original_session_saving = drupal_save_session();
5450
  drupal_save_session(FALSE);
5451

    
5452
  // Force the current user to anonymous to ensure consistent permissions on
5453
  // cron runs.
5454
  $original_user = $GLOBALS['user'];
5455
  $GLOBALS['user'] = drupal_anonymous_user();
5456

    
5457
  // Try to allocate enough time to run all the hook_cron implementations.
5458
  drupal_set_time_limit(240);
5459

    
5460
  $return = FALSE;
5461
  // Grab the defined cron queues.
5462
  $queues = module_invoke_all('cron_queue_info');
5463
  drupal_alter('cron_queue_info', $queues);
5464

    
5465
  // Try to acquire cron lock.
5466
  if (!lock_acquire('cron', 240.0)) {
5467
    // Cron is still running normally.
5468
    watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
5469
  }
5470
  else {
5471
    // Make sure every queue exists. There is no harm in trying to recreate an
5472
    // existing queue.
5473
    foreach ($queues as $queue_name => $info) {
5474
      DrupalQueue::get($queue_name)->createQueue();
5475
    }
5476

    
5477
    // Iterate through the modules calling their cron handlers (if any):
5478
    foreach (module_implements('cron') as $module) {
5479
      // Do not let an exception thrown by one module disturb another.
5480
      try {
5481
        module_invoke($module, 'cron');
5482
      }
5483
      catch (Exception $e) {
5484
        watchdog_exception('cron', $e);
5485
      }
5486
    }
5487

    
5488
    // Record cron time.
5489
    variable_set('cron_last', REQUEST_TIME);
5490
    watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
5491

    
5492
    // Release cron lock.
5493
    lock_release('cron');
5494

    
5495
    // Return TRUE so other functions can check if it did run successfully
5496
    $return = TRUE;
5497
  }
5498

    
5499
  foreach ($queues as $queue_name => $info) {
5500
    if (!empty($info['skip on cron'])) {
5501
      // Do not run if queue wants to skip.
5502
      continue;
5503
    }
5504
    $callback = $info['worker callback'];
5505
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
5506
    $queue = DrupalQueue::get($queue_name);
5507
    while (time() < $end && ($item = $queue->claimItem())) {
5508
      try {
5509
        call_user_func($callback, $item->data);
5510
        $queue->deleteItem($item);
5511
      }
5512
      catch (Exception $e) {
5513
        // In case of exception log it and leave the item in the queue
5514
        // to be processed again later.
5515
        watchdog_exception('cron', $e);
5516
      }
5517
    }
5518
  }
5519
  // Restore the user.
5520
  $GLOBALS['user'] = $original_user;
5521
  drupal_save_session($original_session_saving);
5522

    
5523
  return $return;
5524
}
5525

    
5526
/**
5527
 * DEPRECATED: Shutdown function: Performs cron cleanup.
5528
 *
5529
 * This function is deprecated because the 'cron_semaphore' variable it
5530
 * references no longer exists. It is therefore no longer used as a shutdown
5531
 * function by Drupal core.
5532
 *
5533
 * @deprecated
5534
 */
5535
function drupal_cron_cleanup() {
5536
  // See if the semaphore is still locked.
5537
  if (variable_get('cron_semaphore', FALSE)) {
5538
    watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);
5539

    
5540
    // Release cron semaphore.
5541
    variable_del('cron_semaphore');
5542
  }
5543
}
5544

    
5545
/**
5546
 * Returns information about system object files (modules, themes, etc.).
5547
 *
5548
 * This function is used to find all or some system object files (module files,
5549
 * theme files, etc.) that exist on the site. It searches in several locations,
5550
 * depending on what type of object you are looking for. For instance, if you
5551
 * are looking for modules and call:
5552
 * @code
5553
 * drupal_system_listing("/\.module$/", "modules", 'name', 0);
5554
 * @endcode
5555
 * this function will search the site-wide modules directory (i.e., /modules/),
5556
 * your installation profile's directory (i.e.,
5557
 * /profiles/your_site_profile/modules/), the all-sites directory (i.e.,
5558
 * /sites/all/modules/), and your site-specific directory (i.e.,
5559
 * /sites/your_site_dir/modules/), in that order, and return information about
5560
 * all of the files ending in .module in those directories.
5561
 *
5562
 * The information is returned in an associative array, which can be keyed on
5563
 * the file name ($key = 'filename'), the file name without the extension ($key
5564
 * = 'name'), or the full file stream URI ($key = 'uri'). If you use a key of
5565
 * 'filename' or 'name', files found later in the search will take precedence
5566
 * over files found earlier (unless they belong to a module or theme not
5567
 * compatible with Drupal core); if you choose a key of 'uri', you will get all
5568
 * files found.
5569
 *
5570
 * @param string $mask
5571
 *   The preg_match() regular expression for the files to find.
5572
 * @param string $directory
5573
 *   The subdirectory name in which the files are found. For example,
5574
 *   'modules' will search in sub-directories of the top-level /modules
5575
 *   directory, sub-directories of /sites/all/modules/, etc.
5576
 * @param string $key
5577
 *   The key to be used for the associative array returned. Possible values are
5578
 *   'uri', for the file's URI; 'filename', for the basename of the file; and
5579
 *   'name' for the name of the file without the extension. If you choose 'name'
5580
 *   or 'filename', only the highest-precedence file will be returned.
5581
 * @param int $min_depth
5582
 *   Minimum depth of directories to return files from, relative to each
5583
 *   directory searched. For instance, a minimum depth of 2 would find modules
5584
 *   inside /modules/node/tests, but not modules directly in /modules/node.
5585
 *
5586
 * @return array
5587
 *   An associative array of file objects, keyed on the chosen key. Each element
5588
 *   in the array is an object containing file information, with properties:
5589
 *   - 'uri': Full URI of the file.
5590
 *   - 'filename': File name.
5591
 *   - 'name': Name of file without the extension.
5592
 */
5593
function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
5594
  $config = conf_path();
5595

    
5596
  $searchdir = array($directory);
5597
  $files = array();
5598

    
5599
  // The 'profiles' directory contains pristine collections of modules and
5600
  // themes as organized by a distribution. It is pristine in the same way
5601
  // that /modules is pristine for core; users should avoid changing anything
5602
  // there in favor of sites/all or sites/<domain> directories.
5603
  $profiles = array();
5604
  $profile = drupal_get_profile();
5605
  // For SimpleTest to be able to test modules packaged together with a
5606
  // distribution we need to include the profile of the parent site (in which
5607
  // test runs are triggered).
5608
  if (drupal_valid_test_ua()) {
5609
    $testing_profile = variable_get('simpletest_parent_profile', FALSE);
5610
    if ($testing_profile && $testing_profile != $profile) {
5611
      $profiles[] = $testing_profile;
5612
    }
5613
  }
5614
  // In case both profile directories contain the same extension, the actual
5615
  // profile always has precedence.
5616
  $profiles[] = $profile;
5617
  foreach ($profiles as $profile) {
5618
    if (file_exists("profiles/$profile/$directory")) {
5619
      $searchdir[] = "profiles/$profile/$directory";
5620
    }
5621
  }
5622

    
5623
  // Always search sites/all/* as well as the global directories.
5624
  $searchdir[] = 'sites/all/' . $directory;
5625

    
5626
  if (file_exists("$config/$directory")) {
5627
    $searchdir[] = "$config/$directory";
5628
  }
5629

    
5630
  // Get current list of items.
5631
  if (!function_exists('file_scan_directory')) {
5632
    require_once DRUPAL_ROOT . '/includes/file.inc';
5633
  }
5634
  foreach ($searchdir as $dir) {
5635
    $files_to_add = file_scan_directory($dir, $mask, array('key' => $key, 'min_depth' => $min_depth));
5636

    
5637
    // Duplicate files found in later search directories take precedence over
5638
    // earlier ones, so we want them to overwrite keys in our resulting
5639
    // $files array.
5640
    // The exception to this is if the later file is from a module or theme not
5641
    // compatible with Drupal core. This may occur during upgrades of Drupal
5642
    // core when new modules exist in core while older contrib modules with the
5643
    // same name exist in a directory such as sites/all/modules/.
5644
    foreach (array_intersect_key($files_to_add, $files) as $file_key => $file) {
5645
      // If it has no info file, then we just behave liberally and accept the
5646
      // new resource on the list for merging.
5647
      if (file_exists($info_file = dirname($file->uri) . '/' . $file->name . '.info')) {
5648
        // Get the .info file for the module or theme this file belongs to.
5649
        $info = drupal_parse_info_file($info_file);
5650

    
5651
        // If the module or theme is incompatible with Drupal core, remove it
5652
        // from the array for the current search directory, so it is not
5653
        // overwritten when merged with the $files array.
5654
        if (isset($info['core']) && $info['core'] != DRUPAL_CORE_COMPATIBILITY) {
5655
          unset($files_to_add[$file_key]);
5656
        }
5657
      }
5658
    }
5659
    $files = array_merge($files, $files_to_add);
5660
  }
5661

    
5662
  return $files;
5663
}
5664

    
5665
/**
5666
 * Sets the main page content value for later use.
5667
 *
5668
 * Given the nature of the Drupal page handling, this will be called once with
5669
 * a string or array. We store that and return it later as the block is being
5670
 * displayed.
5671
 *
5672
 * @param $content
5673
 *   A string or renderable array representing the body of the page.
5674
 *
5675
 * @return
5676
 *   If called without $content, a renderable array representing the body of
5677
 *   the page.
5678
 */
5679
function drupal_set_page_content($content = NULL) {
5680
  $content_block = &drupal_static(__FUNCTION__, NULL);
5681
  $main_content_display = &drupal_static('system_main_content_added', FALSE);
5682

    
5683
  if (!empty($content)) {
5684
    $content_block = (is_array($content) ? $content : array('main' => array('#markup' => $content)));
5685
  }
5686
  else {
5687
    // Indicate that the main content has been requested. We assume that
5688
    // the module requesting the content will be adding it to the page.
5689
    // A module can indicate that it does not handle the content by setting
5690
    // the static variable back to FALSE after calling this function.
5691
    $main_content_display = TRUE;
5692
    return $content_block;
5693
  }
5694
}
5695

    
5696
/**
5697
 * #pre_render callback to render #browsers into #prefix and #suffix.
5698
 *
5699
 * @param $elements
5700
 *   A render array with a '#browsers' property. The '#browsers' property can
5701
 *   contain any or all of the following keys:
5702
 *   - 'IE': If FALSE, the element is not rendered by Internet Explorer. If
5703
 *     TRUE, the element is rendered by Internet Explorer. Can also be a string
5704
 *     containing an expression for Internet Explorer to evaluate as part of a
5705
 *     conditional comment. For example, this can be set to 'lt IE 7' for the
5706
 *     element to be rendered in Internet Explorer 6, but not in Internet
5707
 *     Explorer 7 or higher. Defaults to TRUE.
5708
 *   - '!IE': If FALSE, the element is not rendered by browsers other than
5709
 *     Internet Explorer. If TRUE, the element is rendered by those browsers.
5710
 *     Defaults to TRUE.
5711
 *   Examples:
5712
 *   - To render an element in all browsers, '#browsers' can be left out or set
5713
 *     to array('IE' => TRUE, '!IE' => TRUE).
5714
 *   - To render an element in Internet Explorer only, '#browsers' can be set
5715
 *     to array('!IE' => FALSE).
5716
 *   - To render an element in Internet Explorer 6 only, '#browsers' can be set
5717
 *     to array('IE' => 'lt IE 7', '!IE' => FALSE).
5718
 *   - To render an element in Internet Explorer 8 and higher and in all other
5719
 *     browsers, '#browsers' can be set to array('IE' => 'gte IE 8').
5720
 *
5721
 * @return
5722
 *   The passed-in element with markup for conditional comments potentially
5723
 *   added to '#prefix' and '#suffix'.
5724
 */
5725
function drupal_pre_render_conditional_comments($elements) {
5726
  $browsers = isset($elements['#browsers']) ? $elements['#browsers'] : array();
5727
  $browsers += array(
5728
    'IE' => TRUE,
5729
    '!IE' => TRUE,
5730
  );
5731

    
5732
  // If rendering in all browsers, no need for conditional comments.
5733
  if ($browsers['IE'] === TRUE && $browsers['!IE']) {
5734
    return $elements;
5735
  }
5736

    
5737
  // Determine the conditional comment expression for Internet Explorer to
5738
  // evaluate.
5739
  if ($browsers['IE'] === TRUE) {
5740
    $expression = 'IE';
5741
  }
5742
  elseif ($browsers['IE'] === FALSE) {
5743
    $expression = '!IE';
5744
  }
5745
  else {
5746
    $expression = $browsers['IE'];
5747
  }
5748

    
5749
  // Wrap the element's potentially existing #prefix and #suffix properties with
5750
  // conditional comment markup. The conditional comment expression is evaluated
5751
  // by Internet Explorer only. To control the rendering by other browsers,
5752
  // either the "downlevel-hidden" or "downlevel-revealed" technique must be
5753
  // used. See http://en.wikipedia.org/wiki/Conditional_comment for details.
5754
  $elements += array(
5755
    '#prefix' => '',
5756
    '#suffix' => '',
5757
  );
5758
  if (!$browsers['!IE']) {
5759
    // "downlevel-hidden".
5760
    $elements['#prefix'] = "\n<!--[if $expression]>\n" . $elements['#prefix'];
5761
    $elements['#suffix'] .= "<![endif]-->\n";
5762
  }
5763
  else {
5764
    // "downlevel-revealed".
5765
    $elements['#prefix'] = "\n<!--[if $expression]><!-->\n" . $elements['#prefix'];
5766
    $elements['#suffix'] .= "<!--<![endif]-->\n";
5767
  }
5768

    
5769
  return $elements;
5770
}
5771

    
5772
/**
5773
 * #pre_render callback to render a link into #markup.
5774
 *
5775
 * Doing so during pre_render gives modules a chance to alter the link parts.
5776
 *
5777
 * @param $elements
5778
 *   A structured array whose keys form the arguments to l():
5779
 *   - #title: The link text to pass as argument to l().
5780
 *   - #href: The URL path component to pass as argument to l().
5781
 *   - #options: (optional) An array of options to pass to l().
5782
 *
5783
 * @return
5784
 *   The passed-in elements containing a rendered link in '#markup'.
5785
 */
5786
function drupal_pre_render_link($element) {
5787
  // By default, link options to pass to l() are normally set in #options.
5788
  $element += array('#options' => array());
5789
  // However, within the scope of renderable elements, #attributes is a valid
5790
  // way to specify attributes, too. Take them into account, but do not override
5791
  // attributes from #options.
5792
  if (isset($element['#attributes'])) {
5793
    $element['#options'] += array('attributes' => array());
5794
    $element['#options']['attributes'] += $element['#attributes'];
5795
  }
5796

    
5797
  // This #pre_render callback can be invoked from inside or outside of a Form
5798
  // API context, and depending on that, a HTML ID may be already set in
5799
  // different locations. #options should have precedence over Form API's #id.
5800
  // #attributes have been taken over into #options above already.
5801
  if (isset($element['#options']['attributes']['id'])) {
5802
    $element['#id'] = $element['#options']['attributes']['id'];
5803
  }
5804
  elseif (isset($element['#id'])) {
5805
    $element['#options']['attributes']['id'] = $element['#id'];
5806
  }
5807

    
5808
  // Conditionally invoke ajax_pre_render_element(), if #ajax is set.
5809
  if (isset($element['#ajax']) && !isset($element['#ajax_processed'])) {
5810
    // If no HTML ID was found above, automatically create one.
5811
    if (!isset($element['#id'])) {
5812
      $element['#id'] = $element['#options']['attributes']['id'] = drupal_html_id('ajax-link');
5813
    }
5814
    // If #ajax['path] was not specified, use the href as Ajax request URL.
5815
    if (!isset($element['#ajax']['path'])) {
5816
      $element['#ajax']['path'] = $element['#href'];
5817
      $element['#ajax']['options'] = $element['#options'];
5818
    }
5819
    $element = ajax_pre_render_element($element);
5820
  }
5821

    
5822
  $element['#markup'] = l($element['#title'], $element['#href'], $element['#options']);
5823
  return $element;
5824
}
5825

    
5826
/**
5827
 * #pre_render callback that collects child links into a single array.
5828
 *
5829
 * This function can be added as a pre_render callback for a renderable array,
5830
 * usually one which will be themed by theme_links(). It iterates through all
5831
 * unrendered children of the element, collects any #links properties it finds,
5832
 * merges them into the parent element's #links array, and prevents those
5833
 * children from being rendered separately.
5834
 *
5835
 * The purpose of this is to allow links to be logically grouped into related
5836
 * categories, so that each child group can be rendered as its own list of
5837
 * links if drupal_render() is called on it, but calling drupal_render() on the
5838
 * parent element will still produce a single list containing all the remaining
5839
 * links, regardless of what group they were in.
5840
 *
5841
 * A typical example comes from node links, which are stored in a renderable
5842
 * array similar to this:
5843
 * @code
5844
 * $node->content['links'] = array(
5845
 *   '#theme' => 'links__node',
5846
 *   '#pre_render' => array('drupal_pre_render_links'),
5847
 *   'comment' => array(
5848
 *     '#theme' => 'links__node__comment',
5849
 *     '#links' => array(
5850
 *       // An array of links associated with node comments, suitable for
5851
 *       // passing in to theme_links().
5852
 *     ),
5853
 *   ),
5854
 *   'statistics' => array(
5855
 *     '#theme' => 'links__node__statistics',
5856
 *     '#links' => array(
5857
 *       // An array of links associated with node statistics, suitable for
5858
 *       // passing in to theme_links().
5859
 *     ),
5860
 *   ),
5861
 *   'translation' => array(
5862
 *     '#theme' => 'links__node__translation',
5863
 *     '#links' => array(
5864
 *       // An array of links associated with node translation, suitable for
5865
 *       // passing in to theme_links().
5866
 *     ),
5867
 *   ),
5868
 * );
5869
 * @endcode
5870
 *
5871
 * In this example, the links are grouped by functionality, which can be
5872
 * helpful to themers who want to display certain kinds of links independently.
5873
 * For example, adding this code to node.tpl.php will result in the comment
5874
 * links being rendered as a single list:
5875
 * @code
5876
 * print render($content['links']['comment']);
5877
 * @endcode
5878
 *
5879
 * (where $node->content has been transformed into $content before handing
5880
 * control to the node.tpl.php template).
5881
 *
5882
 * The pre_render function defined here allows the above flexibility, but also
5883
 * allows the following code to be used to render all remaining links into a
5884
 * single list, regardless of their group:
5885
 * @code
5886
 * print render($content['links']);
5887
 * @endcode
5888
 *
5889
 * In the above example, this will result in the statistics and translation
5890
 * links being rendered together in a single list (but not the comment links,
5891
 * which were rendered previously on their own).
5892
 *
5893
 * Because of the way this function works, the individual properties of each
5894
 * group (for example, a group-specific #theme property such as
5895
 * 'links__node__comment' in the example above, or any other property such as
5896
 * #attributes or #pre_render that is attached to it) are only used when that
5897
 * group is rendered on its own. When the group is rendered together with other
5898
 * children, these child-specific properties are ignored, and only the overall
5899
 * properties of the parent are used.
5900
 */
5901
function drupal_pre_render_links($element) {
5902
  $element += array('#links' => array());
5903
  foreach (element_children($element) as $key) {
5904
    $child = &$element[$key];
5905
    // If the child has links which have not been printed yet and the user has
5906
    // access to it, merge its links in to the parent.
5907
    if (isset($child['#links']) && empty($child['#printed']) && (!isset($child['#access']) || $child['#access'])) {
5908
      $element['#links'] += $child['#links'];
5909
      // Mark the child as having been printed already (so that its links
5910
      // cannot be mistakenly rendered twice).
5911
      $child['#printed'] = TRUE;
5912
    }
5913
  }
5914
  return $element;
5915
}
5916

    
5917
/**
5918
 * #pre_render callback to append contents in #markup to #children.
5919
 *
5920
 * This needs to be a #pre_render callback, because eventually assigned
5921
 * #theme_wrappers will expect the element's rendered content in #children.
5922
 * Note that if also a #theme is defined for the element, then the result of
5923
 * the theme callback will override #children.
5924
 *
5925
 * @param $elements
5926
 *   A structured array using the #markup key.
5927
 *
5928
 * @return
5929
 *   The passed-in elements, but #markup appended to #children.
5930
 *
5931
 * @see drupal_render()
5932
 */
5933
function drupal_pre_render_markup($elements) {
5934
  $elements['#children'] = $elements['#markup'];
5935
  return $elements;
5936
}
5937

    
5938
/**
5939
 * Renders the page, including all theming.
5940
 *
5941
 * @param $page
5942
 *   A string or array representing the content of a page. The array consists of
5943
 *   the following keys:
5944
 *   - #type: Value is always 'page'. This pushes the theming through
5945
 *     page.tpl.php (required).
5946
 *   - #show_messages: Suppress drupal_get_message() items. Used by Batch
5947
 *     API (optional).
5948
 *
5949
 * @see hook_page_alter()
5950
 * @see element_info()
5951
 */
5952
function drupal_render_page($page) {
5953
  $main_content_display = &drupal_static('system_main_content_added', FALSE);
5954

    
5955
  // Allow menu callbacks to return strings or arbitrary arrays to render.
5956
  // If the array returned is not of #type page directly, we need to fill
5957
  // in the page with defaults.
5958
  if (is_string($page) || (is_array($page) && (!isset($page['#type']) || ($page['#type'] != 'page')))) {
5959
    drupal_set_page_content($page);
5960
    $page = element_info('page');
5961
  }
5962

    
5963
  // Modules can add elements to $page as needed in hook_page_build().
5964
  foreach (module_implements('page_build') as $module) {
5965
    $function = $module . '_page_build';
5966
    $function($page);
5967
  }
5968
  // Modules alter the $page as needed. Blocks are populated into regions like
5969
  // 'sidebar_first', 'footer', etc.
5970
  drupal_alter('page', $page);
5971

    
5972
  // If no module has taken care of the main content, add it to the page now.
5973
  // This allows the site to still be usable even if no modules that
5974
  // control page regions (for example, the Block module) are enabled.
5975
  if (!$main_content_display) {
5976
    $page['content']['system_main'] = drupal_set_page_content();
5977
  }
5978

    
5979
  return drupal_render($page);
5980
}
5981

    
5982
/**
5983
 * Renders HTML given a structured array tree.
5984
 *
5985
 * Recursively iterates over each of the array elements, generating HTML code.
5986
 *
5987
 * Renderable arrays have two kinds of key/value pairs: properties and
5988
 * children. Properties have keys starting with '#' and their values influence
5989
 * how the array will be rendered. Children are all elements whose keys do not
5990
 * start with a '#'. Their values should be renderable arrays themselves,
5991
 * which will be rendered during the rendering of the parent array. The markup
5992
 * provided by the children is typically inserted into the markup generated by
5993
 * the parent array.
5994
 *
5995
 * HTML generation for a renderable array, and the treatment of any children,
5996
 * is controlled by two properties containing theme functions, #theme and
5997
 * #theme_wrappers.
5998
 *
5999
 * #theme is the theme function called first. If it is set and the element has
6000
 * any children, it is the responsibility of the theme function to render
6001
 * these children. For elements that are not allowed to have any children,
6002
 * e.g. buttons or textfields, the theme function can be used to render the
6003
 * element itself. If #theme is not present and the element has children, each
6004
 * child is itself rendered by a call to drupal_render(), and the results are
6005
 * concatenated.
6006
 *
6007
 * The #theme_wrappers property contains an array of theme functions which will
6008
 * be called, in order, after #theme has run. These can be used to add further
6009
 * markup around the rendered children; e.g., fieldsets add the required markup
6010
 * for a fieldset around their rendered child elements. All wrapper theme
6011
 * functions have to include the element's #children property in their output,
6012
 * as it contains the output of the previous theme functions and the rendered
6013
 * children.
6014
 *
6015
 * For example, for the form element type, by default only the #theme_wrappers
6016
 * property is set, which adds the form markup around the rendered child
6017
 * elements of the form. This allows you to set the #theme property on a
6018
 * specific form to a custom theme function, giving you complete control over
6019
 * the placement of the form's children while not at all having to deal with
6020
 * the form markup itself.
6021
 *
6022
 * drupal_render() can optionally cache the rendered output of elements to
6023
 * improve performance. To use drupal_render() caching, set the element's #cache
6024
 * property to an associative array with one or several of the following keys:
6025
 * - 'keys': An array of one or more keys that identify the element. If 'keys'
6026
 *   is set, the cache ID is created automatically from these keys. See
6027
 *   drupal_render_cid_create().
6028
 * - 'granularity' (optional): Define the cache granularity using binary
6029
 *   combinations of the cache granularity constants, e.g.
6030
 *   DRUPAL_CACHE_PER_USER to cache for each user separately or
6031
 *   DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE to cache separately for each
6032
 *   page and role. If not specified the element is cached globally for each
6033
 *   theme and language.
6034
 * - 'cid': Specify the cache ID directly. Either 'keys' or 'cid' is required.
6035
 *   If 'cid' is set, 'keys' and 'granularity' are ignored. Use only if you
6036
 *   have special requirements.
6037
 * - 'expire': Set to one of the cache lifetime constants.
6038
 * - 'bin': Specify a cache bin to cache the element in. Defaults to 'cache'.
6039
 *
6040
 * This function is usually called from within another function, like
6041
 * drupal_get_form() or a theme function. Elements are sorted internally
6042
 * using uasort(). Since this is expensive, when passing already sorted
6043
 * elements to drupal_render(), for example from a database query, set
6044
 * $elements['#sorted'] = TRUE to avoid sorting them a second time.
6045
 *
6046
 * drupal_render() flags each element with a '#printed' status to indicate that
6047
 * the element has been rendered, which allows individual elements of a given
6048
 * array to be rendered independently and prevents them from being rendered
6049
 * more than once on subsequent calls to drupal_render() (e.g., as part of a
6050
 * larger array). If the same array or array element is passed more than once
6051
 * to drupal_render(), it simply returns an empty string.
6052
 *
6053
 * @param array $elements
6054
 *   The structured array describing the data to be rendered.
6055
 *
6056
 * @return string
6057
 *   The rendered HTML.
6058
 */
6059
function drupal_render(&$elements) {
6060
  // Early-return nothing if user does not have access.
6061
  if (empty($elements) || (isset($elements['#access']) && !$elements['#access'])) {
6062
    return '';
6063
  }
6064

    
6065
  // Do not print elements twice.
6066
  if (!empty($elements['#printed'])) {
6067
    return '';
6068
  }
6069

    
6070
  // Try to fetch the element's markup from cache and return.
6071
  if (isset($elements['#cache'])) {
6072
    $cached_output = drupal_render_cache_get($elements);
6073
    if ($cached_output !== FALSE) {
6074
      return $cached_output;
6075
    }
6076
  }
6077

    
6078
  // If #markup is set, ensure #type is set. This allows to specify just #markup
6079
  // on an element without setting #type.
6080
  if (isset($elements['#markup']) && !isset($elements['#type'])) {
6081
    $elements['#type'] = 'markup';
6082
  }
6083

    
6084
  // If the default values for this element have not been loaded yet, populate
6085
  // them.
6086
  if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
6087
    $elements += element_info($elements['#type']);
6088
  }
6089

    
6090
  // Make any final changes to the element before it is rendered. This means
6091
  // that the $element or the children can be altered or corrected before the
6092
  // element is rendered into the final text.
6093
  if (isset($elements['#pre_render'])) {
6094
    foreach ($elements['#pre_render'] as $function) {
6095
      if (function_exists($function)) {
6096
        $elements = $function($elements);
6097
      }
6098
    }
6099
  }
6100

    
6101
  // Allow #pre_render to abort rendering.
6102
  if (!empty($elements['#printed'])) {
6103
    return '';
6104
  }
6105

    
6106
  // Get the children of the element, sorted by weight.
6107
  $children = element_children($elements, TRUE);
6108

    
6109
  // Initialize this element's #children, unless a #pre_render callback already
6110
  // preset #children.
6111
  if (!isset($elements['#children'])) {
6112
    $elements['#children'] = '';
6113
  }
6114
  // Call the element's #theme function if it is set. Then any children of the
6115
  // element have to be rendered there.
6116
  if (isset($elements['#theme'])) {
6117
    $elements['#children'] = theme($elements['#theme'], $elements);
6118
  }
6119
  // If #theme was not set and the element has children, render them now.
6120
  // This is the same process as drupal_render_children() but is inlined
6121
  // for speed.
6122
  if ($elements['#children'] == '') {
6123
    foreach ($children as $key) {
6124
      $elements['#children'] .= drupal_render($elements[$key]);
6125
    }
6126
  }
6127

    
6128
  // Let the theme functions in #theme_wrappers add markup around the rendered
6129
  // children.
6130
  if (isset($elements['#theme_wrappers'])) {
6131
    foreach ($elements['#theme_wrappers'] as $theme_wrapper) {
6132
      $elements['#children'] = theme($theme_wrapper, $elements);
6133
    }
6134
  }
6135

    
6136
  // Filter the outputted content and make any last changes before the
6137
  // content is sent to the browser. The changes are made on $content
6138
  // which allows the output'ed text to be filtered.
6139
  if (isset($elements['#post_render'])) {
6140
    foreach ($elements['#post_render'] as $function) {
6141
      if (function_exists($function)) {
6142
        $elements['#children'] = $function($elements['#children'], $elements);
6143
      }
6144
    }
6145
  }
6146

    
6147
  // Add any JavaScript state information associated with the element.
6148
  if (!empty($elements['#states'])) {
6149
    drupal_process_states($elements);
6150
  }
6151

    
6152
  // Add additional libraries, CSS, JavaScript an other custom
6153
  // attached data associated with this element.
6154
  if (!empty($elements['#attached'])) {
6155
    drupal_process_attached($elements);
6156
  }
6157

    
6158
  $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
6159
  $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
6160
  $output = $prefix . $elements['#children'] . $suffix;
6161

    
6162
  // Cache the processed element if #cache is set.
6163
  if (isset($elements['#cache'])) {
6164
    drupal_render_cache_set($output, $elements);
6165
  }
6166

    
6167
  $elements['#printed'] = TRUE;
6168
  return $output;
6169
}
6170

    
6171
/**
6172
 * Renders children of an element and concatenates them.
6173
 *
6174
 * @param array $element
6175
 *   The structured array whose children shall be rendered.
6176
 * @param array $children_keys
6177
 *   (optional) If the keys of the element's children are already known, they
6178
 *   can be passed in to save another run of element_children().
6179
 *
6180
 * @return string
6181
 *   The rendered HTML of all children of the element.
6182

    
6183
 * @see drupal_render()
6184
 */
6185
function drupal_render_children(&$element, $children_keys = NULL) {
6186
  if ($children_keys === NULL) {
6187
    $children_keys = element_children($element);
6188
  }
6189
  $output = '';
6190
  foreach ($children_keys as $key) {
6191
    if (!empty($element[$key])) {
6192
      $output .= drupal_render($element[$key]);
6193
    }
6194
  }
6195
  return $output;
6196
}
6197

    
6198
/**
6199
 * Renders an element.
6200
 *
6201
 * This function renders an element using drupal_render(). The top level
6202
 * element is shown with show() before rendering, so it will always be rendered
6203
 * even if hide() had been previously used on it.
6204
 *
6205
 * @param $element
6206
 *   The element to be rendered.
6207
 *
6208
 * @return
6209
 *   The rendered element.
6210
 *
6211
 * @see drupal_render()
6212
 * @see show()
6213
 * @see hide()
6214
 */
6215
function render(&$element) {
6216
  if (is_array($element)) {
6217
    show($element);
6218
    return drupal_render($element);
6219
  }
6220
  else {
6221
    // Safe-guard for inappropriate use of render() on flat variables: return
6222
    // the variable as-is.
6223
    return $element;
6224
  }
6225
}
6226

    
6227
/**
6228
 * Hides an element from later rendering.
6229
 *
6230
 * The first time render() or drupal_render() is called on an element tree,
6231
 * as each element in the tree is rendered, it is marked with a #printed flag
6232
 * and the rendered children of the element are cached. Subsequent calls to
6233
 * render() or drupal_render() will not traverse the child tree of this element
6234
 * again: they will just use the cached children. So if you want to hide an
6235
 * element, be sure to call hide() on the element before its parent tree is
6236
 * rendered for the first time, as it will have no effect on subsequent
6237
 * renderings of the parent tree.
6238
 *
6239
 * @param $element
6240
 *   The element to be hidden.
6241
 *
6242
 * @return
6243
 *   The element.
6244
 *
6245
 * @see render()
6246
 * @see show()
6247
 */
6248
function hide(&$element) {
6249
  $element['#printed'] = TRUE;
6250
  return $element;
6251
}
6252

    
6253
/**
6254
 * Shows a hidden element for later rendering.
6255
 *
6256
 * You can also use render($element), which shows the element while rendering
6257
 * it.
6258
 *
6259
 * The first time render() or drupal_render() is called on an element tree,
6260
 * as each element in the tree is rendered, it is marked with a #printed flag
6261
 * and the rendered children of the element are cached. Subsequent calls to
6262
 * render() or drupal_render() will not traverse the child tree of this element
6263
 * again: they will just use the cached children. So if you want to show an
6264
 * element, be sure to call show() on the element before its parent tree is
6265
 * rendered for the first time, as it will have no effect on subsequent
6266
 * renderings of the parent tree.
6267
 *
6268
 * @param $element
6269
 *   The element to be shown.
6270
 *
6271
 * @return
6272
 *   The element.
6273
 *
6274
 * @see render()
6275
 * @see hide()
6276
 */
6277
function show(&$element) {
6278
  $element['#printed'] = FALSE;
6279
  return $element;
6280
}
6281

    
6282
/**
6283
 * Gets the rendered output of a renderable element from the cache.
6284
 *
6285
 * @param $elements
6286
 *   A renderable array.
6287
 *
6288
 * @return
6289
 *   A markup string containing the rendered content of the element, or FALSE
6290
 *   if no cached copy of the element is available.
6291
 *
6292
 * @see drupal_render()
6293
 * @see drupal_render_cache_set()
6294
 */
6295
function drupal_render_cache_get($elements) {
6296
  if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
6297
    return FALSE;
6298
  }
6299
  $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
6300

    
6301
  if (!empty($cid) && $cache = cache_get($cid, $bin)) {
6302
    // Add additional libraries, JavaScript, CSS and other data attached
6303
    // to this element.
6304
    if (isset($cache->data['#attached'])) {
6305
      drupal_process_attached($cache->data);
6306
    }
6307
    // Return the rendered output.
6308
    return $cache->data['#markup'];
6309
  }
6310
  return FALSE;
6311
}
6312

    
6313
/**
6314
 * Caches the rendered output of a renderable element.
6315
 *
6316
 * This is called by drupal_render() if the #cache property is set on an
6317
 * element.
6318
 *
6319
 * @param $markup
6320
 *   The rendered output string of $elements.
6321
 * @param $elements
6322
 *   A renderable array.
6323
 *
6324
 * @see drupal_render_cache_get()
6325
 */
6326
function drupal_render_cache_set(&$markup, $elements) {
6327
  // Create the cache ID for the element.
6328
  if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
6329
    return FALSE;
6330
  }
6331

    
6332
  // Cache implementations are allowed to modify the markup, to support
6333
  // replacing markup with edge-side include commands. The supporting cache
6334
  // backend will store the markup in some other key (like
6335
  // $data['#real-value']) and return an include command instead. When the
6336
  // ESI command is executed by the content accelerator, the real value can
6337
  // be retrieved and used.
6338
  $data['#markup'] = &$markup;
6339
  // Persist attached data associated with this element.
6340
  $attached = drupal_render_collect_attached($elements, TRUE);
6341
  if ($attached) {
6342
    $data['#attached'] = $attached;
6343
  }
6344
  $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
6345
  $expire = isset($elements['#cache']['expire']) ? $elements['#cache']['expire'] : CACHE_PERMANENT;
6346
  cache_set($cid, $data, $bin, $expire);
6347
}
6348

    
6349
/**
6350
 * Collects #attached for an element and its children into a single array.
6351
 *
6352
 * When caching elements, it is necessary to collect all libraries, JavaScript
6353
 * and CSS into a single array, from both the element itself and all child
6354
 * elements. This allows drupal_render() to add these back to the page when the
6355
 * element is returned from cache.
6356
 *
6357
 * @param $elements
6358
 *   The element to collect #attached from.
6359
 * @param $return
6360
 *   Whether to return the attached elements and reset the internal static.
6361
 *
6362
 * @return
6363
 *   The #attached array for this element and its descendants.
6364
 */
6365
function drupal_render_collect_attached($elements, $return = FALSE) {
6366
  $attached = &drupal_static(__FUNCTION__, array());
6367

    
6368
  // Collect all #attached for this element.
6369
  if (isset($elements['#attached'])) {
6370
    foreach ($elements['#attached'] as $key => $value) {
6371
      if (!isset($attached[$key])) {
6372
        $attached[$key] = array();
6373
      }
6374
      $attached[$key] = array_merge($attached[$key], $value);
6375
    }
6376
  }
6377
  if ($children = element_children($elements)) {
6378
    foreach ($children as $child) {
6379
      drupal_render_collect_attached($elements[$child]);
6380
    }
6381
  }
6382

    
6383
  // If this was the first call to the function, return all attached elements
6384
  // and reset the static cache.
6385
  if ($return) {
6386
    $return = $attached;
6387
    $attached = array();
6388
    return $return;
6389
  }
6390
}
6391

    
6392
/**
6393
 * Prepares an element for caching based on a query.
6394
 *
6395
 * This smart caching strategy saves Drupal from querying and rendering to HTML
6396
 * when the underlying query is unchanged.
6397
 *
6398
 * Expensive queries should use the query builder to create the query and then
6399
 * call this function. Executing the query and formatting results should happen
6400
 * in a #pre_render callback.
6401
 *
6402
 * @param $query
6403
 *   A select query object as returned by db_select().
6404
 * @param $function
6405
 *   The name of the function doing this caching. A _pre_render suffix will be
6406
 *   added to this string and is also part of the cache key in
6407
 *   drupal_render_cache_set() and drupal_render_cache_get().
6408
 * @param $expire
6409
 *   The cache expire time, passed eventually to cache_set().
6410
 * @param $granularity
6411
 *   One or more granularity constants passed to drupal_render_cid_parts().
6412
 *
6413
 * @return
6414
 *   A renderable array with the following keys and values:
6415
 *   - #query: The passed-in $query.
6416
 *   - #pre_render: $function with a _pre_render suffix.
6417
 *   - #cache: An associative array prepared for drupal_render_cache_set().
6418
 */
6419
function drupal_render_cache_by_query($query, $function, $expire = CACHE_TEMPORARY, $granularity = NULL) {
6420
  $cache_keys = array_merge(array($function), drupal_render_cid_parts($granularity));
6421
  $query->preExecute();
6422
  $cache_keys[] = hash('sha256', serialize(array((string) $query, $query->getArguments())));
6423
  return array(
6424
    '#query' => $query,
6425
    '#pre_render' => array($function . '_pre_render'),
6426
    '#cache' => array(
6427
      'keys' => $cache_keys,
6428
      'expire' => $expire,
6429
    ),
6430
  );
6431
}
6432

    
6433
/**
6434
 * Returns cache ID parts for building a cache ID.
6435
 *
6436
 * @param $granularity
6437
 *   One or more cache granularity constants. For example, to cache separately
6438
 *   for each user, use DRUPAL_CACHE_PER_USER. To cache separately for each
6439
 *   page and role, use the expression:
6440
 *   @code
6441
 *   DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE
6442
 *   @endcode
6443
 *
6444
 * @return
6445
 *   An array of cache ID parts, always containing the active theme. If the
6446
 *   locale module is enabled it also contains the active language. If
6447
 *   $granularity was passed in, more parts are added.
6448
 */
6449
function drupal_render_cid_parts($granularity = NULL) {
6450
  global $theme, $base_root, $user;
6451

    
6452
  $cid_parts[] = $theme;
6453
  // If Locale is enabled but we have only one language we do not need it as cid
6454
  // part.
6455
  if (drupal_multilingual()) {
6456
    foreach (language_types_configurable() as $language_type) {
6457
      $cid_parts[] = $GLOBALS[$language_type]->language;
6458
    }
6459
  }
6460

    
6461
  if (!empty($granularity)) {
6462
    $cache_per_role = $granularity & DRUPAL_CACHE_PER_ROLE;
6463
    $cache_per_user = $granularity & DRUPAL_CACHE_PER_USER;
6464
    // User 1 has special permissions outside of the role system, so when
6465
    // caching per role is requested, it should cache per user instead.
6466
    if ($user->uid == 1 && $cache_per_role) {
6467
      $cache_per_user = TRUE;
6468
      $cache_per_role = FALSE;
6469
    }
6470
    // 'PER_ROLE' and 'PER_USER' are mutually exclusive. 'PER_USER' can be a
6471
    // resource drag for sites with many users, so when a module is being
6472
    // equivocal, we favor the less expensive 'PER_ROLE' pattern.
6473
    if ($cache_per_role) {
6474
      $cid_parts[] = 'r.' . implode(',', array_keys($user->roles));
6475
    }
6476
    elseif ($cache_per_user) {
6477
      $cid_parts[] = "u.$user->uid";
6478
    }
6479

    
6480
    if ($granularity & DRUPAL_CACHE_PER_PAGE) {
6481
      $cid_parts[] = $base_root . request_uri();
6482
    }
6483
  }
6484

    
6485
  return $cid_parts;
6486
}
6487

    
6488
/**
6489
 * Creates the cache ID for a renderable element.
6490
 *
6491
 * This creates the cache ID string, either by returning the #cache['cid']
6492
 * property if present or by building the cache ID out of the #cache['keys']
6493
 * and, optionally, the #cache['granularity'] properties.
6494
 *
6495
 * @param $elements
6496
 *   A renderable array.
6497
 *
6498
 * @return
6499
 *   The cache ID string, or FALSE if the element may not be cached.
6500
 */
6501
function drupal_render_cid_create($elements) {
6502
  if (isset($elements['#cache']['cid'])) {
6503
    return $elements['#cache']['cid'];
6504
  }
6505
  elseif (isset($elements['#cache']['keys'])) {
6506
    $granularity = isset($elements['#cache']['granularity']) ? $elements['#cache']['granularity'] : NULL;
6507
    // Merge in additional cache ID parts based provided by drupal_render_cid_parts().
6508
    $cid_parts = array_merge($elements['#cache']['keys'], drupal_render_cid_parts($granularity));
6509
    return implode(':', $cid_parts);
6510
  }
6511
  return FALSE;
6512
}
6513

    
6514
/**
6515
 * Function used by uasort to sort structured arrays by weight.
6516
 */
6517
function element_sort($a, $b) {
6518
  $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
6519
  $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
6520
  if ($a_weight == $b_weight) {
6521
    return 0;
6522
  }
6523
  return ($a_weight < $b_weight) ? -1 : 1;
6524
}
6525

    
6526
/**
6527
 * Array sorting callback; sorts elements by title.
6528
 */
6529
function element_sort_by_title($a, $b) {
6530
  $a_title = (is_array($a) && isset($a['#title'])) ? $a['#title'] : '';
6531
  $b_title = (is_array($b) && isset($b['#title'])) ? $b['#title'] : '';
6532
  return strnatcasecmp($a_title, $b_title);
6533
}
6534

    
6535
/**
6536
 * Retrieves the default properties for the defined element type.
6537
 *
6538
 * @param $type
6539
 *   An element type as defined by hook_element_info().
6540
 */
6541
function element_info($type) {
6542
  // Use the advanced drupal_static() pattern, since this is called very often.
6543
  static $drupal_static_fast;
6544
  if (!isset($drupal_static_fast)) {
6545
    $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__);
6546
  }
6547
  $cache = &$drupal_static_fast['cache'];
6548

    
6549
  if (!isset($cache)) {
6550
    $cache = module_invoke_all('element_info');
6551
    foreach ($cache as $element_type => $info) {
6552
      $cache[$element_type]['#type'] = $element_type;
6553
    }
6554
    // Allow modules to alter the element type defaults.
6555
    drupal_alter('element_info', $cache);
6556
  }
6557

    
6558
  return isset($cache[$type]) ? $cache[$type] : array();
6559
}
6560

    
6561
/**
6562
 * Retrieves a single property for the defined element type.
6563
 *
6564
 * @param $type
6565
 *   An element type as defined by hook_element_info().
6566
 * @param $property_name
6567
 *   The property within the element type that should be returned.
6568
 * @param $default
6569
 *   (Optional) The value to return if the element type does not specify a
6570
 *   value for the property. Defaults to NULL.
6571
 */
6572
function element_info_property($type, $property_name, $default = NULL) {
6573
  return (($info = element_info($type)) && array_key_exists($property_name, $info)) ? $info[$property_name] : $default;
6574
}
6575

    
6576
/**
6577
 * Sorts a structured array by the 'weight' element.
6578
 *
6579
 * Note that the sorting is by the 'weight' array element, not by the render
6580
 * element property '#weight'.
6581
 *
6582
 * Callback for uasort() used in various functions.
6583
 *
6584
 * @param $a
6585
 *   First item for comparison. The compared items should be associative arrays
6586
 *   that optionally include a 'weight' element. For items without a 'weight'
6587
 *   element, a default value of 0 will be used.
6588
 * @param $b
6589
 *   Second item for comparison.
6590
 */
6591
function drupal_sort_weight($a, $b) {
6592
  $a_weight = (is_array($a) && isset($a['weight'])) ? $a['weight'] : 0;
6593
  $b_weight = (is_array($b) && isset($b['weight'])) ? $b['weight'] : 0;
6594
  if ($a_weight == $b_weight) {
6595
    return 0;
6596
  }
6597
  return ($a_weight < $b_weight) ? -1 : 1;
6598
}
6599

    
6600
/**
6601
 * Array sorting callback; sorts elements by 'title' key.
6602
 */
6603
function drupal_sort_title($a, $b) {
6604
  if (!isset($b['title'])) {
6605
    return -1;
6606
  }
6607
  if (!isset($a['title'])) {
6608
    return 1;
6609
  }
6610
  return strcasecmp($a['title'], $b['title']);
6611
}
6612

    
6613
/**
6614
 * Checks if the key is a property.
6615
 */
6616
function element_property($key) {
6617
  return $key[0] == '#';
6618
}
6619

    
6620
/**
6621
 * Gets properties of a structured array element (keys beginning with '#').
6622
 */
6623
function element_properties($element) {
6624
  return array_filter(array_keys((array) $element), 'element_property');
6625
}
6626

    
6627
/**
6628
 * Checks if the key is a child.
6629
 */
6630
function element_child($key) {
6631
  return !isset($key[0]) || $key[0] != '#';
6632
}
6633

    
6634
/**
6635
 * Identifies the children of an element array, optionally sorted by weight.
6636
 *
6637
 * The children of a element array are those key/value pairs whose key does
6638
 * not start with a '#'. See drupal_render() for details.
6639
 *
6640
 * @param $elements
6641
 *   The element array whose children are to be identified.
6642
 * @param $sort
6643
 *   Boolean to indicate whether the children should be sorted by weight.
6644
 *
6645
 * @return
6646
 *   The array keys of the element's children.
6647
 */
6648
function element_children(&$elements, $sort = FALSE) {
6649
  // Do not attempt to sort elements which have already been sorted.
6650
  $sort = isset($elements['#sorted']) ? !$elements['#sorted'] : $sort;
6651

    
6652
  // Filter out properties from the element, leaving only children.
6653
  $children = array();
6654
  $sortable = FALSE;
6655
  foreach ($elements as $key => $value) {
6656
    if ($key === '' || $key[0] !== '#') {
6657
      $children[$key] = $value;
6658
      if (is_array($value) && isset($value['#weight'])) {
6659
        $sortable = TRUE;
6660
      }
6661
    }
6662
  }
6663
  // Sort the children if necessary.
6664
  if ($sort && $sortable) {
6665
    uasort($children, 'element_sort');
6666
    // Put the sorted children back into $elements in the correct order, to
6667
    // preserve sorting if the same element is passed through
6668
    // element_children() twice.
6669
    foreach ($children as $key => $child) {
6670
      unset($elements[$key]);
6671
      $elements[$key] = $child;
6672
    }
6673
    $elements['#sorted'] = TRUE;
6674
  }
6675

    
6676
  return array_keys($children);
6677
}
6678

    
6679
/**
6680
 * Returns the visible children of an element.
6681
 *
6682
 * @param $elements
6683
 *   The parent element.
6684
 *
6685
 * @return
6686
 *   The array keys of the element's visible children.
6687
 */
6688
function element_get_visible_children(array $elements) {
6689
  $visible_children = array();
6690

    
6691
  foreach (element_children($elements) as $key) {
6692
    $child = $elements[$key];
6693

    
6694
    // Skip un-accessible children.
6695
    if (isset($child['#access']) && !$child['#access']) {
6696
      continue;
6697
    }
6698

    
6699
    // Skip value and hidden elements, since they are not rendered.
6700
    if (isset($child['#type']) && in_array($child['#type'], array('value', 'hidden'))) {
6701
      continue;
6702
    }
6703

    
6704
    $visible_children[$key] = $child;
6705
  }
6706

    
6707
  return array_keys($visible_children);
6708
}
6709

    
6710
/**
6711
 * Sets HTML attributes based on element properties.
6712
 *
6713
 * @param $element
6714
 *   The renderable element to process.
6715
 * @param $map
6716
 *   An associative array whose keys are element property names and whose values
6717
 *   are the HTML attribute names to set for corresponding the property; e.g.,
6718
 *   array('#propertyname' => 'attributename'). If both names are identical
6719
 *   except for the leading '#', then an attribute name value is sufficient and
6720
 *   no property name needs to be specified.
6721
 */
6722
function element_set_attributes(array &$element, array $map) {
6723
  foreach ($map as $property => $attribute) {
6724
    // If the key is numeric, the attribute name needs to be taken over.
6725
    if (is_int($property)) {
6726
      $property = '#' . $attribute;
6727
    }
6728
    // Do not overwrite already existing attributes.
6729
    if (isset($element[$property]) && !isset($element['#attributes'][$attribute])) {
6730
      $element['#attributes'][$attribute] = $element[$property];
6731
    }
6732
  }
6733
}
6734

    
6735
/**
6736
 * Recursively computes the difference of arrays with additional index check.
6737
 *
6738
 * This is a version of array_diff_assoc() that supports multidimensional
6739
 * arrays.
6740
 *
6741
 * @param array $array1
6742
 *   The array to compare from.
6743
 * @param array $array2
6744
 *   The array to compare to.
6745
 *
6746
 * @return array
6747
 *   Returns an array containing all the values from array1 that are not present
6748
 *   in array2.
6749
 */
6750
function drupal_array_diff_assoc_recursive($array1, $array2) {
6751
  $difference = array();
6752

    
6753
  foreach ($array1 as $key => $value) {
6754
    if (is_array($value)) {
6755
      if (!array_key_exists($key, $array2) || !is_array($array2[$key])) {
6756
        $difference[$key] = $value;
6757
      }
6758
      else {
6759
        $new_diff = drupal_array_diff_assoc_recursive($value, $array2[$key]);
6760
        if (!empty($new_diff)) {
6761
          $difference[$key] = $new_diff;
6762
        }
6763
      }
6764
    }
6765
    elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
6766
      $difference[$key] = $value;
6767
    }
6768
  }
6769

    
6770
  return $difference;
6771
}
6772

    
6773
/**
6774
 * Sets a value in a nested array with variable depth.
6775
 *
6776
 * This helper function should be used when the depth of the array element you
6777
 * are changing may vary (that is, the number of parent keys is variable). It
6778
 * is primarily used for form structures and renderable arrays.
6779
 *
6780
 * Example:
6781
 * @code
6782
 * // Assume you have a 'signature' element somewhere in a form. It might be:
6783
 * $form['signature_settings']['signature'] = array(
6784
 *   '#type' => 'text_format',
6785
 *   '#title' => t('Signature'),
6786
 * );
6787
 * // Or, it might be further nested:
6788
 * $form['signature_settings']['user']['signature'] = array(
6789
 *   '#type' => 'text_format',
6790
 *   '#title' => t('Signature'),
6791
 * );
6792
 * @endcode
6793
 *
6794
 * To deal with the situation, the code needs to figure out the route to the
6795
 * element, given an array of parents that is either
6796
 * @code array('signature_settings', 'signature') @endcode in the first case or
6797
 * @code array('signature_settings', 'user', 'signature') @endcode in the second
6798
 * case.
6799
 *
6800
 * Without this helper function the only way to set the signature element in one
6801
 * line would be using eval(), which should be avoided:
6802
 * @code
6803
 * // Do not do this! Avoid eval().
6804
 * eval('$form[\'' . implode("']['", $parents) . '\'] = $element;');
6805
 * @endcode
6806
 *
6807
 * Instead, use this helper function:
6808
 * @code
6809
 * drupal_array_set_nested_value($form, $parents, $element);
6810
 * @endcode
6811
 *
6812
 * However if the number of array parent keys is static, the value should always
6813
 * be set directly rather than calling this function. For instance, for the
6814
 * first example we could just do:
6815
 * @code
6816
 * $form['signature_settings']['signature'] = $element;
6817
 * @endcode
6818
 *
6819
 * @param $array
6820
 *   A reference to the array to modify.
6821
 * @param $parents
6822
 *   An array of parent keys, starting with the outermost key.
6823
 * @param $value
6824
 *   The value to set.
6825
 * @param $force
6826
 *   (Optional) If TRUE, the value is forced into the structure even if it
6827
 *   requires the deletion of an already existing non-array parent value. If
6828
 *   FALSE, PHP throws an error if trying to add into a value that is not an
6829
 *   array. Defaults to FALSE.
6830
 *
6831
 * @see drupal_array_get_nested_value()
6832
 */
6833
function drupal_array_set_nested_value(array &$array, array $parents, $value, $force = FALSE) {
6834
  $ref = &$array;
6835
  foreach ($parents as $parent) {
6836
    // PHP auto-creates container arrays and NULL entries without error if $ref
6837
    // is NULL, but throws an error if $ref is set, but not an array.
6838
    if ($force && isset($ref) && !is_array($ref)) {
6839
      $ref = array();
6840
    }
6841
    $ref = &$ref[$parent];
6842
  }
6843
  $ref = $value;
6844
}
6845

    
6846
/**
6847
 * Retrieves a value from a nested array with variable depth.
6848
 *
6849
 * This helper function should be used when the depth of the array element being
6850
 * retrieved may vary (that is, the number of parent keys is variable). It is
6851
 * primarily used for form structures and renderable arrays.
6852
 *
6853
 * Without this helper function the only way to get a nested array value with
6854
 * variable depth in one line would be using eval(), which should be avoided:
6855
 * @code
6856
 * // Do not do this! Avoid eval().
6857
 * // May also throw a PHP notice, if the variable array keys do not exist.
6858
 * eval('$value = $array[\'' . implode("']['", $parents) . "'];");
6859
 * @endcode
6860
 *
6861
 * Instead, use this helper function:
6862
 * @code
6863
 * $value = drupal_array_get_nested_value($form, $parents);
6864
 * @endcode
6865
 *
6866
 * A return value of NULL is ambiguous, and can mean either that the requested
6867
 * key does not exist, or that the actual value is NULL. If it is required to
6868
 * know whether the nested array key actually exists, pass a third argument that
6869
 * is altered by reference:
6870
 * @code
6871
 * $key_exists = NULL;
6872
 * $value = drupal_array_get_nested_value($form, $parents, $key_exists);
6873
 * if ($key_exists) {
6874
 *   // ... do something with $value ...
6875
 * }
6876
 * @endcode
6877
 *
6878
 * However if the number of array parent keys is static, the value should always
6879
 * be retrieved directly rather than calling this function. For instance:
6880
 * @code
6881
 * $value = $form['signature_settings']['signature'];
6882
 * @endcode
6883
 *
6884
 * @param $array
6885
 *   The array from which to get the value.
6886
 * @param $parents
6887
 *   An array of parent keys of the value, starting with the outermost key.
6888
 * @param $key_exists
6889
 *   (optional) If given, an already defined variable that is altered by
6890
 *   reference.
6891
 *
6892
 * @return
6893
 *   The requested nested value. Possibly NULL if the value is NULL or not all
6894
 *   nested parent keys exist. $key_exists is altered by reference and is a
6895
 *   Boolean that indicates whether all nested parent keys exist (TRUE) or not
6896
 *   (FALSE). This allows to distinguish between the two possibilities when NULL
6897
 *   is returned.
6898
 *
6899
 * @see drupal_array_set_nested_value()
6900
 */
6901
function &drupal_array_get_nested_value(array &$array, array $parents, &$key_exists = NULL) {
6902
  $ref = &$array;
6903
  foreach ($parents as $parent) {
6904
    if (is_array($ref) && array_key_exists($parent, $ref)) {
6905
      $ref = &$ref[$parent];
6906
    }
6907
    else {
6908
      $key_exists = FALSE;
6909
      $null = NULL;
6910
      return $null;
6911
    }
6912
  }
6913
  $key_exists = TRUE;
6914
  return $ref;
6915
}
6916

    
6917
/**
6918
 * Determines whether a nested array contains the requested keys.
6919
 *
6920
 * This helper function should be used when the depth of the array element to be
6921
 * checked may vary (that is, the number of parent keys is variable). See
6922
 * drupal_array_set_nested_value() for details. It is primarily used for form
6923
 * structures and renderable arrays.
6924
 *
6925
 * If it is required to also get the value of the checked nested key, use
6926
 * drupal_array_get_nested_value() instead.
6927
 *
6928
 * If the number of array parent keys is static, this helper function is
6929
 * unnecessary and the following code can be used instead:
6930
 * @code
6931
 * $value_exists = isset($form['signature_settings']['signature']);
6932
 * $key_exists = array_key_exists('signature', $form['signature_settings']);
6933
 * @endcode
6934
 *
6935
 * @param $array
6936
 *   The array with the value to check for.
6937
 * @param $parents
6938
 *   An array of parent keys of the value, starting with the outermost key.
6939
 *
6940
 * @return
6941
 *   TRUE if all the parent keys exist, FALSE otherwise.
6942
 *
6943
 * @see drupal_array_get_nested_value()
6944
 */
6945
function drupal_array_nested_key_exists(array $array, array $parents) {
6946
  // Although this function is similar to PHP's array_key_exists(), its
6947
  // arguments should be consistent with drupal_array_get_nested_value().
6948
  $key_exists = NULL;
6949
  drupal_array_get_nested_value($array, $parents, $key_exists);
6950
  return $key_exists;
6951
}
6952

    
6953
/**
6954
 * Provides theme registration for themes across .inc files.
6955
 */
6956
function drupal_common_theme() {
6957
  return array(
6958
    // From theme.inc.
6959
    'html' => array(
6960
      'render element' => 'page',
6961
      'template' => 'html',
6962
    ),
6963
    'page' => array(
6964
      'render element' => 'page',
6965
      'template' => 'page',
6966
    ),
6967
    'region' => array(
6968
      'render element' => 'elements',
6969
      'template' => 'region',
6970
    ),
6971
    'status_messages' => array(
6972
      'variables' => array('display' => NULL),
6973
    ),
6974
    'link' => array(
6975
      'variables' => array('text' => NULL, 'path' => NULL, 'options' => array()),
6976
    ),
6977
    'links' => array(
6978
      'variables' => array('links' => NULL, 'attributes' => array('class' => array('links')), 'heading' => array()),
6979
    ),
6980
    'image' => array(
6981
      // HTML 4 and XHTML 1.0 always require an alt attribute. The HTML 5 draft
6982
      // allows the alt attribute to be omitted in some cases. Therefore,
6983
      // default the alt attribute to an empty string, but allow code calling
6984
      // theme('image') to pass explicit NULL for it to be omitted. Usually,
6985
      // neither omission nor an empty string satisfies accessibility
6986
      // requirements, so it is strongly encouraged for code calling
6987
      // theme('image') to pass a meaningful value for the alt variable.
6988
      // - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
6989
      // - http://www.w3.org/TR/xhtml1/dtds.html
6990
      // - http://dev.w3.org/html5/spec/Overview.html#alt
6991
      // The title attribute is optional in all cases, so it is omitted by
6992
      // default.
6993
      'variables' => array('path' => NULL, 'width' => NULL, 'height' => NULL, 'alt' => '', 'title' => NULL, 'attributes' => array()),
6994
    ),
6995
    'breadcrumb' => array(
6996
      'variables' => array('breadcrumb' => NULL),
6997
    ),
6998
    'help' => array(
6999
      'variables' => array(),
7000
    ),
7001
    'table' => array(
7002
      'variables' => array(
7003
        'header' => NULL,
7004
        'footer' => NULL,
7005
        'rows' => NULL,
7006
        'attributes' => array(),
7007
        'caption' => NULL,
7008
        'colgroups' => array(),
7009
        'sticky' => TRUE,
7010
        'empty' => '',
7011
      ),
7012
    ),
7013
    'tablesort_indicator' => array(
7014
      'variables' => array('style' => NULL),
7015
    ),
7016
    'mark' => array(
7017
      'variables' => array('type' => MARK_NEW),
7018
    ),
7019
    'item_list' => array(
7020
      'variables' => array('items' => array(), 'title' => NULL, 'type' => 'ul', 'attributes' => array()),
7021
    ),
7022
    'more_help_link' => array(
7023
      'variables' => array('url' => NULL),
7024
    ),
7025
    'feed_icon' => array(
7026
      'variables' => array('url' => NULL, 'title' => NULL),
7027
    ),
7028
    'more_link' => array(
7029
      'variables' => array('url' => NULL, 'title' => NULL)
7030
    ),
7031
    'username' => array(
7032
      'variables' => array('account' => NULL),
7033
    ),
7034
    'progress_bar' => array(
7035
      'variables' => array('percent' => NULL, 'message' => NULL),
7036
    ),
7037
    'indentation' => array(
7038
      'variables' => array('size' => 1),
7039
    ),
7040
    'html_tag' => array(
7041
      'render element' => 'element',
7042
    ),
7043
    // From theme.maintenance.inc.
7044
    'maintenance_page' => array(
7045
      'variables' => array('content' => NULL, 'show_messages' => TRUE),
7046
      'template' => 'maintenance-page',
7047
    ),
7048
    'update_page' => array(
7049
      'variables' => array('content' => NULL, 'show_messages' => TRUE),
7050
    ),
7051
    'install_page' => array(
7052
      'variables' => array('content' => NULL),
7053
    ),
7054
    'task_list' => array(
7055
      'variables' => array('items' => NULL, 'active' => NULL),
7056
    ),
7057
    'authorize_message' => array(
7058
      'variables' => array('message' => NULL, 'success' => TRUE),
7059
    ),
7060
    'authorize_report' => array(
7061
      'variables' => array('messages' => array()),
7062
    ),
7063
    // From pager.inc.
7064
    'pager' => array(
7065
      'variables' => array('tags' => array(), 'element' => 0, 'parameters' => array(), 'quantity' => 9),
7066
    ),
7067
    'pager_first' => array(
7068
      'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
7069
    ),
7070
    'pager_previous' => array(
7071
      'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
7072
    ),
7073
    'pager_next' => array(
7074
      'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
7075
    ),
7076
    'pager_last' => array(
7077
      'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
7078
    ),
7079
    'pager_link' => array(
7080
      'variables' => array('text' => NULL, 'page_new' => NULL, 'element' => NULL, 'parameters' => array(), 'attributes' => array()),
7081
    ),
7082
    // From menu.inc.
7083
    'menu_link' => array(
7084
      'render element' => 'element',
7085
    ),
7086
    'menu_tree' => array(
7087
      'render element' => 'tree',
7088
    ),
7089
    'menu_local_task' => array(
7090
      'render element' => 'element',
7091
    ),
7092
    'menu_local_action' => array(
7093
      'render element' => 'element',
7094
    ),
7095
    'menu_local_tasks' => array(
7096
      'variables' => array('primary' => array(), 'secondary' => array()),
7097
    ),
7098
    // From form.inc.
7099
    'select' => array(
7100
      'render element' => 'element',
7101
    ),
7102
    'fieldset' => array(
7103
      'render element' => 'element',
7104
    ),
7105
    'radio' => array(
7106
      'render element' => 'element',
7107
    ),
7108
    'radios' => array(
7109
      'render element' => 'element',
7110
    ),
7111
    'date' => array(
7112
      'render element' => 'element',
7113
    ),
7114
    'exposed_filters' => array(
7115
      'render element' => 'form',
7116
    ),
7117
    'checkbox' => array(
7118
      'render element' => 'element',
7119
    ),
7120
    'checkboxes' => array(
7121
      'render element' => 'element',
7122
    ),
7123
    'button' => array(
7124
      'render element' => 'element',
7125
    ),
7126
    'image_button' => array(
7127
      'render element' => 'element',
7128
    ),
7129
    'hidden' => array(
7130
      'render element' => 'element',
7131
    ),
7132
    'textfield' => array(
7133
      'render element' => 'element',
7134
    ),
7135
    'form' => array(
7136
      'render element' => 'element',
7137
    ),
7138
    'textarea' => array(
7139
      'render element' => 'element',
7140
    ),
7141
    'password' => array(
7142
      'render element' => 'element',
7143
    ),
7144
    'file' => array(
7145
      'render element' => 'element',
7146
    ),
7147
    'tableselect' => array(
7148
      'render element' => 'element',
7149
    ),
7150
    'form_element' => array(
7151
      'render element' => 'element',
7152
    ),
7153
    'form_required_marker' => array(
7154
      'render element' => 'element',
7155
    ),
7156
    'form_element_label' => array(
7157
      'render element' => 'element',
7158
    ),
7159
    'vertical_tabs' => array(
7160
      'render element' => 'element',
7161
    ),
7162
    'container' => array(
7163
      'render element' => 'element',
7164
    ),
7165
  );
7166
}
7167

    
7168
/**
7169
 * @addtogroup schemaapi
7170
 * @{
7171
 */
7172

    
7173
/**
7174
 * Creates all tables defined in a module's hook_schema().
7175
 *
7176
 * Note: This function does not pass the module's schema through
7177
 * hook_schema_alter(). The module's tables will be created exactly as the
7178
 * module defines them.
7179
 *
7180
 * @param $module
7181
 *   The module for which the tables will be created.
7182
 */
7183
function drupal_install_schema($module) {
7184
  $schema = drupal_get_schema_unprocessed($module);
7185
  _drupal_schema_initialize($schema, $module, FALSE);
7186

    
7187
  foreach ($schema as $name => $table) {
7188
    db_create_table($name, $table);
7189
  }
7190
}
7191

    
7192
/**
7193
 * Removes all tables defined in a module's hook_schema().
7194
 *
7195
 * Note: This function does not pass the module's schema through
7196
 * hook_schema_alter(). The module's tables will be created exactly as the
7197
 * module defines them.
7198
 *
7199
 * @param $module
7200
 *   The module for which the tables will be removed.
7201
 *
7202
 * @return
7203
 *   An array of arrays with the following key/value pairs:
7204
 *    - success: a boolean indicating whether the query succeeded.
7205
 *    - query: the SQL query(s) executed, passed through check_plain().
7206
 */
7207
function drupal_uninstall_schema($module) {
7208
  $schema = drupal_get_schema_unprocessed($module);
7209
  _drupal_schema_initialize($schema, $module, FALSE);
7210

    
7211
  foreach ($schema as $table) {
7212
    if (db_table_exists($table['name'])) {
7213
      db_drop_table($table['name']);
7214
    }
7215
  }
7216
}
7217

    
7218
/**
7219
 * Returns the unprocessed and unaltered version of a module's schema.
7220
 *
7221
 * Use this function only if you explicitly need the original
7222
 * specification of a schema, as it was defined in a module's
7223
 * hook_schema(). No additional default values will be set,
7224
 * hook_schema_alter() is not invoked and these unprocessed
7225
 * definitions won't be cached. To retrieve the schema after
7226
 * hook_schema_alter() has been invoked use drupal_get_schema().
7227
 *
7228
 * This function can be used to retrieve a schema specification in
7229
 * hook_schema(), so it allows you to derive your tables from existing
7230
 * specifications.
7231
 *
7232
 * It is also used by drupal_install_schema() and
7233
 * drupal_uninstall_schema() to ensure that a module's tables are
7234
 * created exactly as specified without any changes introduced by a
7235
 * module that implements hook_schema_alter().
7236
 *
7237
 * @param $module
7238
 *   The module to which the table belongs.
7239
 * @param $table
7240
 *   The name of the table. If not given, the module's complete schema
7241
 *   is returned.
7242
 */
7243
function drupal_get_schema_unprocessed($module, $table = NULL) {
7244
  // Load the .install file to get hook_schema.
7245
  module_load_install($module);
7246
  $schema = module_invoke($module, 'schema');
7247

    
7248
  if (isset($table) && isset($schema[$table])) {
7249
    return $schema[$table];
7250
  }
7251
  elseif (!empty($schema)) {
7252
    return $schema;
7253
  }
7254
  return array();
7255
}
7256

    
7257
/**
7258
 * Fills in required default values for table definitions from hook_schema().
7259
 *
7260
 * @param $schema
7261
 *   The schema definition array as it was returned by the module's
7262
 *   hook_schema().
7263
 * @param $module
7264
 *   The module for which hook_schema() was invoked.
7265
 * @param $remove_descriptions
7266
 *   (optional) Whether to additionally remove 'description' keys of all tables
7267
 *   and fields to improve performance of serialize() and unserialize().
7268
 *   Defaults to TRUE.
7269
 */
7270
function _drupal_schema_initialize(&$schema, $module, $remove_descriptions = TRUE) {
7271
  // Set the name and module key for all tables.
7272
  foreach ($schema as $name => &$table) {
7273
    if (empty($table['module'])) {
7274
      $table['module'] = $module;
7275
    }
7276
    if (!isset($table['name'])) {
7277
      $table['name'] = $name;
7278
    }
7279
    if ($remove_descriptions) {
7280
      unset($table['description']);
7281
      foreach ($table['fields'] as &$field) {
7282
        unset($field['description']);
7283
      }
7284
    }
7285
  }
7286
}
7287

    
7288
/**
7289
 * Retrieves the type for every field in a table schema.
7290
 *
7291
 * @param $table
7292
 *   The name of the table from which to retrieve type information.
7293
 *
7294
 * @return
7295
 *   An array of types, keyed by field name.
7296
 */
7297
function drupal_schema_field_types($table) {
7298
  $table_schema = drupal_get_schema($table);
7299
  $field_types = array();
7300
  foreach ($table_schema['fields'] as $field_name => $field_info) {
7301
    $field_types[$field_name] = isset($field_info['type']) ? $field_info['type'] : NULL;
7302
  }
7303
  return $field_types;
7304
}
7305

    
7306
/**
7307
 * Retrieves a list of fields from a table schema.
7308
 *
7309
 * The returned list is suitable for use in an SQL query.
7310
 *
7311
 * @param $table
7312
 *   The name of the table from which to retrieve fields.
7313
 * @param
7314
 *   An optional prefix to to all fields.
7315
 *
7316
 * @return An array of fields.
7317
 */
7318
function drupal_schema_fields_sql($table, $prefix = NULL) {
7319
  $schema = drupal_get_schema($table);
7320
  $fields = array_keys($schema['fields']);
7321
  if ($prefix) {
7322
    $columns = array();
7323
    foreach ($fields as $field) {
7324
      $columns[] = "$prefix.$field";
7325
    }
7326
    return $columns;
7327
  }
7328
  else {
7329
    return $fields;
7330
  }
7331
}
7332

    
7333
/**
7334
 * Saves (inserts or updates) a record to the database based upon the schema.
7335
 *
7336
 * Do not use drupal_write_record() within hook_update_N() functions, since the
7337
 * database schema cannot be relied upon when a user is running a series of
7338
 * updates. Instead, use db_insert() or db_update() to save the record.
7339
 *
7340
 * @param $table
7341
 *   The name of the table; this must be defined by a hook_schema()
7342
 *   implementation.
7343
 * @param $record
7344
 *   An object or array representing the record to write, passed in by
7345
 *   reference. If inserting a new record, values not provided in $record will
7346
 *   be populated in $record and in the database with the default values from
7347
 *   the schema, as well as a single serial (auto-increment) field (if present).
7348
 *   If updating an existing record, only provided values are updated in the
7349
 *   database, and $record is not modified.
7350
 * @param $primary_keys
7351
 *   To indicate that this is a new record to be inserted, omit this argument.
7352
 *   If this is an update, this argument specifies the primary keys' field
7353
 *   names. If there is only 1 field in the key, you may pass in a string; if
7354
 *   there are multiple fields in the key, pass in an array.
7355
 *
7356
 * @return
7357
 *   If the record insert or update failed, returns FALSE. If it succeeded,
7358
 *   returns SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
7359
 */
7360
function drupal_write_record($table, &$record, $primary_keys = array()) {
7361
  // Standardize $primary_keys to an array.
7362
  if (is_string($primary_keys)) {
7363
    $primary_keys = array($primary_keys);
7364
  }
7365

    
7366
  $schema = drupal_get_schema($table);
7367
  if (empty($schema)) {
7368
    return FALSE;
7369
  }
7370

    
7371
  $object = (object) $record;
7372
  $fields = array();
7373

    
7374
  // Go through the schema to determine fields to write.
7375
  foreach ($schema['fields'] as $field => $info) {
7376
    if ($info['type'] == 'serial') {
7377
      // Skip serial types if we are updating.
7378
      if (!empty($primary_keys)) {
7379
        continue;
7380
      }
7381
      // Track serial field so we can helpfully populate them after the query.
7382
      // NOTE: Each table should come with one serial field only.
7383
      $serial = $field;
7384
    }
7385

    
7386
    // Skip field if it is in $primary_keys as it is unnecessary to update a
7387
    // field to the value it is already set to.
7388
    if (in_array($field, $primary_keys)) {
7389
      continue;
7390
    }
7391

    
7392
    if (!property_exists($object, $field)) {
7393
      // Skip fields that are not provided, default values are already known
7394
      // by the database.
7395
      continue;
7396
    }
7397

    
7398
    // Build array of fields to update or insert.
7399
    if (empty($info['serialize'])) {
7400
      $fields[$field] = $object->$field;
7401
    }
7402
    else {
7403
      $fields[$field] = serialize($object->$field);
7404
    }
7405

    
7406
    // Type cast to proper datatype, except when the value is NULL and the
7407
    // column allows this.
7408
    //
7409
    // MySQL PDO silently casts e.g. FALSE and '' to 0 when inserting the value
7410
    // into an integer column, but PostgreSQL PDO does not. Also type cast NULL
7411
    // when the column does not allow this.
7412
    if (isset($object->$field) || !empty($info['not null'])) {
7413
      if ($info['type'] == 'int' || $info['type'] == 'serial') {
7414
        $fields[$field] = (int) $fields[$field];
7415
      }
7416
      elseif ($info['type'] == 'float') {
7417
        $fields[$field] = (float) $fields[$field];
7418
      }
7419
      else {
7420
        $fields[$field] = (string) $fields[$field];
7421
      }
7422
    }
7423
  }
7424

    
7425
  if (empty($fields)) {
7426
    return;
7427
  }
7428

    
7429
  // Build the SQL.
7430
  if (empty($primary_keys)) {
7431
    // We are doing an insert.
7432
    $options = array('return' => Database::RETURN_INSERT_ID);
7433
    if (isset($serial) && isset($fields[$serial])) {
7434
      // If the serial column has been explicitly set with an ID, then we don't
7435
      // require the database to return the last insert id.
7436
      if ($fields[$serial]) {
7437
        $options['return'] = Database::RETURN_AFFECTED;
7438
      }
7439
      // If a serial column does exist with no value (i.e. 0) then remove it as
7440
      // the database will insert the correct value for us.
7441
      else {
7442
        unset($fields[$serial]);
7443
      }
7444
    }
7445
    $query = db_insert($table, $options)->fields($fields);
7446
    $return = SAVED_NEW;
7447
  }
7448
  else {
7449
    $query = db_update($table)->fields($fields);
7450
    foreach ($primary_keys as $key) {
7451
      $query->condition($key, $object->$key);
7452
    }
7453
    $return = SAVED_UPDATED;
7454
  }
7455

    
7456
  // Execute the SQL.
7457
  if ($query_return = $query->execute()) {
7458
    if (isset($serial)) {
7459
      // If the database was not told to return the last insert id, it will be
7460
      // because we already know it.
7461
      if (isset($options) && $options['return'] != Database::RETURN_INSERT_ID) {
7462
        $object->$serial = $fields[$serial];
7463
      }
7464
      else {
7465
        $object->$serial = $query_return;
7466
      }
7467
    }
7468
  }
7469
  // If we have a single-field primary key but got no insert ID, the
7470
  // query failed. Note that we explicitly check for FALSE, because
7471
  // a valid update query which doesn't change any values will return
7472
  // zero (0) affected rows.
7473
  elseif ($query_return === FALSE && count($primary_keys) == 1) {
7474
    $return = FALSE;
7475
  }
7476

    
7477
  // If we are inserting, populate empty fields with default values.
7478
  if (empty($primary_keys)) {
7479
    foreach ($schema['fields'] as $field => $info) {
7480
      if (isset($info['default']) && !property_exists($object, $field)) {
7481
        $object->$field = $info['default'];
7482
      }
7483
    }
7484
  }
7485

    
7486
  // If we began with an array, convert back.
7487
  if (is_array($record)) {
7488
    $record = (array) $object;
7489
  }
7490

    
7491
  return $return;
7492
}
7493

    
7494
/**
7495
 * @} End of "addtogroup schemaapi".
7496
 */
7497

    
7498
/**
7499
 * Parses Drupal module and theme .info files.
7500
 *
7501
 * Info files are NOT for placing arbitrary theme and module-specific settings.
7502
 * Use variable_get() and variable_set() for that.
7503
 *
7504
 * Information stored in a module .info file:
7505
 * - name: The real name of the module for display purposes.
7506
 * - description: A brief description of the module.
7507
 * - dependencies: An array of dependency strings. Each is in the form
7508
 *   'project:module (versions)'; with the following meanings:
7509
 *   - project: (optional) Project shortname, recommended to ensure uniqueness,
7510
 *     if the module is part of a project hosted on drupal.org. If omitted,
7511
 *     also omit the : that follows. The project name is currently ignored by
7512
 *     Drupal core but is used for automated testing.
7513
 *   - module: (required) Module shortname within the project.
7514
 *   - (versions): Optional version information, consisting of one or more
7515
 *     comma-separated operator/value pairs or simply version numbers, which
7516
 *     can contain "x" as a wildcard. Examples: (>=7.22, <7.28), (7.x-3.x).
7517
 * - package: The name of the package of modules this module belongs to.
7518
 *
7519
 * See forum.info for an example of a module .info file.
7520
 *
7521
 * Information stored in a theme .info file:
7522
 * - name: The real name of the theme for display purposes.
7523
 * - description: Brief description.
7524
 * - screenshot: Path to screenshot relative to the theme's .info file.
7525
 * - engine: Theme engine; typically phptemplate.
7526
 * - base: Name of a base theme, if applicable; e.g., base = zen.
7527
 * - regions: Listed regions; e.g., region[left] = Left sidebar.
7528
 * - features: Features available; e.g., features[] = logo.
7529
 * - stylesheets: Theme stylesheets; e.g., stylesheets[all][] = my-style.css.
7530
 * - scripts: Theme scripts; e.g., scripts[] = my-script.js.
7531
 *
7532
 * See bartik.info for an example of a theme .info file.
7533
 *
7534
 * @param $filename
7535
 *   The file we are parsing. Accepts file with relative or absolute path.
7536
 *
7537
 * @return
7538
 *   The info array.
7539
 *
7540
 * @see drupal_parse_info_format()
7541
 */
7542
function drupal_parse_info_file($filename) {
7543
  $info = &drupal_static(__FUNCTION__, array());
7544

    
7545
  if (!isset($info[$filename])) {
7546
    if (!file_exists($filename)) {
7547
      $info[$filename] = array();
7548
    }
7549
    else {
7550
      $data = file_get_contents($filename);
7551
      $info[$filename] = drupal_parse_info_format($data);
7552
    }
7553
  }
7554
  return $info[$filename];
7555
}
7556

    
7557
/**
7558
 * Parses data in Drupal's .info format.
7559
 *
7560
 * Data should be in an .ini-like format to specify values. White-space
7561
 * generally doesn't matter, except inside values:
7562
 * @code
7563
 *   key = value
7564
 *   key = "value"
7565
 *   key = 'value'
7566
 *   key = "multi-line
7567
 *   value"
7568
 *   key = 'multi-line
7569
 *   value'
7570
 *   key
7571
 *   =
7572
 *   'value'
7573
 * @endcode
7574
 *
7575
 * Arrays are created using a HTTP GET alike syntax:
7576
 * @code
7577
 *   key[] = "numeric array"
7578
 *   key[index] = "associative array"
7579
 *   key[index][] = "nested numeric array"
7580
 *   key[index][index] = "nested associative array"
7581
 * @endcode
7582
 *
7583
 * PHP constants are substituted in, but only when used as the entire value.
7584
 * Comments should start with a semi-colon at the beginning of a line.
7585
 *
7586
 * @param $data
7587
 *   A string to parse.
7588
 *
7589
 * @return
7590
 *   The info array.
7591
 *
7592
 * @see drupal_parse_info_file()
7593
 */
7594
function drupal_parse_info_format($data) {
7595
  $info = array();
7596

    
7597
  if (preg_match_all('
7598
    @^\s*                           # Start at the beginning of a line, ignoring leading whitespace
7599
    ((?:
7600
      [^=;\[\]]|                    # Key names cannot contain equal signs, semi-colons or square brackets,
7601
      \[[^\[\]]*\]                  # unless they are balanced and not nested
7602
    )+?)
7603
    \s*=\s*                         # Key/value pairs are separated by equal signs (ignoring white-space)
7604
    (?:
7605
      ("(?:[^"]|(?<=\\\\)")*")|     # Double-quoted string, which may contain slash-escaped quotes/slashes
7606
      (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
7607
      ([^\r\n]*?)                   # Non-quoted string
7608
    )\s*$                           # Stop at the next end of a line, ignoring trailing whitespace
7609
    @msx', $data, $matches, PREG_SET_ORDER)) {
7610
    foreach ($matches as $match) {
7611
      // Fetch the key and value string.
7612
      $i = 0;
7613
      foreach (array('key', 'value1', 'value2', 'value3') as $var) {
7614
        $$var = isset($match[++$i]) ? $match[$i] : '';
7615
      }
7616
      $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
7617

    
7618
      // Parse array syntax.
7619
      $keys = preg_split('/\]?\[/', rtrim($key, ']'));
7620
      $last = array_pop($keys);
7621
      $parent = &$info;
7622

    
7623
      // Create nested arrays.
7624
      foreach ($keys as $key) {
7625
        if ($key == '') {
7626
          $key = count($parent);
7627
        }
7628
        if (!isset($parent[$key]) || !is_array($parent[$key])) {
7629
          $parent[$key] = array();
7630
        }
7631
        $parent = &$parent[$key];
7632
      }
7633

    
7634
      // Handle PHP constants.
7635
      if (preg_match('/^\w+$/i', $value) && defined($value)) {
7636
        $value = constant($value);
7637
      }
7638

    
7639
      // Insert actual value.
7640
      if ($last == '') {
7641
        $last = count($parent);
7642
      }
7643
      $parent[$last] = $value;
7644
    }
7645
  }
7646

    
7647
  return $info;
7648
}
7649

    
7650
/**
7651
 * Returns a list of severity levels, as defined in RFC 3164.
7652
 *
7653
 * @return
7654
 *   Array of the possible severity levels for log messages.
7655
 *
7656
 * @see http://www.ietf.org/rfc/rfc3164.txt
7657
 * @see watchdog()
7658
 * @ingroup logging_severity_levels
7659
 */
7660
function watchdog_severity_levels() {
7661
  return array(
7662
    WATCHDOG_EMERGENCY => t('emergency'),
7663
    WATCHDOG_ALERT     => t('alert'),
7664
    WATCHDOG_CRITICAL  => t('critical'),
7665
    WATCHDOG_ERROR     => t('error'),
7666
    WATCHDOG_WARNING   => t('warning'),
7667
    WATCHDOG_NOTICE    => t('notice'),
7668
    WATCHDOG_INFO      => t('info'),
7669
    WATCHDOG_DEBUG     => t('debug'),
7670
  );
7671
}
7672

    
7673

    
7674
/**
7675
 * Explodes a string of tags into an array.
7676
 *
7677
 * @see drupal_implode_tags()
7678
 */
7679
function drupal_explode_tags($tags) {
7680
  // This regexp allows the following types of user input:
7681
  // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
7682
  $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
7683
  preg_match_all($regexp, $tags, $matches);
7684
  $typed_tags = array_unique($matches[1]);
7685

    
7686
  $tags = array();
7687
  foreach ($typed_tags as $tag) {
7688
    // If a user has escaped a term (to demonstrate that it is a group,
7689
    // or includes a comma or quote character), we remove the escape
7690
    // formatting so to save the term into the database as the user intends.
7691
    $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
7692
    if ($tag != "") {
7693
      $tags[] = $tag;
7694
    }
7695
  }
7696

    
7697
  return $tags;
7698
}
7699

    
7700
/**
7701
 * Implodes an array of tags into a string.
7702
 *
7703
 * @see drupal_explode_tags()
7704
 */
7705
function drupal_implode_tags($tags) {
7706
  $encoded_tags = array();
7707
  foreach ($tags as $tag) {
7708
    // Commas and quotes in tag names are special cases, so encode them.
7709
    if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
7710
      $tag = '"' . str_replace('"', '""', $tag) . '"';
7711
    }
7712

    
7713
    $encoded_tags[] = $tag;
7714
  }
7715
  return implode(', ', $encoded_tags);
7716
}
7717

    
7718
/**
7719
 * Flushes all cached data on the site.
7720
 *
7721
 * Empties cache tables, rebuilds the menu cache and theme registries, and
7722
 * invokes a hook so that other modules' cache data can be cleared as well.
7723
 */
7724
function drupal_flush_all_caches() {
7725
  // Change query-strings on css/js files to enforce reload for all users.
7726
  _drupal_flush_css_js();
7727

    
7728
  registry_rebuild();
7729
  drupal_clear_css_cache();
7730
  drupal_clear_js_cache();
7731

    
7732
  // Rebuild the theme data. Note that the module data is rebuilt above, as
7733
  // part of registry_rebuild().
7734
  system_rebuild_theme_data();
7735
  drupal_theme_rebuild();
7736

    
7737
  entity_info_cache_clear();
7738
  node_types_rebuild();
7739
  // node_menu() defines menu items based on node types so it needs to come
7740
  // after node types are rebuilt.
7741
  menu_rebuild();
7742

    
7743
  // Synchronize to catch any actions that were added or removed.
7744
  actions_synchronize();
7745

    
7746
  // Don't clear cache_form - in-progress form submissions may break.
7747
  // Ordered so clearing the page cache will always be the last action.
7748
  $core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
7749
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
7750
  foreach ($cache_tables as $table) {
7751
    cache_clear_all('*', $table, TRUE);
7752
  }
7753

    
7754
  // Rebuild the bootstrap module list. We do this here so that developers
7755
  // can get new hook_boot() implementations registered without having to
7756
  // write a hook_update_N() function.
7757
  _system_update_bootstrap_status();
7758
}
7759

    
7760
/**
7761
 * Changes the dummy query string added to all CSS and JavaScript files.
7762
 *
7763
 * Changing the dummy query string appended to CSS and JavaScript files forces
7764
 * all browsers to reload fresh files.
7765
 */
7766
function _drupal_flush_css_js() {
7767
  // The timestamp is converted to base 36 in order to make it more compact.
7768
  variable_set('css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
7769
}
7770

    
7771
/**
7772
 * Outputs debug information.
7773
 *
7774
 * The debug information is passed on to trigger_error() after being converted
7775
 * to a string using _drupal_debug_message().
7776
 *
7777
 * @param $data
7778
 *   Data to be output.
7779
 * @param $label
7780
 *   Label to prefix the data.
7781
 * @param $print_r
7782
 *   Flag to switch between print_r() and var_export() for data conversion to
7783
 *   string. Set $print_r to TRUE when dealing with a recursive data structure
7784
 *   as var_export() will generate an error.
7785
 */
7786
function debug($data, $label = NULL, $print_r = FALSE) {
7787
  // Print $data contents to string.
7788
  $string = check_plain($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
7789

    
7790
  // Display values with pre-formatting to increase readability.
7791
  $string = '<pre>' . $string . '</pre>';
7792

    
7793
  trigger_error(trim($label ? "$label: $string" : $string));
7794
}
7795

    
7796
/**
7797
 * Parses a dependency for comparison by drupal_check_incompatibility().
7798
 *
7799
 * @param $dependency
7800
 *   A dependency string, which specifies a module dependency, and optionally
7801
 *   the project it comes from and versions that are supported. Supported
7802
 *   formats include:
7803
 *   - 'module'
7804
 *   - 'project:module'
7805
 *   - 'project:module (>=version, version)'
7806
 *
7807
 * @return
7808
 *   An associative array with three keys:
7809
 *   - 'name' includes the name of the thing to depend on (e.g. 'foo').
7810
 *   - 'original_version' contains the original version string (which can be
7811
 *     used in the UI for reporting incompatibilities).
7812
 *   - 'versions' is a list of associative arrays, each containing the keys
7813
 *     'op' and 'version'. 'op' can be one of: '=', '==', '!=', '<>', '<',
7814
 *     '<=', '>', or '>='. 'version' is one piece like '4.5-beta3'.
7815
 *   Callers should pass this structure to drupal_check_incompatibility().
7816
 *
7817
 * @see drupal_check_incompatibility()
7818
 */
7819
function drupal_parse_dependency($dependency) {
7820
  $value = array();
7821
  // Split out the optional project name.
7822
  if (strpos($dependency, ':')) {
7823
    list($project_name, $dependency) = explode(':', $dependency);
7824
    $value['project'] = $project_name;
7825
  }
7826
  // We use named subpatterns and support every op that version_compare
7827
  // supports. Also, op is optional and defaults to equals.
7828
  $p_op = '(?P<operation>!=|==|=|<|<=|>|>=|<>)?';
7829
  // Core version is always optional: 7.x-2.x and 2.x is treated the same.
7830
  $p_core = '(?:' . preg_quote(DRUPAL_CORE_COMPATIBILITY) . '-)?';
7831
  $p_major = '(?P<major>\d+)';
7832
  // By setting the minor version to x, branches can be matched.
7833
  $p_minor = '(?P<minor>(?:\d+|x)(?:-[A-Za-z]+\d+)?)';
7834
  $parts = explode('(', $dependency, 2);
7835
  $value['name'] = trim($parts[0]);
7836
  if (isset($parts[1])) {
7837
    $value['original_version'] = ' (' . $parts[1];
7838
    foreach (explode(',', $parts[1]) as $version) {
7839
      if (preg_match("/^\s*$p_op\s*$p_core$p_major\.$p_minor/", $version, $matches)) {
7840
        $op = !empty($matches['operation']) ? $matches['operation'] : '=';
7841
        if ($matches['minor'] == 'x') {
7842
          // Drupal considers "2.x" to mean any version that begins with
7843
          // "2" (e.g. 2.0, 2.9 are all "2.x"). PHP's version_compare(),
7844
          // on the other hand, treats "x" as a string; so to
7845
          // version_compare(), "2.x" is considered less than 2.0. This
7846
          // means that >=2.x and <2.x are handled by version_compare()
7847
          // as we need, but > and <= are not.
7848
          if ($op == '>' || $op == '<=') {
7849
            $matches['major']++;
7850
          }
7851
          // Equivalence can be checked by adding two restrictions.
7852
          if ($op == '=' || $op == '==') {
7853
            $value['versions'][] = array('op' => '<', 'version' => ($matches['major'] + 1) . '.x');
7854
            $op = '>=';
7855
          }
7856
        }
7857
        $value['versions'][] = array('op' => $op, 'version' => $matches['major'] . '.' . $matches['minor']);
7858
      }
7859
    }
7860
  }
7861
  return $value;
7862
}
7863

    
7864
/**
7865
 * Checks whether a version is compatible with a given dependency.
7866
 *
7867
 * @param $v
7868
 *   The parsed dependency structure from drupal_parse_dependency().
7869
 * @param $current_version
7870
 *   The version to check against (like 4.2).
7871
 *
7872
 * @return
7873
 *   NULL if compatible, otherwise the original dependency version string that
7874
 *   caused the incompatibility.
7875
 *
7876
 * @see drupal_parse_dependency()
7877
 */
7878
function drupal_check_incompatibility($v, $current_version) {
7879
  if (!empty($v['versions'])) {
7880
    foreach ($v['versions'] as $required_version) {
7881
      if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
7882
        return $v['original_version'];
7883
      }
7884
    }
7885
  }
7886
}
7887

    
7888
/**
7889
 * Get the entity info array of an entity type.
7890
 *
7891
 * @param $entity_type
7892
 *   The entity type, e.g. node, for which the info shall be returned, or NULL
7893
 *   to return an array with info about all types.
7894
 *
7895
 * @see hook_entity_info()
7896
 * @see hook_entity_info_alter()
7897
 */
7898
function entity_get_info($entity_type = NULL) {
7899
  global $language;
7900

    
7901
  // Use the advanced drupal_static() pattern, since this is called very often.
7902
  static $drupal_static_fast;
7903
  if (!isset($drupal_static_fast)) {
7904
    $drupal_static_fast['entity_info'] = &drupal_static(__FUNCTION__);
7905
  }
7906
  $entity_info = &$drupal_static_fast['entity_info'];
7907

    
7908
  // hook_entity_info() includes translated strings, so each language is cached
7909
  // separately.
7910
  $langcode = $language->language;
7911

    
7912
  if (empty($entity_info)) {
7913
    if ($cache = cache_get("entity_info:$langcode")) {
7914
      $entity_info = $cache->data;
7915
    }
7916
    else {
7917
      $entity_info = module_invoke_all('entity_info');
7918
      // Merge in default values.
7919
      foreach ($entity_info as $name => $data) {
7920
        $entity_info[$name] += array(
7921
          'fieldable' => FALSE,
7922
          'controller class' => 'DrupalDefaultEntityController',
7923
          'static cache' => TRUE,
7924
          'field cache' => TRUE,
7925
          'load hook' => $name . '_load',
7926
          'bundles' => array(),
7927
          'view modes' => array(),
7928
          'entity keys' => array(),
7929
          'translation' => array(),
7930
        );
7931
        $entity_info[$name]['entity keys'] += array(
7932
          'revision' => '',
7933
          'bundle' => '',
7934
        );
7935
        foreach ($entity_info[$name]['view modes'] as $view_mode => $view_mode_info) {
7936
          $entity_info[$name]['view modes'][$view_mode] += array(
7937
            'custom settings' => FALSE,
7938
          );
7939
        }
7940
        // If no bundle key is provided, assume a single bundle, named after
7941
        // the entity type.
7942
        if (empty($entity_info[$name]['entity keys']['bundle']) && empty($entity_info[$name]['bundles'])) {
7943
          $entity_info[$name]['bundles'] = array($name => array('label' => $entity_info[$name]['label']));
7944
        }
7945
        // Prepare entity schema fields SQL info for
7946
        // DrupalEntityControllerInterface::buildQuery().
7947
        if (isset($entity_info[$name]['base table'])) {
7948
          $entity_info[$name]['base table field types'] = drupal_schema_field_types($entity_info[$name]['base table']);
7949
          $entity_info[$name]['schema_fields_sql']['base table'] = drupal_schema_fields_sql($entity_info[$name]['base table']);
7950
          if (isset($entity_info[$name]['revision table'])) {
7951
            $entity_info[$name]['schema_fields_sql']['revision table'] = drupal_schema_fields_sql($entity_info[$name]['revision table']);
7952
          }
7953
        }
7954
      }
7955
      // Let other modules alter the entity info.
7956
      drupal_alter('entity_info', $entity_info);
7957
      cache_set("entity_info:$langcode", $entity_info);
7958
    }
7959
  }
7960

    
7961
  if (empty($entity_type)) {
7962
    return $entity_info;
7963
  }
7964
  elseif (isset($entity_info[$entity_type])) {
7965
    return $entity_info[$entity_type];
7966
  }
7967
}
7968

    
7969
/**
7970
 * Resets the cached information about entity types.
7971
 */
7972
function entity_info_cache_clear() {
7973
  drupal_static_reset('entity_get_info');
7974
  // Clear all languages.
7975
  cache_clear_all('entity_info:', 'cache', TRUE);
7976
}
7977

    
7978
/**
7979
 * Helper function to extract id, vid, and bundle name from an entity.
7980
 *
7981
 * @param $entity_type
7982
 *   The entity type; e.g. 'node' or 'user'.
7983
 * @param $entity
7984
 *   The entity from which to extract values.
7985
 *
7986
 * @return
7987
 *   A numerically indexed array (not a hash table) containing these
7988
 *   elements:
7989
 *   - 0: Primary ID of the entity.
7990
 *   - 1: Revision ID of the entity, or NULL if $entity_type is not versioned.
7991
 *   - 2: Bundle name of the entity, or NULL if $entity_type has no bundles.
7992
 */
7993
function entity_extract_ids($entity_type, $entity) {
7994
  $info = entity_get_info($entity_type);
7995

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

    
8000
  if (!empty($info['entity keys']['bundle'])) {
8001
    // Explicitly fail for malformed entities missing the bundle property.
8002
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
8003
      throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
8004
    }
8005
    $bundle = $entity->{$info['entity keys']['bundle']};
8006
  }
8007
  else {
8008
    // The entity type provides no bundle key: assume a single bundle, named
8009
    // after the entity type.
8010
    $bundle = $entity_type;
8011
  }
8012

    
8013
  return array($id, $vid, $bundle);
8014
}
8015

    
8016
/**
8017
 * Helper function to assemble an object structure with initial ids.
8018
 *
8019
 * This function can be seen as reciprocal to entity_extract_ids().
8020
 *
8021
 * @param $entity_type
8022
 *   The entity type; e.g. 'node' or 'user'.
8023
 * @param $ids
8024
 *   A numerically indexed array, as returned by entity_extract_ids().
8025
 *
8026
 * @return
8027
 *   An entity structure, initialized with the ids provided.
8028
 *
8029
 * @see entity_extract_ids()
8030
 */
8031
function entity_create_stub_entity($entity_type, $ids) {
8032
  $entity = new stdClass();
8033
  $info = entity_get_info($entity_type);
8034
  $entity->{$info['entity keys']['id']} = $ids[0];
8035
  if (!empty($info['entity keys']['revision']) && isset($ids[1])) {
8036
    $entity->{$info['entity keys']['revision']} = $ids[1];
8037
  }
8038
  if (!empty($info['entity keys']['bundle']) && isset($ids[2])) {
8039
    $entity->{$info['entity keys']['bundle']} = $ids[2];
8040
  }
8041
  return $entity;
8042
}
8043

    
8044
/**
8045
 * Load entities from the database.
8046
 *
8047
 * The entities are stored in a static memory cache, and will not require
8048
 * database access if loaded again during the same page request.
8049
 *
8050
 * The actual loading is done through a class that has to implement the
8051
 * DrupalEntityControllerInterface interface. By default,
8052
 * DrupalDefaultEntityController is used. Entity types can specify that a
8053
 * different class should be used by setting the 'controller class' key in
8054
 * hook_entity_info(). These classes can either implement the
8055
 * DrupalEntityControllerInterface interface, or, most commonly, extend the
8056
 * DrupalDefaultEntityController class. See node_entity_info() and the
8057
 * NodeController in node.module as an example.
8058
 *
8059
 * @param $entity_type
8060
 *   The entity type to load, e.g. node or user.
8061
 * @param $ids
8062
 *   An array of entity IDs, or FALSE to load all entities.
8063
 * @param $conditions
8064
 *   (deprecated) An associative array of conditions on the base table, where
8065
 *   the keys are the database fields and the values are the values those
8066
 *   fields must have. Instead, it is preferable to use EntityFieldQuery to
8067
 *   retrieve a list of entity IDs loadable by this function.
8068
 * @param $reset
8069
 *   Whether to reset the internal cache for the requested entity type.
8070
 *
8071
 * @return
8072
 *   An array of entity objects indexed by their ids. When no results are
8073
 *   found, an empty array is returned.
8074
 *
8075
 * @todo Remove $conditions in Drupal 8.
8076
 *
8077
 * @see hook_entity_info()
8078
 * @see DrupalEntityControllerInterface
8079
 * @see DrupalDefaultEntityController
8080
 * @see EntityFieldQuery
8081
 */
8082
function entity_load($entity_type, $ids = FALSE, $conditions = array(), $reset = FALSE) {
8083
  if ($reset) {
8084
    entity_get_controller($entity_type)->resetCache();
8085
  }
8086
  return entity_get_controller($entity_type)->load($ids, $conditions);
8087
}
8088

    
8089
/**
8090
 * Loads the unchanged, i.e. not modified, entity from the database.
8091
 *
8092
 * Unlike entity_load() this function ensures the entity is directly loaded from
8093
 * the database, thus bypassing any static cache. In particular, this function
8094
 * is useful to determine changes by comparing the entity being saved to the
8095
 * stored entity.
8096
 *
8097
 * @param $entity_type
8098
 *   The entity type to load, e.g. node or user.
8099
 * @param $id
8100
 *   The ID of the entity to load.
8101
 *
8102
 * @return
8103
 *   The unchanged entity, or FALSE if the entity cannot be loaded.
8104
 */
8105
function entity_load_unchanged($entity_type, $id) {
8106
  entity_get_controller($entity_type)->resetCache(array($id));
8107
  $result = entity_get_controller($entity_type)->load(array($id));
8108
  return reset($result);
8109
}
8110

    
8111
/**
8112
 * Gets the entity controller for an entity type.
8113
 *
8114
 * @return DrupalEntityControllerInterface
8115
 *   The entity controller object for the specified entity type.
8116
 */
8117
function entity_get_controller($entity_type) {
8118
  $controllers = &drupal_static(__FUNCTION__, array());
8119
  if (!isset($controllers[$entity_type])) {
8120
    $type_info = entity_get_info($entity_type);
8121
    $class = $type_info['controller class'];
8122
    $controllers[$entity_type] = new $class($entity_type);
8123
  }
8124
  return $controllers[$entity_type];
8125
}
8126

    
8127
/**
8128
 * Invoke hook_entity_prepare_view().
8129
 *
8130
 * If adding a new entity similar to nodes, comments or users, you should
8131
 * invoke this function during the ENTITY_build_content() or
8132
 * ENTITY_view_multiple() phases of rendering to allow other modules to alter
8133
 * the objects during this phase. This is needed for situations where
8134
 * information needs to be loaded outside of ENTITY_load() - particularly
8135
 * when loading entities into one another - i.e. a user object into a node, due
8136
 * to the potential for unwanted side-effects such as caching and infinite
8137
 * recursion. By convention, entity_prepare_view() is called after
8138
 * field_attach_prepare_view() to allow entity level hooks to act on content
8139
 * loaded by field API.
8140
 *
8141
 * @param $entity_type
8142
 *   The type of entity, i.e. 'node', 'user'.
8143
 * @param $entities
8144
 *   The entity objects which are being prepared for view, keyed by object ID.
8145
 * @param $langcode
8146
 *   (optional) A language code to be used for rendering. Defaults to the global
8147
 *   content language of the current request.
8148
 *
8149
 * @see hook_entity_prepare_view()
8150
 */
8151
function entity_prepare_view($entity_type, $entities, $langcode = NULL) {
8152
  if (!isset($langcode)) {
8153
    $langcode = $GLOBALS['language_content']->language;
8154
  }
8155

    
8156
  // To ensure hooks are only run once per entity, check for an
8157
  // entity_view_prepared flag and only process items without it.
8158
  // @todo: resolve this more generally for both entity and field level hooks.
8159
  $prepare = array();
8160
  foreach ($entities as $id => $entity) {
8161
    if (empty($entity->entity_view_prepared)) {
8162
      // Add this entity to the items to be prepared.
8163
      $prepare[$id] = $entity;
8164

    
8165
      // Mark this item as prepared.
8166
      $entity->entity_view_prepared = TRUE;
8167
    }
8168
  }
8169

    
8170
  if (!empty($prepare)) {
8171
    module_invoke_all('entity_prepare_view', $prepare, $entity_type, $langcode);
8172
  }
8173
}
8174

    
8175
/**
8176
 * Invoke hook_entity_view_mode_alter().
8177
 *
8178
 * If adding a new entity similar to nodes, comments or users, you should invoke
8179
 * this function during the ENTITY_build_content() or ENTITY_view_multiple()
8180
 * phases of rendering to allow other modules to alter the view mode during this
8181
 * phase. This function needs to be called before field_attach_prepare_view() to
8182
 * ensure that the correct content is loaded by field API.
8183
 *
8184
 * @param $entity_type
8185
 *   The type of entity, i.e. 'node', 'user'.
8186
 * @param $entities
8187
 *   The entity objects which are being prepared for view, keyed by object ID.
8188
 * @param $view_mode
8189
 *   The original view mode e.g. 'full', 'teaser'...
8190
 * @param $langcode
8191
 *   (optional) A language code to be used for rendering. Defaults to the global
8192
 *   content language of the current request.
8193
 * @return
8194
 *   An associative array with arrays of entities keyed by view mode.
8195
 *
8196
 * @see hook_entity_view_mode_alter()
8197
 */
8198
function entity_view_mode_prepare($entity_type, $entities, $view_mode, $langcode = NULL) {
8199
  if (!isset($langcode)) {
8200
    $langcode = $GLOBALS['language_content']->language;
8201
  }
8202

    
8203
  // To ensure hooks are never run after field_attach_prepare_view() only
8204
  // process items without the entity_view_prepared flag.
8205
  $entities_by_view_mode = array();
8206
  foreach ($entities as $id => $entity) {
8207
    $entity_view_mode = $view_mode;
8208
    if (empty($entity->entity_view_prepared)) {
8209

    
8210
      // Allow modules to change the view mode.
8211
      $context = array(
8212
        'entity_type' => $entity_type,
8213
        'entity' => $entity,
8214
        'langcode' => $langcode,
8215
      );
8216
      drupal_alter('entity_view_mode', $entity_view_mode, $context);
8217
    }
8218

    
8219
    $entities_by_view_mode[$entity_view_mode][$id] = $entity;
8220
  }
8221

    
8222
  return $entities_by_view_mode;
8223
}
8224

    
8225
/**
8226
 * Returns the URI elements of an entity.
8227
 *
8228
 * @param $entity_type
8229
 *   The entity type; e.g. 'node' or 'user'.
8230
 * @param $entity
8231
 *   The entity for which to generate a path.
8232
 * @return
8233
 *   An array containing the 'path' and 'options' keys used to build the URI of
8234
 *   the entity, and matching the signature of url(). NULL if the entity has no
8235
 *   URI of its own.
8236
 */
8237
function entity_uri($entity_type, $entity) {
8238
  $info = entity_get_info($entity_type);
8239
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
8240

    
8241
  // A bundle-specific callback takes precedence over the generic one for the
8242
  // entity type.
8243
  if (isset($info['bundles'][$bundle]['uri callback'])) {
8244
    $uri_callback = $info['bundles'][$bundle]['uri callback'];
8245
  }
8246
  elseif (isset($info['uri callback'])) {
8247
    $uri_callback = $info['uri callback'];
8248
  }
8249
  else {
8250
    return NULL;
8251
  }
8252

    
8253
  // Invoke the callback to get the URI. If there is no callback, return NULL.
8254
  if (isset($uri_callback) && function_exists($uri_callback)) {
8255
    $uri = $uri_callback($entity);
8256
    // Pass the entity data to url() so that alter functions do not need to
8257
    // lookup this entity again.
8258
    $uri['options']['entity_type'] = $entity_type;
8259
    $uri['options']['entity'] = $entity;
8260
    return $uri;
8261
  }
8262
}
8263

    
8264
/**
8265
 * Returns the label of an entity.
8266
 *
8267
 * See the 'label callback' component of the hook_entity_info() return value
8268
 * for more information.
8269
 *
8270
 * @param $entity_type
8271
 *   The entity type; e.g., 'node' or 'user'.
8272
 * @param $entity
8273
 *   The entity for which to generate the label.
8274
 *
8275
 * @return
8276
 *   The entity label, or FALSE if not found.
8277
 */
8278
function entity_label($entity_type, $entity) {
8279
  $label = FALSE;
8280
  $info = entity_get_info($entity_type);
8281
  if (isset($info['label callback']) && function_exists($info['label callback'])) {
8282
    $label = $info['label callback']($entity, $entity_type);
8283
  }
8284
  elseif (!empty($info['entity keys']['label']) && isset($entity->{$info['entity keys']['label']})) {
8285
    $label = $entity->{$info['entity keys']['label']};
8286
  }
8287

    
8288
  return $label;
8289
}
8290

    
8291
/**
8292
 * Returns the language of an entity.
8293
 *
8294
 * @param $entity_type
8295
 *   The entity type; e.g., 'node' or 'user'.
8296
 * @param $entity
8297
 *   The entity for which to get the language.
8298
 *
8299
 * @return
8300
 *   A valid language code or NULL if the entity has no language support.
8301
 */
8302
function entity_language($entity_type, $entity) {
8303
  $info = entity_get_info($entity_type);
8304

    
8305
  // Invoke the callback to get the language. If there is no callback, try to
8306
  // get it from a property of the entity, otherwise NULL.
8307
  if (isset($info['language callback']) && function_exists($info['language callback'])) {
8308
    $langcode = $info['language callback']($entity_type, $entity);
8309
  }
8310
  elseif (!empty($info['entity keys']['language']) && isset($entity->{$info['entity keys']['language']})) {
8311
    $langcode = $entity->{$info['entity keys']['language']};
8312
  }
8313
  else {
8314
    // The value returned in D8 would be LANGUAGE_NONE, we cannot use it here to
8315
    // preserve backward compatibility. In fact this function has been
8316
    // introduced very late in the D7 life cycle, mainly as the proper default
8317
    // for field_attach_form(). By returning LANGUAGE_NONE when no language
8318
    // information is available, we would introduce a potentially BC-breaking
8319
    // API change, since field_attach_form() defaults to the default language
8320
    // instead of LANGUAGE_NONE. Moreover this allows us to distinguish between
8321
    // entities that have no language specified from ones that do not have
8322
    // language support at all.
8323
    $langcode = NULL;
8324
  }
8325

    
8326
  return $langcode;
8327
}
8328

    
8329
/**
8330
 * Attaches field API validation to entity forms.
8331
 */
8332
function entity_form_field_validate($entity_type, $form, &$form_state) {
8333
  // All field attach API functions act on an entity object, but during form
8334
  // validation, we don't have one. $form_state contains the entity as it was
8335
  // prior to processing the current form submission, and we must not update it
8336
  // until we have fully validated the submitted input. Therefore, for
8337
  // validation, act on a pseudo entity created out of the form values.
8338
  $pseudo_entity = (object) $form_state['values'];
8339
  field_attach_form_validate($entity_type, $pseudo_entity, $form, $form_state);
8340
}
8341

    
8342
/**
8343
 * Copies submitted values to entity properties for simple entity forms.
8344
 *
8345
 * During the submission handling of an entity form's "Save", "Preview", and
8346
 * possibly other buttons, the form state's entity needs to be updated with the
8347
 * submitted form values. Each entity form implements its own builder function
8348
 * for doing this, appropriate for the particular entity and form, whereas
8349
 * modules may specify additional builder functions in $form['#entity_builders']
8350
 * for copying the form values of added form elements to entity properties.
8351
 * Many of the main entity builder functions can call this helper function to
8352
 * re-use its logic of copying $form_state['values'][PROPERTY] values to
8353
 * $entity->PROPERTY for all entries in $form_state['values'] that are not field
8354
 * data, and calling field_attach_submit() to copy field data. Apart from that
8355
 * this helper invokes any additional builder functions that have been specified
8356
 * in $form['#entity_builders'].
8357
 *
8358
 * For some entity forms (e.g., forms with complex non-field data and forms that
8359
 * simultaneously edit multiple entities), this behavior may be inappropriate,
8360
 * so the builder function for such forms needs to implement the required
8361
 * functionality instead of calling this function.
8362
 */
8363
function entity_form_submit_build_entity($entity_type, $entity, $form, &$form_state) {
8364
  $info = entity_get_info($entity_type);
8365
  list(, , $bundle) = entity_extract_ids($entity_type, $entity);
8366

    
8367
  // Copy top-level form values that are not for fields to entity properties,
8368
  // without changing existing entity properties that are not being edited by
8369
  // this form. Copying field values must be done using field_attach_submit().
8370
  $values_excluding_fields = $info['fieldable'] ? array_diff_key($form_state['values'], field_info_instances($entity_type, $bundle)) : $form_state['values'];
8371
  foreach ($values_excluding_fields as $key => $value) {
8372
    $entity->$key = $value;
8373
  }
8374

    
8375
  // Invoke all specified builders for copying form values to entity properties.
8376
  if (isset($form['#entity_builders'])) {
8377
    foreach ($form['#entity_builders'] as $function) {
8378
      $function($entity_type, $entity, $form, $form_state);
8379
    }
8380
  }
8381

    
8382
  // Copy field values to the entity.
8383
  if ($info['fieldable']) {
8384
    field_attach_submit($entity_type, $entity, $form, $form_state);
8385
  }
8386
}
8387

    
8388
/**
8389
 * Performs one or more XML-RPC request(s).
8390
 *
8391
 * Usage example:
8392
 * @code
8393
 * $result = xmlrpc('http://example.com/xmlrpc.php', array(
8394
 *   'service.methodName' => array($parameter, $second, $third),
8395
 * ));
8396
 * @endcode
8397
 *
8398
 * @param $url
8399
 *   An absolute URL of the XML-RPC endpoint.
8400
 * @param $args
8401
 *   An associative array whose keys are the methods to call and whose values
8402
 *   are the arguments to pass to the respective method. If multiple methods
8403
 *   are specified, a system.multicall is performed.
8404
 * @param $options
8405
 *   (optional) An array of options to pass along to drupal_http_request().
8406
 *
8407
 * @return
8408
 *   For one request:
8409
 *     Either the return value of the method on success, or FALSE.
8410
 *     If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
8411
 *   For multiple requests:
8412
 *     An array of results. Each result will either be the result
8413
 *     returned by the method called, or an xmlrpc_error object if the call
8414
 *     failed. See xmlrpc_error().
8415
 */
8416
function xmlrpc($url, $args, $options = array()) {
8417
  require_once DRUPAL_ROOT . '/includes/xmlrpc.inc';
8418
  return _xmlrpc($url, $args, $options);
8419
}
8420

    
8421
/**
8422
 * Retrieves a list of all available archivers.
8423
 *
8424
 * @see hook_archiver_info()
8425
 * @see hook_archiver_info_alter()
8426
 */
8427
function archiver_get_info() {
8428
  $archiver_info = &drupal_static(__FUNCTION__, array());
8429

    
8430
  if (empty($archiver_info)) {
8431
    $cache = cache_get('archiver_info');
8432
    if ($cache === FALSE) {
8433
      // Rebuild the cache and save it.
8434
      $archiver_info = module_invoke_all('archiver_info');
8435
      drupal_alter('archiver_info', $archiver_info);
8436
      uasort($archiver_info, 'drupal_sort_weight');
8437
      cache_set('archiver_info', $archiver_info);
8438
    }
8439
    else {
8440
      $archiver_info = $cache->data;
8441
    }
8442
  }
8443

    
8444
  return $archiver_info;
8445
}
8446

    
8447
/**
8448
 * Returns a string of supported archive extensions.
8449
 *
8450
 * @return
8451
 *   A space-separated string of extensions suitable for use by the file
8452
 *   validation system.
8453
 */
8454
function archiver_get_extensions() {
8455
  $valid_extensions = array();
8456
  foreach (archiver_get_info() as $archive) {
8457
    foreach ($archive['extensions'] as $extension) {
8458
      foreach (explode('.', $extension) as $part) {
8459
        if (!in_array($part, $valid_extensions)) {
8460
          $valid_extensions[] = $part;
8461
        }
8462
      }
8463
    }
8464
  }
8465
  return implode(' ', $valid_extensions);
8466
}
8467

    
8468
/**
8469
 * Creates the appropriate archiver for the specified file.
8470
 *
8471
 * @param $file
8472
 *   The full path of the archive file. Note that stream wrapper paths are
8473
 *   supported, but not remote ones.
8474
 *
8475
 * @return
8476
 *   A newly created instance of the archiver class appropriate
8477
 *   for the specified file, already bound to that file.
8478
 *   If no appropriate archiver class was found, will return FALSE.
8479
 */
8480
function archiver_get_archiver($file) {
8481
  // Archivers can only work on local paths
8482
  $filepath = drupal_realpath($file);
8483
  if (!is_file($filepath)) {
8484
    throw new Exception(t('Archivers can only operate on local files: %file not supported', array('%file' => $file)));
8485
  }
8486
  $archiver_info = archiver_get_info();
8487

    
8488
  foreach ($archiver_info as $implementation) {
8489
    foreach ($implementation['extensions'] as $extension) {
8490
      // Because extensions may be multi-part, such as .tar.gz,
8491
      // we cannot use simpler approaches like substr() or pathinfo().
8492
      // This method isn't quite as clean but gets the job done.
8493
      // Also note that the file may not yet exist, so we cannot rely
8494
      // on fileinfo() or other disk-level utilities.
8495
      if (strrpos($filepath, '.' . $extension) === strlen($filepath) - strlen('.' . $extension)) {
8496
        return new $implementation['class']($filepath);
8497
      }
8498
    }
8499
  }
8500
}
8501

    
8502
/**
8503
 * Assembles the Drupal Updater registry.
8504
 *
8505
 * An Updater is a class that knows how to update various parts of the Drupal
8506
 * file system, for example to update modules that have newer releases, or to
8507
 * install a new theme.
8508
 *
8509
 * @return
8510
 *   The Drupal Updater class registry.
8511
 *
8512
 * @see hook_updater_info()
8513
 * @see hook_updater_info_alter()
8514
 */
8515
function drupal_get_updaters() {
8516
  $updaters = &drupal_static(__FUNCTION__);
8517
  if (!isset($updaters)) {
8518
    $updaters = module_invoke_all('updater_info');
8519
    drupal_alter('updater_info', $updaters);
8520
    uasort($updaters, 'drupal_sort_weight');
8521
  }
8522
  return $updaters;
8523
}
8524

    
8525
/**
8526
 * Assembles the Drupal FileTransfer registry.
8527
 *
8528
 * @return
8529
 *   The Drupal FileTransfer class registry.
8530
 *
8531
 * @see FileTransfer
8532
 * @see hook_filetransfer_info()
8533
 * @see hook_filetransfer_info_alter()
8534
 */
8535
function drupal_get_filetransfer_info() {
8536
  $info = &drupal_static(__FUNCTION__);
8537
  if (!isset($info)) {
8538
    // Since we have to manually set the 'file path' default for each
8539
    // module separately, we can't use module_invoke_all().
8540
    $info = array();
8541
    foreach (module_implements('filetransfer_info') as $module) {
8542
      $function = $module . '_filetransfer_info';
8543
      if (function_exists($function)) {
8544
        $result = $function();
8545
        if (isset($result) && is_array($result)) {
8546
          foreach ($result as &$values) {
8547
            if (empty($values['file path'])) {
8548
              $values['file path'] = drupal_get_path('module', $module);
8549
            }
8550
          }
8551
          $info = array_merge_recursive($info, $result);
8552
        }
8553
      }
8554
    }
8555
    drupal_alter('filetransfer_info', $info);
8556
    uasort($info, 'drupal_sort_weight');
8557
  }
8558
  return $info;
8559
}