Projet

Général

Profil

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

root / drupal7 / includes / common.inc @ e33d3026

1
<?php
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
232
  return $profile;
233
}
234

    
235

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

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

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

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

    
262
  return $breadcrumb;
263
}
264

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
445
  return $params;
446
}
447

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

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

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

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

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

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

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

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

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

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

    
620
  return $options;
621
}
622

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

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

    
691
  drupal_alter('drupal_goto', $path, $options, $http_response_code);
692

    
693
  // The 'Location' HTTP header must be absolute.
694
  $options['absolute'] = TRUE;
695

    
696
  $url = url($path, $options);
697

    
698
  header('Location: ' . $url, TRUE, $http_response_code);
699

    
700
  // The "Location" header sends a redirect status code to the HTTP daemon. In
701
  // some cases this can be wrong, so we make sure none of the code below the
702
  // drupal_goto() call gets executed upon redirection.
703
  drupal_exit($url);
704
}
705

    
706
/**
707
 * Delivers a "site is under maintenance" message to the browser.
708
 *
709
 * Page callback functions wanting to report a "site offline" message should
710
 * return MENU_SITE_OFFLINE instead of calling drupal_site_offline(). However,
711
 * functions that are invoked in contexts where that return value might not
712
 * bubble up to menu_execute_active_handler() should call drupal_site_offline().
713
 */
714
function drupal_site_offline() {
715
  drupal_deliver_page(MENU_SITE_OFFLINE);
716
}
717

    
718
/**
719
 * Delivers a "page not found" error to the browser.
720
 *
721
 * Page callback functions wanting to report a "page not found" message should
722
 * return MENU_NOT_FOUND instead of calling drupal_not_found(). However,
723
 * functions that are invoked in contexts where that return value might not
724
 * bubble up to menu_execute_active_handler() should call drupal_not_found().
725
 */
726
function drupal_not_found() {
727
  drupal_deliver_page(MENU_NOT_FOUND);
728
}
729

    
730
/**
731
 * Delivers an "access denied" error to the browser.
732
 *
733
 * Page callback functions wanting to report an "access denied" message should
734
 * return MENU_ACCESS_DENIED instead of calling drupal_access_denied(). However,
735
 * functions that are invoked in contexts where that return value might not
736
 * bubble up to menu_execute_active_handler() should call
737
 * drupal_access_denied().
738
 */
739
function drupal_access_denied() {
740
  drupal_deliver_page(MENU_ACCESS_DENIED);
741
}
742

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

    
790
  $result = new stdClass();
791

    
792
  // Parse the URL and make sure we can handle the schema.
793
  $uri = @parse_url($url);
794

    
795
  if ($uri == FALSE) {
796
    $result->error = 'unable to parse URL';
797
    $result->code = -1001;
798
    return $result;
799
  }
800

    
801
  if (!isset($uri['scheme'])) {
802
    $result->error = 'missing schema';
803
    $result->code = -1002;
804
    return $result;
805
  }
806

    
807
  timer_start(__FUNCTION__);
808

    
809
  // Merge the default options.
810
  $options += array(
811
    'headers' => array(),
812
    'method' => 'GET',
813
    'data' => NULL,
814
    'max_redirects' => 3,
815
    'timeout' => 30.0,
816
    'context' => NULL,
817
  );
818

    
819
  // Merge the default headers.
820
  $options['headers'] += array(
821
    'User-Agent' => 'Drupal (+http://drupal.org/)',
822
  );
823

    
824
  // stream_socket_client() requires timeout to be a float.
825
  $options['timeout'] = (float) $options['timeout'];
826

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

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

    
854
  switch ($uri['scheme']) {
855
    case 'proxy':
856
      // Make the socket connection to a proxy server.
857
      $socket = 'tcp://' . $proxy_server . ':' . variable_get('proxy_port', 8080);
858
      // The Host header still needs to match the real request.
859
      $options['headers']['Host'] = $uri['host'];
860
      $options['headers']['Host'] .= isset($uri['port']) && $uri['port'] != 80 ? ':' . $uri['port'] : '';
861
      break;
862

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

    
873
    case 'https':
874
      // Note: Only works when PHP is compiled with OpenSSL support.
875
      $port = isset($uri['port']) ? $uri['port'] : 443;
876
      $socket = 'ssl://' . $uri['host'] . ':' . $port;
877
      $options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
878
      break;
879

    
880
    default:
881
      $result->error = 'invalid schema ' . $uri['scheme'];
882
      $result->code = -1003;
883
      return $result;
884
  }
885

    
886
  if (empty($options['context'])) {
887
    $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout']);
888
  }
889
  else {
890
    // Create a stream with context. Allows verification of a SSL certificate.
891
    $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
892
  }
893

    
894
  // Make sure the socket opened properly.
895
  if (!$fp) {
896
    // When a network error occurs, we use a negative number so it does not
897
    // clash with the HTTP status codes.
898
    $result->code = -$errno;
899
    $result->error = trim($errstr) ? trim($errstr) : t('Error opening socket @socket', array('@socket' => $socket));
900

    
901
    // Mark that this request failed. This will trigger a check of the web
902
    // server's ability to make outgoing HTTP requests the next time that
903
    // requirements checking is performed.
904
    // See system_requirements().
905
    variable_set('drupal_http_request_fails', TRUE);
906

    
907
    return $result;
908
  }
909

    
910
  // Construct the path to act on.
911
  $path = isset($uri['path']) ? $uri['path'] : '/';
912
  if (isset($uri['query'])) {
913
    $path .= '?' . $uri['query'];
914
  }
915

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

    
925
  // If the server URL has a user then attempt to use basic authentication.
926
  if (isset($uri['user'])) {
927
    $options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ':'));
928
  }
929

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

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

    
954
  // Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
955
  // and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
956
  // instead must invoke stream_get_meta_data() each iteration.
957
  $info = stream_get_meta_data($fp);
958
  $alive = !$info['eof'] && !$info['timed_out'];
959
  $response = '';
960

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

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

    
987
  // Parse the response status line.
988
  list($protocol, $code, $status_message) = explode(' ', trim(array_shift($response)), 3);
989
  $result->protocol = $protocol;
990
  $result->status_message = $status_message;
991

    
992
  $result->headers = array();
993

    
994
  // Parse the response headers.
995
  while ($line = trim(array_shift($response))) {
996
    list($name, $value) = explode(':', $line, 2);
997
    $name = strtolower($name);
998
    if (isset($result->headers[$name]) && $name == 'set-cookie') {
999
      // RFC 2109: the Set-Cookie response header comprises the token Set-
1000
      // Cookie:, followed by a comma-separated list of one or more cookies.
1001
      $result->headers[$name] .= ',' . trim($value);
1002
    }
1003
    else {
1004
      $result->headers[$name] = trim($value);
1005
    }
1006
  }
1007

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

    
1057
  switch ($code) {
1058
    case 200: // OK
1059
    case 304: // Not modified
1060
      break;
1061
    case 301: // Moved permanently
1062
    case 302: // Moved temporarily
1063
    case 307: // Moved temporarily
1064
      $location = $result->headers['location'];
1065
      $options['timeout'] -= timer_read(__FUNCTION__) / 1000;
1066
      if ($options['timeout'] <= 0) {
1067
        $result->code = HTTP_REQUEST_TIMEOUT;
1068
        $result->error = 'request timed out';
1069
      }
1070
      elseif ($options['max_redirects']) {
1071
        // Redirect to the new location.
1072
        $options['max_redirects']--;
1073
        $result = drupal_http_request($location, $options);
1074
        $result->redirect_code = $code;
1075
      }
1076
      if (!isset($result->redirect_url)) {
1077
        $result->redirect_url = $location;
1078
      }
1079
      break;
1080
    default:
1081
      $result->error = $status_message;
1082
  }
1083

    
1084
  return $result;
1085
}
1086

    
1087
/**
1088
 * Helper function for determining hosts excluded from needing a proxy.
1089
 *
1090
 * @return
1091
 *   TRUE if a proxy should be used for this host.
1092
 */
1093
function _drupal_http_use_proxy($host) {
1094
  $proxy_exceptions = variable_get('proxy_exceptions', array('localhost', '127.0.0.1'));
1095
  return !in_array(strtolower($host), $proxy_exceptions, TRUE);
1096
}
1097

    
1098
/**
1099
 * @} End of "HTTP handling".
1100
 */
1101

    
1102
/**
1103
 * Strips slashes from a string or array of strings.
1104
 *
1105
 * Callback for array_walk() within fix_gpx_magic().
1106
 *
1107
 * @param $item
1108
 *   An individual string or array of strings from superglobals.
1109
 */
1110
function _fix_gpc_magic(&$item) {
1111
  if (is_array($item)) {
1112
    array_walk($item, '_fix_gpc_magic');
1113
  }
1114
  else {
1115
    $item = stripslashes($item);
1116
  }
1117
}
1118

    
1119
/**
1120
 * Strips slashes from $_FILES items.
1121
 *
1122
 * Callback for array_walk() within fix_gpc_magic().
1123
 *
1124
 * The tmp_name key is skipped keys since PHP generates single backslashes for
1125
 * file paths on Windows systems.
1126
 *
1127
 * @param $item
1128
 *   An item from $_FILES.
1129
 * @param $key
1130
 *   The key for the item within $_FILES.
1131
 *
1132
 * @see http://php.net/manual/features.file-upload.php#42280
1133
 */
1134
function _fix_gpc_magic_files(&$item, $key) {
1135
  if ($key != 'tmp_name') {
1136
    if (is_array($item)) {
1137
      array_walk($item, '_fix_gpc_magic_files');
1138
    }
1139
    else {
1140
      $item = stripslashes($item);
1141
    }
1142
  }
1143
}
1144

    
1145
/**
1146
 * Fixes double-escaping caused by "magic quotes" in some PHP installations.
1147
 *
1148
 * @see _fix_gpc_magic()
1149
 * @see _fix_gpc_magic_files()
1150
 */
1151
function fix_gpc_magic() {
1152
  static $fixed = FALSE;
1153
  if (!$fixed && ini_get('magic_quotes_gpc')) {
1154
    array_walk($_GET, '_fix_gpc_magic');
1155
    array_walk($_POST, '_fix_gpc_magic');
1156
    array_walk($_COOKIE, '_fix_gpc_magic');
1157
    array_walk($_REQUEST, '_fix_gpc_magic');
1158
    array_walk($_FILES, '_fix_gpc_magic_files');
1159
  }
1160
  $fixed = TRUE;
1161
}
1162

    
1163
/**
1164
 * @defgroup validation Input validation
1165
 * @{
1166
 * Functions to validate user input.
1167
 */
1168

    
1169
/**
1170
 * Verifies the syntax of the given e-mail address.
1171
 *
1172
 * This uses the
1173
 * @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
1174
 *
1175
 * @param $mail
1176
 *   A string containing an e-mail address.
1177
 *
1178
 * @return
1179
 *   TRUE if the address is in a valid format.
1180
 */
1181
function valid_email_address($mail) {
1182
  return (bool)filter_var($mail, FILTER_VALIDATE_EMAIL);
1183
}
1184

    
1185
/**
1186
 * Verifies the syntax of the given URL.
1187
 *
1188
 * This function should only be used on actual URLs. It should not be used for
1189
 * Drupal menu paths, which can contain arbitrary characters.
1190
 * Valid values per RFC 3986.
1191
 * @param $url
1192
 *   The URL to verify.
1193
 * @param $absolute
1194
 *   Whether the URL is absolute (beginning with a scheme such as "http:").
1195
 *
1196
 * @return
1197
 *   TRUE if the URL is in a valid format.
1198
 */
1199
function valid_url($url, $absolute = FALSE) {
1200
  if ($absolute) {
1201
    return (bool)preg_match("
1202
      /^                                                      # Start at the beginning of the text
1203
      (?:ftp|https?|feed):\/\/                                # Look for ftp, http, https or feed schemes
1204
      (?:                                                     # Userinfo (optional) which is typically
1205
        (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)*      # a username or a username and password
1206
        (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@          # combination
1207
      )?
1208
      (?:
1209
        (?:[a-z0-9\-\.]|%[0-9a-f]{2})+                        # A domain name or a IPv4 address
1210
        |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\])         # or a well formed IPv6 address
1211
      )
1212
      (?::[0-9]+)?                                            # Server port number (optional)
1213
      (?:[\/|\?]
1214
        (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})   # The path and query (optional)
1215
      *)?
1216
    $/xi", $url);
1217
  }
1218
  else {
1219
    return (bool)preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url);
1220
  }
1221
}
1222

    
1223
/**
1224
 * @} End of "defgroup validation".
1225
 */
1226

    
1227
/**
1228
 * Registers an event for the current visitor to the flood control mechanism.
1229
 *
1230
 * @param $name
1231
 *   The name of an event.
1232
 * @param $window
1233
 *   Optional number of seconds before this event expires. Defaults to 3600 (1
1234
 *   hour). Typically uses the same value as the flood_is_allowed() $window
1235
 *   parameter. Expired events are purged on cron run to prevent the flood table
1236
 *   from growing indefinitely.
1237
 * @param $identifier
1238
 *   Optional identifier (defaults to the current user's IP address).
1239
 */
1240
function flood_register_event($name, $window = 3600, $identifier = NULL) {
1241
  if (!isset($identifier)) {
1242
    $identifier = ip_address();
1243
  }
1244
  db_insert('flood')
1245
    ->fields(array(
1246
      'event' => $name,
1247
      'identifier' => $identifier,
1248
      'timestamp' => REQUEST_TIME,
1249
      'expiration' => REQUEST_TIME + $window,
1250
    ))
1251
    ->execute();
1252
}
1253

    
1254
/**
1255
 * Makes the flood control mechanism forget an event for the current visitor.
1256
 *
1257
 * @param $name
1258
 *   The name of an event.
1259
 * @param $identifier
1260
 *   Optional identifier (defaults to the current user's IP address).
1261
 */
1262
function flood_clear_event($name, $identifier = NULL) {
1263
  if (!isset($identifier)) {
1264
    $identifier = ip_address();
1265
  }
1266
  db_delete('flood')
1267
    ->condition('event', $name)
1268
    ->condition('identifier', $identifier)
1269
    ->execute();
1270
}
1271

    
1272
/**
1273
 * Checks whether a user is allowed to proceed with the specified event.
1274
 *
1275
 * Events can have thresholds saying that each user can only do that event
1276
 * a certain number of times in a time window. This function verifies that the
1277
 * current user has not exceeded this threshold.
1278
 *
1279
 * @param $name
1280
 *   The unique name of the event.
1281
 * @param $threshold
1282
 *   The maximum number of times each user can do this event per time window.
1283
 * @param $window
1284
 *   Number of seconds in the time window for this event (default is 3600
1285
 *   seconds, or 1 hour).
1286
 * @param $identifier
1287
 *   Unique identifier of the current user. Defaults to their IP address.
1288
 *
1289
 * @return
1290
 *   TRUE if the user is allowed to proceed. FALSE if they have exceeded the
1291
 *   threshold and should not be allowed to proceed.
1292
 */
1293
function flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) {
1294
  if (!isset($identifier)) {
1295
    $identifier = ip_address();
1296
  }
1297
  $number = db_query("SELECT COUNT(*) FROM {flood} WHERE event = :event AND identifier = :identifier AND timestamp > :timestamp", array(
1298
    ':event' => $name,
1299
    ':identifier' => $identifier,
1300
    ':timestamp' => REQUEST_TIME - $window))
1301
    ->fetchField();
1302
  return ($number < $threshold);
1303
}
1304

    
1305
/**
1306
 * @defgroup sanitization Sanitization functions
1307
 * @{
1308
 * Functions to sanitize values.
1309
 *
1310
 * See http://drupal.org/writing-secure-code for information
1311
 * on writing secure code.
1312
 */
1313

    
1314
/**
1315
 * Strips dangerous protocols (e.g. 'javascript:') from a URI.
1316
 *
1317
 * This function must be called for all URIs within user-entered input prior
1318
 * to being output to an HTML attribute value. It is often called as part of
1319
 * check_url() or filter_xss(), but those functions return an HTML-encoded
1320
 * string, so this function can be called independently when the output needs to
1321
 * be a plain-text string for passing to t(), l(), drupal_attributes(), or
1322
 * another function that will call check_plain() separately.
1323
 *
1324
 * @param $uri
1325
 *   A plain-text URI that might contain dangerous protocols.
1326
 *
1327
 * @return
1328
 *   A plain-text URI stripped of dangerous protocols. As with all plain-text
1329
 *   strings, this return value must not be output to an HTML page without
1330
 *   check_plain() being called on it. However, it can be passed to functions
1331
 *   expecting plain-text strings.
1332
 *
1333
 * @see check_url()
1334
 */
1335
function drupal_strip_dangerous_protocols($uri) {
1336
  static $allowed_protocols;
1337

    
1338
  if (!isset($allowed_protocols)) {
1339
    $allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal')));
1340
  }
1341

    
1342
  // Iteratively remove any invalid protocol found.
1343
  do {
1344
    $before = $uri;
1345
    $colonpos = strpos($uri, ':');
1346
    if ($colonpos > 0) {
1347
      // We found a colon, possibly a protocol. Verify.
1348
      $protocol = substr($uri, 0, $colonpos);
1349
      // If a colon is preceded by a slash, question mark or hash, it cannot
1350
      // possibly be part of the URL scheme. This must be a relative URL, which
1351
      // inherits the (safe) protocol of the base document.
1352
      if (preg_match('![/?#]!', $protocol)) {
1353
        break;
1354
      }
1355
      // Check if this is a disallowed protocol. Per RFC2616, section 3.2.3
1356
      // (URI Comparison) scheme comparison must be case-insensitive.
1357
      if (!isset($allowed_protocols[strtolower($protocol)])) {
1358
        $uri = substr($uri, $colonpos + 1);
1359
      }
1360
    }
1361
  } while ($before != $uri);
1362

    
1363
  return $uri;
1364
}
1365

    
1366
/**
1367
 * Strips dangerous protocols from a URI and encodes it for output to HTML.
1368
 *
1369
 * @param $uri
1370
 *   A plain-text URI that might contain dangerous protocols.
1371
 *
1372
 * @return
1373
 *   A URI stripped of dangerous protocols and encoded for output to an HTML
1374
 *   attribute value. Because it is already encoded, it should not be set as a
1375
 *   value within a $attributes array passed to drupal_attributes(), because
1376
 *   drupal_attributes() expects those values to be plain-text strings. To pass
1377
 *   a filtered URI to drupal_attributes(), call
1378
 *   drupal_strip_dangerous_protocols() instead.
1379
 *
1380
 * @see drupal_strip_dangerous_protocols()
1381
 */
1382
function check_url($uri) {
1383
  return check_plain(drupal_strip_dangerous_protocols($uri));
1384
}
1385

    
1386
/**
1387
 * Applies a very permissive XSS/HTML filter for admin-only use.
1388
 *
1389
 * Use only for fields where it is impractical to use the
1390
 * whole filter system, but where some (mainly inline) mark-up
1391
 * is desired (so check_plain() is not acceptable).
1392
 *
1393
 * Allows all tags that can be used inside an HTML body, save
1394
 * for scripts and styles.
1395
 */
1396
function filter_xss_admin($string) {
1397
  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'));
1398
}
1399

    
1400
/**
1401
 * Filters HTML to prevent cross-site-scripting (XSS) vulnerabilities.
1402
 *
1403
 * Based on kses by Ulf Harnhammar, see http://sourceforge.net/projects/kses.
1404
 * For examples of various XSS attacks, see: http://ha.ckers.org/xss.html.
1405
 *
1406
 * This code does four things:
1407
 * - Removes characters and constructs that can trick browsers.
1408
 * - Makes sure all HTML entities are well-formed.
1409
 * - Makes sure all HTML tags and attributes are well-formed.
1410
 * - Makes sure no HTML tags contain URLs with a disallowed protocol (e.g.
1411
 *   javascript:).
1412
 *
1413
 * @param $string
1414
 *   The string with raw HTML in it. It will be stripped of everything that can
1415
 *   cause an XSS attack.
1416
 * @param $allowed_tags
1417
 *   An array of allowed tags.
1418
 *
1419
 * @return
1420
 *   An XSS safe version of $string, or an empty string if $string is not
1421
 *   valid UTF-8.
1422
 *
1423
 * @see drupal_validate_utf8()
1424
 */
1425
function filter_xss($string, $allowed_tags = array('a', 'em', 'strong', 'cite', 'blockquote', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd')) {
1426
  // Only operate on valid UTF-8 strings. This is necessary to prevent cross
1427
  // site scripting issues on Internet Explorer 6.
1428
  if (!drupal_validate_utf8($string)) {
1429
    return '';
1430
  }
1431
  // Store the text format.
1432
  _filter_xss_split($allowed_tags, TRUE);
1433
  // Remove NULL characters (ignored by some browsers).
1434
  $string = str_replace(chr(0), '', $string);
1435
  // Remove Netscape 4 JS entities.
1436
  $string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
1437

    
1438
  // Defuse all HTML entities.
1439
  $string = str_replace('&', '&amp;', $string);
1440
  // Change back only well-formed entities in our whitelist:
1441
  // Decimal numeric entities.
1442
  $string = preg_replace('/&amp;#([0-9]+;)/', '&#\1', $string);
1443
  // Hexadecimal numeric entities.
1444
  $string = preg_replace('/&amp;#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\1', $string);
1445
  // Named entities.
1446
  $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string);
1447

    
1448
  return preg_replace_callback('%
1449
    (
1450
    <(?=[^a-zA-Z!/])  # a lone <
1451
    |                 # or
1452
    <!--.*?-->        # a comment
1453
    |                 # or
1454
    <[^>]*(>|$)       # a string that starts with a <, up until the > or the end of the string
1455
    |                 # or
1456
    >                 # just a >
1457
    )%x', '_filter_xss_split', $string);
1458
}
1459

    
1460
/**
1461
 * Processes an HTML tag.
1462
 *
1463
 * @param $m
1464
 *   An array with various meaning depending on the value of $store.
1465
 *   If $store is TRUE then the array contains the allowed tags.
1466
 *   If $store is FALSE then the array has one element, the HTML tag to process.
1467
 * @param $store
1468
 *   Whether to store $m.
1469
 *
1470
 * @return
1471
 *   If the element isn't allowed, an empty string. Otherwise, the cleaned up
1472
 *   version of the HTML element.
1473
 */
1474
function _filter_xss_split($m, $store = FALSE) {
1475
  static $allowed_html;
1476

    
1477
  if ($store) {
1478
    $allowed_html = array_flip($m);
1479
    return;
1480
  }
1481

    
1482
  $string = $m[1];
1483

    
1484
  if (substr($string, 0, 1) != '<') {
1485
    // We matched a lone ">" character.
1486
    return '&gt;';
1487
  }
1488
  elseif (strlen($string) == 1) {
1489
    // We matched a lone "<" character.
1490
    return '&lt;';
1491
  }
1492

    
1493
  if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
1494
    // Seriously malformed.
1495
    return '';
1496
  }
1497

    
1498
  $slash = trim($matches[1]);
1499
  $elem = &$matches[2];
1500
  $attrlist = &$matches[3];
1501
  $comment = &$matches[4];
1502

    
1503
  if ($comment) {
1504
    $elem = '!--';
1505
  }
1506

    
1507
  if (!isset($allowed_html[strtolower($elem)])) {
1508
    // Disallowed HTML element.
1509
    return '';
1510
  }
1511

    
1512
  if ($comment) {
1513
    return $comment;
1514
  }
1515

    
1516
  if ($slash != '') {
1517
    return "</$elem>";
1518
  }
1519

    
1520
  // Is there a closing XHTML slash at the end of the attributes?
1521
  $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
1522
  $xhtml_slash = $count ? ' /' : '';
1523

    
1524
  // Clean up attributes.
1525
  $attr2 = implode(' ', _filter_xss_attributes($attrlist));
1526
  $attr2 = preg_replace('/[<>]/', '', $attr2);
1527
  $attr2 = strlen($attr2) ? ' ' . $attr2 : '';
1528

    
1529
  return "<$elem$attr2$xhtml_slash>";
1530
}
1531

    
1532
/**
1533
 * Processes a string of HTML attributes.
1534
 *
1535
 * @return
1536
 *   Cleaned up version of the HTML attributes.
1537
 */
1538
function _filter_xss_attributes($attr) {
1539
  $attrarr = array();
1540
  $mode = 0;
1541
  $attrname = '';
1542

    
1543
  while (strlen($attr) != 0) {
1544
    // Was the last operation successful?
1545
    $working = 0;
1546

    
1547
    switch ($mode) {
1548
      case 0:
1549
        // Attribute name, href for instance.
1550
        if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
1551
          $attrname = strtolower($match[1]);
1552
          $skip = ($attrname == 'style' || substr($attrname, 0, 2) == 'on');
1553
          $working = $mode = 1;
1554
          $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
1555
        }
1556
        break;
1557

    
1558
      case 1:
1559
        // Equals sign or valueless ("selected").
1560
        if (preg_match('/^\s*=\s*/', $attr)) {
1561
          $working = 1; $mode = 2;
1562
          $attr = preg_replace('/^\s*=\s*/', '', $attr);
1563
          break;
1564
        }
1565

    
1566
        if (preg_match('/^\s+/', $attr)) {
1567
          $working = 1; $mode = 0;
1568
          if (!$skip) {
1569
            $attrarr[] = $attrname;
1570
          }
1571
          $attr = preg_replace('/^\s+/', '', $attr);
1572
        }
1573
        break;
1574

    
1575
      case 2:
1576
        // Attribute value, a URL after href= for instance.
1577
        if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
1578
          $thisval = filter_xss_bad_protocol($match[1]);
1579

    
1580
          if (!$skip) {
1581
            $attrarr[] = "$attrname=\"$thisval\"";
1582
          }
1583
          $working = 1;
1584
          $mode = 0;
1585
          $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
1586
          break;
1587
        }
1588

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

    
1592
          if (!$skip) {
1593
            $attrarr[] = "$attrname='$thisval'";
1594
          }
1595
          $working = 1; $mode = 0;
1596
          $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
1597
          break;
1598
        }
1599

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

    
1603
          if (!$skip) {
1604
            $attrarr[] = "$attrname=\"$thisval\"";
1605
          }
1606
          $working = 1; $mode = 0;
1607
          $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
1608
        }
1609
        break;
1610
    }
1611

    
1612
    if ($working == 0) {
1613
      // Not well formed; remove and try again.
1614
      $attr = preg_replace('/
1615
        ^
1616
        (
1617
        "[^"]*("|$)     # - a string that starts with a double quote, up until the next double quote or the end of the string
1618
        |               # or
1619
        \'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
1620
        |               # or
1621
        \S              # - a non-whitespace character
1622
        )*              # any number of the above three
1623
        \s*             # any number of whitespaces
1624
        /x', '', $attr);
1625
      $mode = 0;
1626
    }
1627
  }
1628

    
1629
  // The attribute list ends with a valueless attribute like "selected".
1630
  if ($mode == 1 && !$skip) {
1631
    $attrarr[] = $attrname;
1632
  }
1633
  return $attrarr;
1634
}
1635

    
1636
/**
1637
 * Processes an HTML attribute value and strips dangerous protocols from URLs.
1638
 *
1639
 * @param $string
1640
 *   The string with the attribute value.
1641
 * @param $decode
1642
 *   (deprecated) Whether to decode entities in the $string. Set to FALSE if the
1643
 *   $string is in plain text, TRUE otherwise. Defaults to TRUE. This parameter
1644
 *   is deprecated and will be removed in Drupal 8. To process a plain-text URI,
1645
 *   call drupal_strip_dangerous_protocols() or check_url() instead.
1646
 *
1647
 * @return
1648
 *   Cleaned up and HTML-escaped version of $string.
1649
 */
1650
function filter_xss_bad_protocol($string, $decode = TRUE) {
1651
  // Get the plain text representation of the attribute value (i.e. its meaning).
1652
  // @todo Remove the $decode parameter in Drupal 8, and always assume an HTML
1653
  //   string that needs decoding.
1654
  if ($decode) {
1655
    if (!function_exists('decode_entities')) {
1656
      require_once DRUPAL_ROOT . '/includes/unicode.inc';
1657
    }
1658

    
1659
    $string = decode_entities($string);
1660
  }
1661
  return check_plain(drupal_strip_dangerous_protocols($string));
1662
}
1663

    
1664
/**
1665
 * @} End of "defgroup sanitization".
1666
 */
1667

    
1668
/**
1669
 * @defgroup format Formatting
1670
 * @{
1671
 * Functions to format numbers, strings, dates, etc.
1672
 */
1673

    
1674
/**
1675
 * Formats an RSS channel.
1676
 *
1677
 * Arbitrary elements may be added using the $args associative array.
1678
 */
1679
function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
1680
  global $language_content;
1681
  $langcode = $langcode ? $langcode : $language_content->language;
1682

    
1683
  $output = "<channel>\n";
1684
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1685
  $output .= ' <link>' . check_url($link) . "</link>\n";
1686

    
1687
  // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
1688
  // We strip all HTML tags, but need to prevent double encoding from properly
1689
  // escaped source data (such as &amp becoming &amp;amp;).
1690
  $output .= ' <description>' . check_plain(decode_entities(strip_tags($description))) . "</description>\n";
1691
  $output .= ' <language>' . check_plain($langcode) . "</language>\n";
1692
  $output .= format_xml_elements($args);
1693
  $output .= $items;
1694
  $output .= "</channel>\n";
1695

    
1696
  return $output;
1697
}
1698

    
1699
/**
1700
 * Formats a single RSS item.
1701
 *
1702
 * Arbitrary elements may be added using the $args associative array.
1703
 */
1704
function format_rss_item($title, $link, $description, $args = array()) {
1705
  $output = "<item>\n";
1706
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1707
  $output .= ' <link>' . check_url($link) . "</link>\n";
1708
  $output .= ' <description>' . check_plain($description) . "</description>\n";
1709
  $output .= format_xml_elements($args);
1710
  $output .= "</item>\n";
1711

    
1712
  return $output;
1713
}
1714

    
1715
/**
1716
 * Formats XML elements.
1717
 *
1718
 * @param $array
1719
 *   An array where each item represents an element and is either a:
1720
 *   - (key => value) pair (<key>value</key>)
1721
 *   - Associative array with fields:
1722
 *     - 'key': element name
1723
 *     - 'value': element contents
1724
 *     - 'attributes': associative array of element attributes
1725
 *
1726
 * In both cases, 'value' can be a simple string, or it can be another array
1727
 * with the same format as $array itself for nesting.
1728
 */
1729
function format_xml_elements($array) {
1730
  $output = '';
1731
  foreach ($array as $key => $value) {
1732
    if (is_numeric($key)) {
1733
      if ($value['key']) {
1734
        $output .= ' <' . $value['key'];
1735
        if (isset($value['attributes']) && is_array($value['attributes'])) {
1736
          $output .= drupal_attributes($value['attributes']);
1737
        }
1738

    
1739
        if (isset($value['value']) && $value['value'] != '') {
1740
          $output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) . '</' . $value['key'] . ">\n";
1741
        }
1742
        else {
1743
          $output .= " />\n";
1744
        }
1745
      }
1746
    }
1747
    else {
1748
      $output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</$key>\n";
1749
    }
1750
  }
1751
  return $output;
1752
}
1753

    
1754
/**
1755
 * Formats a string containing a count of items.
1756
 *
1757
 * This function ensures that the string is pluralized correctly. Since t() is
1758
 * called by this function, make sure not to pass already-localized strings to
1759
 * it.
1760
 *
1761
 * For example:
1762
 * @code
1763
 *   $output = format_plural($node->comment_count, '1 comment', '@count comments');
1764
 * @endcode
1765
 *
1766
 * Example with additional replacements:
1767
 * @code
1768
 *   $output = format_plural($update_count,
1769
 *     'Changed the content type of 1 post from %old-type to %new-type.',
1770
 *     'Changed the content type of @count posts from %old-type to %new-type.',
1771
 *     array('%old-type' => $info->old_type, '%new-type' => $info->new_type));
1772
 * @endcode
1773
 *
1774
 * @param $count
1775
 *   The item count to display.
1776
 * @param $singular
1777
 *   The string for the singular case. Make sure it is clear this is singular,
1778
 *   to ease translation (e.g. use "1 new comment" instead of "1 new"). Do not
1779
 *   use @count in the singular string.
1780
 * @param $plural
1781
 *   The string for the plural case. Make sure it is clear this is plural, to
1782
 *   ease translation. Use @count in place of the item count, as in
1783
 *   "@count new comments".
1784
 * @param $args
1785
 *   An associative array of replacements to make after translation. Instances
1786
 *   of any key in this array are replaced with the corresponding value.
1787
 *   Based on the first character of the key, the value is escaped and/or
1788
 *   themed. See format_string(). Note that you do not need to include @count
1789
 *   in this array; this replacement is done automatically for the plural case.
1790
 * @param $options
1791
 *   An associative array of additional options. See t() for allowed keys.
1792
 *
1793
 * @return
1794
 *   A translated string.
1795
 *
1796
 * @see t()
1797
 * @see format_string()
1798
 */
1799
function format_plural($count, $singular, $plural, array $args = array(), array $options = array()) {
1800
  $args['@count'] = $count;
1801
  if ($count == 1) {
1802
    return t($singular, $args, $options);
1803
  }
1804

    
1805
  // Get the plural index through the gettext formula.
1806
  $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, isset($options['langcode']) ? $options['langcode'] : NULL) : -1;
1807
  // If the index cannot be computed, use the plural as a fallback (which
1808
  // allows for most flexiblity with the replaceable @count value).
1809
  if ($index < 0) {
1810
    return t($plural, $args, $options);
1811
  }
1812
  else {
1813
    switch ($index) {
1814
      case "0":
1815
        return t($singular, $args, $options);
1816
      case "1":
1817
        return t($plural, $args, $options);
1818
      default:
1819
        unset($args['@count']);
1820
        $args['@count[' . $index . ']'] = $count;
1821
        return t(strtr($plural, array('@count' => '@count[' . $index . ']')), $args, $options);
1822
    }
1823
  }
1824
}
1825

    
1826
/**
1827
 * Parses a given byte count.
1828
 *
1829
 * @param $size
1830
 *   A size expressed as a number of bytes with optional SI or IEC binary unit
1831
 *   prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).
1832
 *
1833
 * @return
1834
 *   An integer representation of the size in bytes.
1835
 */
1836
function parse_size($size) {
1837
  $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size.
1838
  $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size.
1839
  if ($unit) {
1840
    // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by.
1841
    return round($size * pow(DRUPAL_KILOBYTE, stripos('bkmgtpezy', $unit[0])));
1842
  }
1843
  else {
1844
    return round($size);
1845
  }
1846
}
1847

    
1848
/**
1849
 * Generates a string representation for the given byte count.
1850
 *
1851
 * @param $size
1852
 *   A size in bytes.
1853
 * @param $langcode
1854
 *   Optional language code to translate to a language other than what is used
1855
 *   to display the page.
1856
 *
1857
 * @return
1858
 *   A translated string representation of the size.
1859
 */
1860
function format_size($size, $langcode = NULL) {
1861
  if ($size < DRUPAL_KILOBYTE) {
1862
    return format_plural($size, '1 byte', '@count bytes', array(), array('langcode' => $langcode));
1863
  }
1864
  else {
1865
    $size = $size / DRUPAL_KILOBYTE; // Convert bytes to kilobytes.
1866
    $units = array(
1867
      t('@size KB', array(), array('langcode' => $langcode)),
1868
      t('@size MB', array(), array('langcode' => $langcode)),
1869
      t('@size GB', array(), array('langcode' => $langcode)),
1870
      t('@size TB', array(), array('langcode' => $langcode)),
1871
      t('@size PB', array(), array('langcode' => $langcode)),
1872
      t('@size EB', array(), array('langcode' => $langcode)),
1873
      t('@size ZB', array(), array('langcode' => $langcode)),
1874
      t('@size YB', array(), array('langcode' => $langcode)),
1875
    );
1876
    foreach ($units as $unit) {
1877
      if (round($size, 2) >= DRUPAL_KILOBYTE) {
1878
        $size = $size / DRUPAL_KILOBYTE;
1879
      }
1880
      else {
1881
        break;
1882
      }
1883
    }
1884
    return str_replace('@size', round($size, 2), $unit);
1885
  }
1886
}
1887

    
1888
/**
1889
 * Formats a time interval with the requested granularity.
1890
 *
1891
 * @param $interval
1892
 *   The length of the interval in seconds.
1893
 * @param $granularity
1894
 *   How many different units to display in the string.
1895
 * @param $langcode
1896
 *   Optional language code to translate to a language other than
1897
 *   what is used to display the page.
1898
 *
1899
 * @return
1900
 *   A translated string representation of the interval.
1901
 */
1902
function format_interval($interval, $granularity = 2, $langcode = NULL) {
1903
  $units = array(
1904
    '1 year|@count years' => 31536000,
1905
    '1 month|@count months' => 2592000,
1906
    '1 week|@count weeks' => 604800,
1907
    '1 day|@count days' => 86400,
1908
    '1 hour|@count hours' => 3600,
1909
    '1 min|@count min' => 60,
1910
    '1 sec|@count sec' => 1
1911
  );
1912
  $output = '';
1913
  foreach ($units as $key => $value) {
1914
    $key = explode('|', $key);
1915
    if ($interval >= $value) {
1916
      $output .= ($output ? ' ' : '') . format_plural(floor($interval / $value), $key[0], $key[1], array(), array('langcode' => $langcode));
1917
      $interval %= $value;
1918
      $granularity--;
1919
    }
1920

    
1921
    if ($granularity == 0) {
1922
      break;
1923
    }
1924
  }
1925
  return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
1926
}
1927

    
1928
/**
1929
 * Formats a date, using a date type or a custom date format string.
1930
 *
1931
 * @param $timestamp
1932
 *   A UNIX timestamp to format.
1933
 * @param $type
1934
 *   (optional) The format to use, one of:
1935
 *   - 'short', 'medium', or 'long' (the corresponding built-in date formats).
1936
 *   - The name of a date type defined by a module in hook_date_format_types(),
1937
 *     if it's been assigned a format.
1938
 *   - The machine name of an administrator-defined date format.
1939
 *   - 'custom', to use $format.
1940
 *   Defaults to 'medium'.
1941
 * @param $format
1942
 *   (optional) If $type is 'custom', a PHP date format string suitable for
1943
 *   input to date(). Use a backslash to escape ordinary text, so it does not
1944
 *   get interpreted as date format characters.
1945
 * @param $timezone
1946
 *   (optional) Time zone identifier, as described at
1947
 *   http://php.net/manual/timezones.php Defaults to the time zone used to
1948
 *   display the page.
1949
 * @param $langcode
1950
 *   (optional) Language code to translate to. Defaults to the language used to
1951
 *   display the page.
1952
 *
1953
 * @return
1954
 *   A translated date string in the requested format.
1955
 */
1956
function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
1957
  // Use the advanced drupal_static() pattern, since this is called very often.
1958
  static $drupal_static_fast;
1959
  if (!isset($drupal_static_fast)) {
1960
    $drupal_static_fast['timezones'] = &drupal_static(__FUNCTION__);
1961
  }
1962
  $timezones = &$drupal_static_fast['timezones'];
1963

    
1964
  if (!isset($timezone)) {
1965
    $timezone = date_default_timezone_get();
1966
  }
1967
  // Store DateTimeZone objects in an array rather than repeatedly
1968
  // constructing identical objects over the life of a request.
1969
  if (!isset($timezones[$timezone])) {
1970
    $timezones[$timezone] = timezone_open($timezone);
1971
  }
1972

    
1973
  // Use the default langcode if none is set.
1974
  global $language;
1975
  if (empty($langcode)) {
1976
    $langcode = isset($language->language) ? $language->language : 'en';
1977
  }
1978

    
1979
  switch ($type) {
1980
    case 'short':
1981
      $format = variable_get('date_format_short', 'm/d/Y - H:i');
1982
      break;
1983

    
1984
    case 'long':
1985
      $format = variable_get('date_format_long', 'l, F j, Y - H:i');
1986
      break;
1987

    
1988
    case 'custom':
1989
      // No change to format.
1990
      break;
1991

    
1992
    case 'medium':
1993
    default:
1994
      // Retrieve the format of the custom $type passed.
1995
      if ($type != 'medium') {
1996
        $format = variable_get('date_format_' . $type, '');
1997
      }
1998
      // Fall back to 'medium'.
1999
      if ($format === '') {
2000
        $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
2001
      }
2002
      break;
2003
  }
2004

    
2005
  // Create a DateTime object from the timestamp.
2006
  $date_time = date_create('@' . $timestamp);
2007
  // Set the time zone for the DateTime object.
2008
  date_timezone_set($date_time, $timezones[$timezone]);
2009

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

    
2017
  // Call date_format().
2018
  $format = date_format($date_time, $format);
2019

    
2020
  // Pass the langcode to _format_date_callback().
2021
  _format_date_callback(NULL, $langcode);
2022

    
2023
  // Translate the marked sequences.
2024
  return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);
2025
}
2026

    
2027
/**
2028
 * Returns an ISO8601 formatted date based on the given date.
2029
 *
2030
 * Callback for use within hook_rdf_mapping() implementations.
2031
 *
2032
 * @param $date
2033
 *   A UNIX timestamp.
2034
 *
2035
 * @return string
2036
 *   An ISO8601 formatted date.
2037
 */
2038
function date_iso8601($date) {
2039
  // The DATE_ISO8601 constant cannot be used here because it does not match
2040
  // date('c') and produces invalid RDF markup.
2041
  return date('c', $date);
2042
}
2043

    
2044
/**
2045
 * Translates a formatted date string.
2046
 *
2047
 * Callback for preg_replace_callback() within format_date().
2048
 */
2049
function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
2050
  // We cache translations to avoid redundant and rather costly calls to t().
2051
  static $cache, $langcode;
2052

    
2053
  if (!isset($matches)) {
2054
    $langcode = $new_langcode;
2055
    return;
2056
  }
2057

    
2058
  $code = $matches[1];
2059
  $string = $matches[2];
2060

    
2061
  if (!isset($cache[$langcode][$code][$string])) {
2062
    $options = array(
2063
      'langcode' => $langcode,
2064
    );
2065

    
2066
    if ($code == 'F') {
2067
      $options['context'] = 'Long month name';
2068
    }
2069

    
2070
    if ($code == '') {
2071
      $cache[$langcode][$code][$string] = $string;
2072
    }
2073
    else {
2074
      $cache[$langcode][$code][$string] = t($string, array(), $options);
2075
    }
2076
  }
2077
  return $cache[$langcode][$code][$string];
2078
}
2079

    
2080
/**
2081
 * Format a username.
2082
 *
2083
 * This is also the label callback implementation of
2084
 * callback_entity_info_label() for user_entity_info().
2085
 *
2086
 * By default, the passed-in object's 'name' property is used if it exists, or
2087
 * else, the site-defined value for the 'anonymous' variable. However, a module
2088
 * may override this by implementing hook_username_alter(&$name, $account).
2089
 *
2090
 * @see hook_username_alter()
2091
 *
2092
 * @param $account
2093
 *   The account object for the user whose name is to be formatted.
2094
 *
2095
 * @return
2096
 *   An unsanitized string with the username to display. The code receiving
2097
 *   this result must ensure that check_plain() is called on it before it is
2098
 *   printed to the page.
2099
 */
2100
function format_username($account) {
2101
  $name = !empty($account->name) ? $account->name : variable_get('anonymous', t('Anonymous'));
2102
  drupal_alter('username', $name, $account);
2103
  return $name;
2104
}
2105

    
2106
/**
2107
 * @} End of "defgroup format".
2108
 */
2109

    
2110
/**
2111
 * Generates an internal or external URL.
2112
 *
2113
 * When creating links in modules, consider whether l() could be a better
2114
 * alternative than url().
2115
 *
2116
 * @param $path
2117
 *   (optional) The internal path or external URL being linked to, such as
2118
 *   "node/34" or "http://example.com/foo". The default value is equivalent to
2119
 *   passing in '<front>'. A few notes:
2120
 *   - If you provide a full URL, it will be considered an external URL.
2121
 *   - If you provide only the path (e.g. "node/34"), it will be
2122
 *     considered an internal link. In this case, it should be a system URL,
2123
 *     and it will be replaced with the alias, if one exists. Additional query
2124
 *     arguments for internal paths must be supplied in $options['query'], not
2125
 *     included in $path.
2126
 *   - If you provide an internal path and $options['alias'] is set to TRUE, the
2127
 *     path is assumed already to be the correct path alias, and the alias is
2128
 *     not looked up.
2129
 *   - The special string '<front>' generates a link to the site's base URL.
2130
 *   - If your external URL contains a query (e.g. http://example.com/foo?a=b),
2131
 *     then you can either URL encode the query keys and values yourself and
2132
 *     include them in $path, or use $options['query'] to let this function
2133
 *     URL encode them.
2134
 * @param $options
2135
 *   (optional) An associative array of additional options, with the following
2136
 *   elements:
2137
 *   - 'query': An array of query key/value-pairs (without any URL-encoding) to
2138
 *     append to the URL.
2139
 *   - 'fragment': A fragment identifier (named anchor) to append to the URL.
2140
 *     Do not include the leading '#' character.
2141
 *   - 'absolute': Defaults to FALSE. Whether to force the output to be an
2142
 *     absolute link (beginning with http:). Useful for links that will be
2143
 *     displayed outside the site, such as in an RSS feed.
2144
 *   - 'alias': Defaults to FALSE. Whether the given path is a URL alias
2145
 *     already.
2146
 *   - 'external': Whether the given path is an external URL.
2147
 *   - 'language': An optional language object. If the path being linked to is
2148
 *     internal to the site, $options['language'] is used to look up the alias
2149
 *     for the URL. If $options['language'] is omitted, the global $language_url
2150
 *     will be used.
2151
 *   - 'https': Whether this URL should point to a secure location. If not
2152
 *     defined, the current scheme is used, so the user stays on HTTP or HTTPS
2153
 *     respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but HTTPS can
2154
 *     only be enforced when the variable 'https' is set to TRUE.
2155
 *   - 'base_url': Only used internally, to modify the base URL when a language
2156
 *     dependent URL requires so.
2157
 *   - 'prefix': Only used internally, to modify the path when a language
2158
 *     dependent URL requires so.
2159
 *   - 'script': The script filename in Drupal's root directory to use when
2160
 *     clean URLs are disabled, such as 'index.php'. Defaults to an empty
2161
 *     string, as most modern web servers automatically find 'index.php'. If
2162
 *     clean URLs are disabled, the value of $path is appended as query
2163
 *     parameter 'q' to $options['script'] in the returned URL. When deploying
2164
 *     Drupal on a web server that cannot be configured to automatically find
2165
 *     index.php, then hook_url_outbound_alter() can be implemented to force
2166
 *     this value to 'index.php'.
2167
 *   - 'entity_type': The entity type of the object that called url(). Only
2168
 *     set if url() is invoked by entity_uri().
2169
 *   - 'entity': The entity object (such as a node) for which the URL is being
2170
 *     generated. Only set if url() is invoked by entity_uri().
2171
 *
2172
 * @return
2173
 *   A string containing a URL to the given path.
2174
 */
2175
function url($path = NULL, array $options = array()) {
2176
  // Merge in defaults.
2177
  $options += array(
2178
    'fragment' => '',
2179
    'query' => array(),
2180
    'absolute' => FALSE,
2181
    'alias' => FALSE,
2182
    'prefix' => ''
2183
  );
2184

    
2185
  if (!isset($options['external'])) {
2186
    // Return an external link if $path contains an allowed absolute URL. Only
2187
    // call the slow drupal_strip_dangerous_protocols() if $path contains a ':'
2188
    // before any / ? or #. Note: we could use url_is_external($path) here, but
2189
    // that would require another function call, and performance inside url() is
2190
    // critical.
2191
    $colonpos = strpos($path, ':');
2192
    $options['external'] = ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && drupal_strip_dangerous_protocols($path) == $path);
2193
  }
2194

    
2195
  // Preserve the original path before altering or aliasing.
2196
  $original_path = $path;
2197

    
2198
  // Allow other modules to alter the outbound URL and options.
2199
  drupal_alter('url_outbound', $path, $options, $original_path);
2200

    
2201
  if (isset($options['fragment']) && $options['fragment'] !== '') {
2202
    $options['fragment'] = '#' . $options['fragment'];
2203
  }
2204

    
2205
  if ($options['external']) {
2206
    // Split off the fragment.
2207
    if (strpos($path, '#') !== FALSE) {
2208
      list($path, $old_fragment) = explode('#', $path, 2);
2209
      // If $options contains no fragment, take it over from the path.
2210
      if (isset($old_fragment) && !$options['fragment']) {
2211
        $options['fragment'] = '#' . $old_fragment;
2212
      }
2213
    }
2214
    // Append the query.
2215
    if ($options['query']) {
2216
      $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($options['query']);
2217
    }
2218
    if (isset($options['https']) && variable_get('https', FALSE)) {
2219
      if ($options['https'] === TRUE) {
2220
        $path = str_replace('http://', 'https://', $path);
2221
      }
2222
      elseif ($options['https'] === FALSE) {
2223
        $path = str_replace('https://', 'http://', $path);
2224
      }
2225
    }
2226
    // Reassemble.
2227
    return $path . $options['fragment'];
2228
  }
2229

    
2230
  global $base_url, $base_secure_url, $base_insecure_url;
2231

    
2232
  // The base_url might be rewritten from the language rewrite in domain mode.
2233
  if (!isset($options['base_url'])) {
2234
    if (isset($options['https']) && variable_get('https', FALSE)) {
2235
      if ($options['https'] === TRUE) {
2236
        $options['base_url'] = $base_secure_url;
2237
        $options['absolute'] = TRUE;
2238
      }
2239
      elseif ($options['https'] === FALSE) {
2240
        $options['base_url'] = $base_insecure_url;
2241
        $options['absolute'] = TRUE;
2242
      }
2243
    }
2244
    else {
2245
      $options['base_url'] = $base_url;
2246
    }
2247
  }
2248

    
2249
  // The special path '<front>' links to the default front page.
2250
  if ($path == '<front>') {
2251
    $path = '';
2252
  }
2253
  elseif (!empty($path) && !$options['alias']) {
2254
    $language = isset($options['language']) && isset($options['language']->language) ? $options['language']->language : '';
2255
    $alias = drupal_get_path_alias($original_path, $language);
2256
    if ($alias != $original_path) {
2257
      $path = $alias;
2258
    }
2259
  }
2260

    
2261
  $base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
2262
  $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
2263

    
2264
  // With Clean URLs.
2265
  if (!empty($GLOBALS['conf']['clean_url'])) {
2266
    $path = drupal_encode_path($prefix . $path);
2267
    if ($options['query']) {
2268
      return $base . $path . '?' . drupal_http_build_query($options['query']) . $options['fragment'];
2269
    }
2270
    else {
2271
      return $base . $path . $options['fragment'];
2272
    }
2273
  }
2274
  // Without Clean URLs.
2275
  else {
2276
    $path = $prefix . $path;
2277
    $query = array();
2278
    if (!empty($path)) {
2279
      $query['q'] = $path;
2280
    }
2281
    if ($options['query']) {
2282
      // We do not use array_merge() here to prevent overriding $path via query
2283
      // parameters.
2284
      $query += $options['query'];
2285
    }
2286
    $query = $query ? ('?' . drupal_http_build_query($query)) : '';
2287
    $script = isset($options['script']) ? $options['script'] : '';
2288
    return $base . $script . $query . $options['fragment'];
2289
  }
2290
}
2291

    
2292
/**
2293
 * Returns TRUE if a path is external to Drupal (e.g. http://example.com).
2294
 *
2295
 * If a path cannot be assessed by Drupal's menu handler, then we must
2296
 * treat it as potentially insecure.
2297
 *
2298
 * @param $path
2299
 *   The internal path or external URL being linked to, such as "node/34" or
2300
 *   "http://example.com/foo".
2301
 *
2302
 * @return
2303
 *   Boolean TRUE or FALSE, where TRUE indicates an external path.
2304
 */
2305
function url_is_external($path) {
2306
  $colonpos = strpos($path, ':');
2307
  // Avoid calling drupal_strip_dangerous_protocols() if there is any
2308
  // slash (/), hash (#) or question_mark (?) before the colon (:)
2309
  // occurrence - if any - as this would clearly mean it is not a URL.
2310
  return $colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && drupal_strip_dangerous_protocols($path) == $path;
2311
}
2312

    
2313
/**
2314
 * Formats an attribute string for an HTTP header.
2315
 *
2316
 * @param $attributes
2317
 *   An associative array of attributes such as 'rel'.
2318
 *
2319
 * @return
2320
 *   A ; separated string ready for insertion in a HTTP header. No escaping is
2321
 *   performed for HTML entities, so this string is not safe to be printed.
2322
 *
2323
 * @see drupal_add_http_header()
2324
 */
2325
function drupal_http_header_attributes(array $attributes = array()) {
2326
  foreach ($attributes as $attribute => &$data) {
2327
    if (is_array($data)) {
2328
      $data = implode(' ', $data);
2329
    }
2330
    $data = $attribute . '="' . $data . '"';
2331
  }
2332
  return $attributes ? ' ' . implode('; ', $attributes) : '';
2333
}
2334

    
2335
/**
2336
 * Converts an associative array to an XML/HTML tag attribute string.
2337
 *
2338
 * Each array key and its value will be formatted into an attribute string.
2339
 * If a value is itself an array, then its elements are concatenated to a single
2340
 * space-delimited string (for example, a class attribute with multiple values).
2341
 *
2342
 * Attribute values are sanitized by running them through check_plain().
2343
 * Attribute names are not automatically sanitized. When using user-supplied
2344
 * attribute names, it is strongly recommended to allow only white-listed names,
2345
 * since certain attributes carry security risks and can be abused.
2346
 *
2347
 * Examples of security aspects when using drupal_attributes:
2348
 * @code
2349
 *   // By running the value in the following statement through check_plain,
2350
 *   // the malicious script is neutralized.
2351
 *   drupal_attributes(array('title' => t('<script>steal_cookie();</script>')));
2352
 *
2353
 *   // The statement below demonstrates dangerous use of drupal_attributes, and
2354
 *   // will return an onmouseout attribute with JavaScript code that, when used
2355
 *   // as attribute in a tag, will cause users to be redirected to another site.
2356
 *   //
2357
 *   // In this case, the 'onmouseout' attribute should not be whitelisted --
2358
 *   // you don't want users to have the ability to add this attribute or others
2359
 *   // that take JavaScript commands.
2360
 *   drupal_attributes(array('onmouseout' => 'window.location="http://malicious.com/";')));
2361
 * @endcode
2362
 *
2363
 * @param $attributes
2364
 *   An associative array of key-value pairs to be converted to attributes.
2365
 *
2366
 * @return
2367
 *   A string ready for insertion in a tag (starts with a space).
2368
 *
2369
 * @ingroup sanitization
2370
 */
2371
function drupal_attributes(array $attributes = array()) {
2372
  foreach ($attributes as $attribute => &$data) {
2373
    $data = implode(' ', (array) $data);
2374
    $data = $attribute . '="' . check_plain($data) . '"';
2375
  }
2376
  return $attributes ? ' ' . implode(' ', $attributes) : '';
2377
}
2378

    
2379
/**
2380
 * Formats an internal or external URL link as an HTML anchor tag.
2381
 *
2382
 * This function correctly handles aliased paths and adds an 'active' class
2383
 * attribute to links that point to the current page (for theming), so all
2384
 * internal links output by modules should be generated by this function if
2385
 * possible.
2386
 *
2387
 * However, for links enclosed in translatable text you should use t() and
2388
 * embed the HTML anchor tag directly in the translated string. For example:
2389
 * @code
2390
 * t('Visit the <a href="@url">settings</a> page', array('@url' => url('admin')));
2391
 * @endcode
2392
 * This keeps the context of the link title ('settings' in the example) for
2393
 * translators.
2394
 *
2395
 * @param string $text
2396
 *   The translated link text for the anchor tag.
2397
 * @param string $path
2398
 *   The internal path or external URL being linked to, such as "node/34" or
2399
 *   "http://example.com/foo". After the url() function is called to construct
2400
 *   the URL from $path and $options, the resulting URL is passed through
2401
 *   check_plain() before it is inserted into the HTML anchor tag, to ensure
2402
 *   well-formed HTML. See url() for more information and notes.
2403
 * @param array $options
2404
 *   An associative array of additional options. Defaults to an empty array. It
2405
 *   may contain the following elements.
2406
 *   - 'attributes': An associative array of HTML attributes to apply to the
2407
 *     anchor tag. If element 'class' is included, it must be an array; 'title'
2408
 *     must be a string; other elements are more flexible, as they just need
2409
 *     to work in a call to drupal_attributes($options['attributes']).
2410
 *   - 'html' (default FALSE): Whether $text is HTML or just plain-text. For
2411
 *     example, to make an image tag into a link, this must be set to TRUE, or
2412
 *     you will see the escaped HTML image tag. $text is not sanitized if
2413
 *     'html' is TRUE. The calling function must ensure that $text is already
2414
 *     safe.
2415
 *   - 'language': An optional language object. If the path being linked to is
2416
 *     internal to the site, $options['language'] is used to determine whether
2417
 *     the link is "active", or pointing to the current page (the language as
2418
 *     well as the path must match). This element is also used by url().
2419
 *   - Additional $options elements used by the url() function.
2420
 *
2421
 * @return string
2422
 *   An HTML string containing a link to the given path.
2423
 *
2424
 * @see url()
2425
 */
2426
function l($text, $path, array $options = array()) {
2427
  global $language_url;
2428
  static $use_theme = NULL;
2429

    
2430
  // Merge in defaults.
2431
  $options += array(
2432
    'attributes' => array(),
2433
    'html' => FALSE,
2434
  );
2435

    
2436
  // Append active class.
2437
  if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
2438
      (empty($options['language']) || $options['language']->language == $language_url->language)) {
2439
    $options['attributes']['class'][] = 'active';
2440
  }
2441

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

    
2448
  // Determine if rendering of the link is to be done with a theme function
2449
  // or the inline default. Inline is faster, but if the theme system has been
2450
  // loaded and a module or theme implements a preprocess or process function
2451
  // or overrides the theme_link() function, then invoke theme(). Preliminary
2452
  // benchmarks indicate that invoking theme() can slow down the l() function
2453
  // by 20% or more, and that some of the link-heavy Drupal pages spend more
2454
  // than 10% of the total page request time in the l() function.
2455
  if (!isset($use_theme) && function_exists('theme')) {
2456
    // Allow edge cases to prevent theme initialization and force inline link
2457
    // rendering.
2458
    if (variable_get('theme_link', TRUE)) {
2459
      drupal_theme_initialize();
2460
      $registry = theme_get_registry(FALSE);
2461
      // We don't want to duplicate functionality that's in theme(), so any
2462
      // hint of a module or theme doing anything at all special with the 'link'
2463
      // theme hook should simply result in theme() being called. This includes
2464
      // the overriding of theme_link() with an alternate function or template,
2465
      // the presence of preprocess or process functions, or the presence of
2466
      // include files.
2467
      $use_theme = !isset($registry['link']['function']) || ($registry['link']['function'] != 'theme_link');
2468
      $use_theme = $use_theme || !empty($registry['link']['preprocess functions']) || !empty($registry['link']['process functions']) || !empty($registry['link']['includes']);
2469
    }
2470
    else {
2471
      $use_theme = FALSE;
2472
    }
2473
  }
2474
  if ($use_theme) {
2475
    return theme('link', array('text' => $text, 'path' => $path, 'options' => $options));
2476
  }
2477
  // The result of url() is a plain-text URL. Because we are using it here
2478
  // in an HTML argument context, we need to encode it properly.
2479
  return '<a href="' . check_plain(url($path, $options)) . '"' . drupal_attributes($options['attributes']) . '>' . ($options['html'] ? $text : check_plain($text)) . '</a>';
2480
}
2481

    
2482
/**
2483
 * Delivers a page callback result to the browser in the appropriate format.
2484
 *
2485
 * This function is most commonly called by menu_execute_active_handler(), but
2486
 * can also be called by error conditions such as drupal_not_found(),
2487
 * drupal_access_denied(), and drupal_site_offline().
2488
 *
2489
 * When a user requests a page, index.php calls menu_execute_active_handler(),
2490
 * which calls the 'page callback' function registered in hook_menu(). The page
2491
 * callback function can return one of:
2492
 * - NULL: to indicate no content.
2493
 * - An integer menu status constant: to indicate an error condition.
2494
 * - A string of HTML content.
2495
 * - A renderable array of content.
2496
 * Returning a renderable array rather than a string of HTML is preferred,
2497
 * because that provides modules with more flexibility in customizing the final
2498
 * result.
2499
 *
2500
 * When the page callback returns its constructed content to
2501
 * menu_execute_active_handler(), this function gets called. The purpose of
2502
 * this function is to determine the most appropriate 'delivery callback'
2503
 * function to route the content to. The delivery callback function then
2504
 * sends the content to the browser in the needed format. The default delivery
2505
 * callback is drupal_deliver_html_page(), which delivers the content as an HTML
2506
 * page, complete with blocks in addition to the content. This default can be
2507
 * overridden on a per menu router item basis by setting 'delivery callback' in
2508
 * hook_menu() or hook_menu_alter(), and can also be overridden on a per request
2509
 * basis in hook_page_delivery_callback_alter().
2510
 *
2511
 * For example, the same page callback function can be used for an HTML
2512
 * version of the page and an Ajax version of the page. The page callback
2513
 * function just needs to decide what content is to be returned and the
2514
 * delivery callback function will send it as an HTML page or an Ajax
2515
 * response, as appropriate.
2516
 *
2517
 * In order for page callbacks to be reusable in different delivery formats,
2518
 * they should not issue any "print" or "echo" statements, but instead just
2519
 * return content.
2520
 *
2521
 * Also note that this function does not perform access checks. The delivery
2522
 * callback function specified in hook_menu(), hook_menu_alter(), or
2523
 * hook_page_delivery_callback_alter() will be called even if the router item
2524
 * access checks fail. This is intentional (it is needed for JSON and other
2525
 * purposes), but it has security implications. Do not call this function
2526
 * directly unless you understand the security implications, and be careful in
2527
 * writing delivery callbacks, so that they do not violate security. See
2528
 * drupal_deliver_html_page() for an example of a delivery callback that
2529
 * respects security.
2530
 *
2531
 * @param $page_callback_result
2532
 *   The result of a page callback. Can be one of:
2533
 *   - NULL: to indicate no content.
2534
 *   - An integer menu status constant: to indicate an error condition.
2535
 *   - A string of HTML content.
2536
 *   - A renderable array of content.
2537
 * @param $default_delivery_callback
2538
 *   (Optional) If given, it is the name of a delivery function most likely
2539
 *   to be appropriate for the page request as determined by the calling
2540
 *   function (e.g., menu_execute_active_handler()). If not given, it is
2541
 *   determined from the menu router information of the current page.
2542
 *
2543
 * @see menu_execute_active_handler()
2544
 * @see hook_menu()
2545
 * @see hook_menu_alter()
2546
 * @see hook_page_delivery_callback_alter()
2547
 */
2548
function drupal_deliver_page($page_callback_result, $default_delivery_callback = NULL) {
2549
  if (!isset($default_delivery_callback) && ($router_item = menu_get_item())) {
2550
    $default_delivery_callback = $router_item['delivery_callback'];
2551
  }
2552
  $delivery_callback = !empty($default_delivery_callback) ? $default_delivery_callback : 'drupal_deliver_html_page';
2553
  // Give modules a chance to alter the delivery callback used, based on
2554
  // request-time context (e.g., HTTP request headers).
2555
  drupal_alter('page_delivery_callback', $delivery_callback);
2556
  if (function_exists($delivery_callback)) {
2557
    $delivery_callback($page_callback_result);
2558
  }
2559
  else {
2560
    // If a delivery callback is specified, but doesn't exist as a function,
2561
    // something is wrong, but don't print anything, since it's not known
2562
    // what format the response needs to be in.
2563
    watchdog('delivery callback not found', 'callback %callback not found: %q.', array('%callback' => $delivery_callback, '%q' => $_GET['q']), WATCHDOG_ERROR);
2564
  }
2565
}
2566

    
2567
/**
2568
 * Packages and sends the result of a page callback to the browser as HTML.
2569
 *
2570
 * @param $page_callback_result
2571
 *   The result of a page callback. Can be one of:
2572
 *   - NULL: to indicate no content.
2573
 *   - An integer menu status constant: to indicate an error condition.
2574
 *   - A string of HTML content.
2575
 *   - A renderable array of content.
2576
 *
2577
 * @see drupal_deliver_page()
2578
 */
2579
function drupal_deliver_html_page($page_callback_result) {
2580
  // Emit the correct charset HTTP header, but not if the page callback
2581
  // result is NULL, since that likely indicates that it printed something
2582
  // in which case, no further headers may be sent, and not if code running
2583
  // for this page request has already set the content type header.
2584
  if (isset($page_callback_result) && is_null(drupal_get_http_header('Content-Type'))) {
2585
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
2586
  }
2587

    
2588
  // Send appropriate HTTP-Header for browsers and search engines.
2589
  global $language;
2590
  drupal_add_http_header('Content-Language', $language->language);
2591

    
2592
  // Menu status constants are integers; page content is a string or array.
2593
  if (is_int($page_callback_result)) {
2594
    // @todo: Break these up into separate functions?
2595
    switch ($page_callback_result) {
2596
      case MENU_NOT_FOUND:
2597
        // Print a 404 page.
2598
        drupal_add_http_header('Status', '404 Not Found');
2599

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

    
2602
        // Check for and return a fast 404 page if configured.
2603
        drupal_fast_404();
2604

    
2605
        // Keep old path for reference, and to allow forms to redirect to it.
2606
        if (!isset($_GET['destination'])) {
2607
          $_GET['destination'] = $_GET['q'];
2608
        }
2609

    
2610
        $path = drupal_get_normal_path(variable_get('site_404', ''));
2611
        if ($path && $path != $_GET['q']) {
2612
          // Custom 404 handler. Set the active item in case there are tabs to
2613
          // display, or other dependencies on the path.
2614
          menu_set_active_item($path);
2615
          $return = menu_execute_active_handler($path, FALSE);
2616
        }
2617

    
2618
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2619
          // Standard 404 handler.
2620
          drupal_set_title(t('Page not found'));
2621
          $return = t('The requested page "@path" could not be found.', array('@path' => request_uri()));
2622
        }
2623

    
2624
        drupal_set_page_content($return);
2625
        $page = element_info('page');
2626
        print drupal_render_page($page);
2627
        break;
2628

    
2629
      case MENU_ACCESS_DENIED:
2630
        // Print a 403 page.
2631
        drupal_add_http_header('Status', '403 Forbidden');
2632
        watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
2633

    
2634
        // Keep old path for reference, and to allow forms to redirect to it.
2635
        if (!isset($_GET['destination'])) {
2636
          $_GET['destination'] = $_GET['q'];
2637
        }
2638

    
2639
        $path = drupal_get_normal_path(variable_get('site_403', ''));
2640
        if ($path && $path != $_GET['q']) {
2641
          // Custom 403 handler. Set the active item in case there are tabs to
2642
          // display or other dependencies on the path.
2643
          menu_set_active_item($path);
2644
          $return = menu_execute_active_handler($path, FALSE);
2645
        }
2646

    
2647
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2648
          // Standard 403 handler.
2649
          drupal_set_title(t('Access denied'));
2650
          $return = t('You are not authorized to access this page.');
2651
        }
2652

    
2653
        print drupal_render_page($return);
2654
        break;
2655

    
2656
      case MENU_SITE_OFFLINE:
2657
        // Print a 503 page.
2658
        drupal_maintenance_theme();
2659
        drupal_add_http_header('Status', '503 Service unavailable');
2660
        drupal_set_title(t('Site under maintenance'));
2661
        print theme('maintenance_page', array('content' => filter_xss_admin(variable_get('maintenance_mode_message',
2662
          t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))))));
2663
        break;
2664
    }
2665
  }
2666
  elseif (isset($page_callback_result)) {
2667
    // Print anything besides a menu constant, assuming it's not NULL or
2668
    // undefined.
2669
    print drupal_render_page($page_callback_result);
2670
  }
2671

    
2672
  // Perform end-of-request tasks.
2673
  drupal_page_footer();
2674
}
2675

    
2676
/**
2677
 * Performs end-of-request tasks.
2678
 *
2679
 * This function sets the page cache if appropriate, and allows modules to
2680
 * react to the closing of the page by calling hook_exit().
2681
 */
2682
function drupal_page_footer() {
2683
  global $user;
2684

    
2685
  module_invoke_all('exit');
2686

    
2687
  // Commit the user session, if needed.
2688
  drupal_session_commit();
2689

    
2690
  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
2691
    drupal_serve_page_from_cache($cache);
2692
  }
2693
  else {
2694
    ob_flush();
2695
  }
2696

    
2697
  _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
2698
  drupal_cache_system_paths();
2699
  module_implements_write_cache();
2700
  system_run_automated_cron();
2701
}
2702

    
2703
/**
2704
 * Performs end-of-request tasks.
2705
 *
2706
 * In some cases page requests need to end without calling drupal_page_footer().
2707
 * In these cases, call drupal_exit() instead. There should rarely be a reason
2708
 * to call exit instead of drupal_exit();
2709
 *
2710
 * @param $destination
2711
 *   If this function is called from drupal_goto(), then this argument
2712
 *   will be a fully-qualified URL that is the destination of the redirect.
2713
 *   This should be passed along to hook_exit() implementations.
2714
 */
2715
function drupal_exit($destination = NULL) {
2716
  if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL) {
2717
    if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
2718
      module_invoke_all('exit', $destination);
2719
    }
2720
    drupal_session_commit();
2721
  }
2722
  exit;
2723
}
2724

    
2725
/**
2726
 * Forms an associative array from a linear array.
2727
 *
2728
 * This function walks through the provided array and constructs an associative
2729
 * array out of it. The keys of the resulting array will be the values of the
2730
 * input array. The values will be the same as the keys unless a function is
2731
 * specified, in which case the output of the function is used for the values
2732
 * instead.
2733
 *
2734
 * @param $array
2735
 *   A linear array.
2736
 * @param $function
2737
 *   A name of a function to apply to all values before output.
2738
 *
2739
 * @return
2740
 *   An associative array.
2741
 */
2742
function drupal_map_assoc($array, $function = NULL) {
2743
  // array_combine() fails with empty arrays:
2744
  // http://bugs.php.net/bug.php?id=34857.
2745
  $array = !empty($array) ? array_combine($array, $array) : array();
2746
  if (is_callable($function)) {
2747
    $array = array_map($function, $array);
2748
  }
2749
  return $array;
2750
}
2751

    
2752
/**
2753
 * Attempts to set the PHP maximum execution time.
2754
 *
2755
 * This function is a wrapper around the PHP function set_time_limit().
2756
 * When called, set_time_limit() restarts the timeout counter from zero.
2757
 * In other words, if the timeout is the default 30 seconds, and 25 seconds
2758
 * into script execution a call such as set_time_limit(20) is made, the
2759
 * script will run for a total of 45 seconds before timing out.
2760
 *
2761
 * It also means that it is possible to decrease the total time limit if
2762
 * the sum of the new time limit and the current time spent running the
2763
 * script is inferior to the original time limit. It is inherent to the way
2764
 * set_time_limit() works, it should rather be called with an appropriate
2765
 * value every time you need to allocate a certain amount of time
2766
 * to execute a task than only once at the beginning of the script.
2767
 *
2768
 * Before calling set_time_limit(), we check if this function is available
2769
 * because it could be disabled by the server administrator. We also hide all
2770
 * the errors that could occur when calling set_time_limit(), because it is
2771
 * not possible to reliably ensure that PHP or a security extension will
2772
 * not issue a warning/error if they prevent the use of this function.
2773
 *
2774
 * @param $time_limit
2775
 *   An integer specifying the new time limit, in seconds. A value of 0
2776
 *   indicates unlimited execution time.
2777
 *
2778
 * @ingroup php_wrappers
2779
 */
2780
function drupal_set_time_limit($time_limit) {
2781
  if (function_exists('set_time_limit')) {
2782
    @set_time_limit($time_limit);
2783
  }
2784
}
2785

    
2786
/**
2787
 * Returns the path to a system item (module, theme, etc.).
2788
 *
2789
 * @param $type
2790
 *   The type of the item (i.e. theme, theme_engine, module, profile).
2791
 * @param $name
2792
 *   The name of the item for which the path is requested.
2793
 *
2794
 * @return
2795
 *   The path to the requested item or an empty string if the item is not found.
2796
 */
2797
function drupal_get_path($type, $name) {
2798
  return dirname(drupal_get_filename($type, $name));
2799
}
2800

    
2801
/**
2802
 * Returns the base URL path (i.e., directory) of the Drupal installation.
2803
 *
2804
 * base_path() adds a "/" to the beginning and end of the returned path if the
2805
 * path is not empty. At the very least, this will return "/".
2806
 *
2807
 * Examples:
2808
 * - http://example.com returns "/" because the path is empty.
2809
 * - http://example.com/drupal/folder returns "/drupal/folder/".
2810
 */
2811
function base_path() {
2812
  return $GLOBALS['base_path'];
2813
}
2814

    
2815
/**
2816
 * Adds a LINK tag with a distinct 'rel' attribute to the page's HEAD.
2817
 *
2818
 * This function can be called as long the HTML header hasn't been sent, which
2819
 * on normal pages is up through the preprocess step of theme('html'). Adding
2820
 * a link will overwrite a prior link with the exact same 'rel' and 'href'
2821
 * attributes.
2822
 *
2823
 * @param $attributes
2824
 *   Associative array of element attributes including 'href' and 'rel'.
2825
 * @param $header
2826
 *   Optional flag to determine if a HTTP 'Link:' header should be sent.
2827
 */
2828
function drupal_add_html_head_link($attributes, $header = FALSE) {
2829
  $element = array(
2830
    '#tag' => 'link',
2831
    '#attributes' => $attributes,
2832
  );
2833
  $href = $attributes['href'];
2834

    
2835
  if ($header) {
2836
    // Also add a HTTP header "Link:".
2837
    $href = '<' . check_plain($attributes['href']) . '>;';
2838
    unset($attributes['href']);
2839
    $element['#attached']['drupal_add_http_header'][] = array('Link',  $href . drupal_http_header_attributes($attributes), TRUE);
2840
  }
2841

    
2842
  drupal_add_html_head($element, 'drupal_add_html_head_link:' . $attributes['rel'] . ':' . $href);
2843
}
2844

    
2845
/**
2846
 * Adds a cascading stylesheet to the stylesheet queue.
2847
 *
2848
 * Calling drupal_static_reset('drupal_add_css') will clear all cascading
2849
 * stylesheets added so far.
2850
 *
2851
 * If CSS aggregation/compression is enabled, all cascading style sheets added
2852
 * with $options['preprocess'] set to TRUE will be merged into one aggregate
2853
 * file and compressed by removing all extraneous white space.
2854
 * Preprocessed inline stylesheets will not be aggregated into this single file;
2855
 * instead, they are just compressed upon output on the page. Externally hosted
2856
 * stylesheets are never aggregated or compressed.
2857
 *
2858
 * The reason for aggregating the files is outlined quite thoroughly here:
2859
 * http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
2860
 * to request overhead, one bigger file just loads faster than two smaller ones
2861
 * half its size."
2862
 *
2863
 * $options['preprocess'] should be only set to TRUE when a file is required for
2864
 * all typical visitors and most pages of a site. It is critical that all
2865
 * preprocessed files are added unconditionally on every page, even if the
2866
 * files do not happen to be needed on a page. This is normally done by calling
2867
 * drupal_add_css() in a hook_init() implementation.
2868
 *
2869
 * Non-preprocessed files should only be added to the page when they are
2870
 * actually needed.
2871
 *
2872
 * @param $data
2873
 *   (optional) The stylesheet data to be added, depending on what is passed
2874
 *   through to the $options['type'] parameter:
2875
 *   - 'file': The path to the CSS file relative to the base_path(), or a
2876
 *     stream wrapper URI. For example: "modules/devel/devel.css" or
2877
 *     "public://generated_css/stylesheet_1.css". Note that Modules should
2878
 *     always prefix the names of their CSS files with the module name; for
2879
 *     example, system-menus.css rather than simply menus.css. Themes can
2880
 *     override module-supplied CSS files based on their filenames, and this
2881
 *     prefixing helps prevent confusing name collisions for theme developers.
2882
 *     See drupal_get_css() where the overrides are performed. Also, if the
2883
 *     direction of the current language is right-to-left (Hebrew, Arabic,
2884
 *     etc.), the function will also look for an RTL CSS file and append it to
2885
 *     the list. The name of this file should have an '-rtl.css' suffix. For
2886
 *     example, a CSS file called 'mymodule-name.css' will have a
2887
 *     'mymodule-name-rtl.css' file added to the list, if exists in the same
2888
 *     directory. This CSS file should contain overrides for properties which
2889
 *     should be reversed or otherwise different in a right-to-left display.
2890
 *   - 'inline': A string of CSS that should be placed in the given scope. Note
2891
 *     that it is better practice to use 'file' stylesheets, rather than
2892
 *     'inline', as the CSS would then be aggregated and cached.
2893
 *   - 'external': The absolute path to an external CSS file that is not hosted
2894
 *     on the local server. These files will not be aggregated if CSS
2895
 *     aggregation is enabled.
2896
 * @param $options
2897
 *   (optional) A string defining the 'type' of CSS that is being added in the
2898
 *   $data parameter ('file', 'inline', or 'external'), or an array which can
2899
 *   have any or all of the following keys:
2900
 *   - 'type': The type of stylesheet being added. Available options are 'file',
2901
 *     'inline' or 'external'. Defaults to 'file'.
2902
 *   - 'basename': Force a basename for the file being added. Modules are
2903
 *     expected to use stylesheets with unique filenames, but integration of
2904
 *     external libraries may make this impossible. The basename of
2905
 *     'modules/node/node.css' is 'node.css'. If the external library "node.js"
2906
 *     ships with a 'node.css', then a different, unique basename would be
2907
 *     'node.js.css'.
2908
 *   - 'group': A number identifying the group in which to add the stylesheet.
2909
 *     Available constants are:
2910
 *     - CSS_SYSTEM: Any system-layer CSS.
2911
 *     - CSS_DEFAULT: (default) Any module-layer CSS.
2912
 *     - CSS_THEME: Any theme-layer CSS.
2913
 *     The group number serves as a weight: the markup for loading a stylesheet
2914
 *     within a lower weight group is output to the page before the markup for
2915
 *     loading a stylesheet within a higher weight group, so CSS within higher
2916
 *     weight groups take precendence over CSS within lower weight groups.
2917
 *   - 'every_page': For optimal front-end performance when aggregation is
2918
 *     enabled, this should be set to TRUE if the stylesheet is present on every
2919
 *     page of the website for users for whom it is present at all. This
2920
 *     defaults to FALSE. It is set to TRUE for stylesheets added via module and
2921
 *     theme .info files. Modules that add stylesheets within hook_init()
2922
 *     implementations, or from other code that ensures that the stylesheet is
2923
 *     added to all website pages, should also set this flag to TRUE. All
2924
 *     stylesheets within the same group that have the 'every_page' flag set to
2925
 *     TRUE and do not have 'preprocess' set to FALSE are aggregated together
2926
 *     into a single aggregate file, and that aggregate file can be reused
2927
 *     across a user's entire site visit, leading to faster navigation between
2928
 *     pages. However, stylesheets that are only needed on pages less frequently
2929
 *     visited, can be added by code that only runs for those particular pages,
2930
 *     and that code should not set the 'every_page' flag. This minimizes the
2931
 *     size of the aggregate file that the user needs to download when first
2932
 *     visiting the website. Stylesheets without the 'every_page' flag are
2933
 *     aggregated into a separate aggregate file. This other aggregate file is
2934
 *     likely to change from page to page, and each new aggregate file needs to
2935
 *     be downloaded when first encountered, so it should be kept relatively
2936
 *     small by ensuring that most commonly needed stylesheets are added to
2937
 *     every page.
2938
 *   - 'weight': The weight of the stylesheet specifies the order in which the
2939
 *     CSS will appear relative to other stylesheets with the same group and
2940
 *     'every_page' flag. The exact ordering of stylesheets is as follows:
2941
 *     - First by group.
2942
 *     - Then by the 'every_page' flag, with TRUE coming before FALSE.
2943
 *     - Then by weight.
2944
 *     - Then by the order in which the CSS was added. For example, all else
2945
 *       being the same, a stylesheet added by a call to drupal_add_css() that
2946
 *       happened later in the page request gets added to the page after one for
2947
 *       which drupal_add_css() happened earlier in the page request.
2948
 *   - 'media': The media type for the stylesheet, e.g., all, print, screen.
2949
 *     Defaults to 'all'.
2950
 *   - 'preprocess': If TRUE and CSS aggregation/compression is enabled, the
2951
 *     styles will be aggregated and compressed. Defaults to TRUE.
2952
 *   - 'browsers': An array containing information specifying which browsers
2953
 *     should load the CSS item. See drupal_pre_render_conditional_comments()
2954
 *     for details.
2955
 *
2956
 * @return
2957
 *   An array of queued cascading stylesheets.
2958
 *
2959
 * @see drupal_get_css()
2960
 */
2961
function drupal_add_css($data = NULL, $options = NULL) {
2962
  $css = &drupal_static(__FUNCTION__, array());
2963

    
2964
  // Construct the options, taking the defaults into consideration.
2965
  if (isset($options)) {
2966
    if (!is_array($options)) {
2967
      $options = array('type' => $options);
2968
    }
2969
  }
2970
  else {
2971
    $options = array();
2972
  }
2973

    
2974
  // Create an array of CSS files for each media type first, since each type needs to be served
2975
  // to the browser differently.
2976
  if (isset($data)) {
2977
    $options += array(
2978
      'type' => 'file',
2979
      'group' => CSS_DEFAULT,
2980
      'weight' => 0,
2981
      'every_page' => FALSE,
2982
      'media' => 'all',
2983
      'preprocess' => TRUE,
2984
      'data' => $data,
2985
      'browsers' => array(),
2986
    );
2987
    $options['browsers'] += array(
2988
      'IE' => TRUE,
2989
      '!IE' => TRUE,
2990
    );
2991

    
2992
    // Files with a query string cannot be preprocessed.
2993
    if ($options['type'] === 'file' && $options['preprocess'] && strpos($options['data'], '?') !== FALSE) {
2994
      $options['preprocess'] = FALSE;
2995
    }
2996

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

    
3000
    // Add the data to the CSS array depending on the type.
3001
    switch ($options['type']) {
3002
      case 'inline':
3003
        // For inline stylesheets, we don't want to use the $data as the array
3004
        // key as $data could be a very long string of CSS.
3005
        $css[] = $options;
3006
        break;
3007
      default:
3008
        // Local and external files must keep their name as the associative key
3009
        // so the same CSS file is not be added twice.
3010
        $css[$data] = $options;
3011
    }
3012
  }
3013

    
3014
  return $css;
3015
}
3016

    
3017
/**
3018
 * Returns a themed representation of all stylesheets to attach to the page.
3019
 *
3020
 * It loads the CSS in order, with 'module' first, then 'theme' afterwards.
3021
 * This ensures proper cascading of styles so themes can easily override
3022
 * module styles through CSS selectors.
3023
 *
3024
 * Themes may replace module-defined CSS files by adding a stylesheet with the
3025
 * same filename. For example, themes/bartik/system-menus.css would replace
3026
 * modules/system/system-menus.css. This allows themes to override complete
3027
 * CSS files, rather than specific selectors, when necessary.
3028
 *
3029
 * If the original CSS file is being overridden by a theme, the theme is
3030
 * responsible for supplying an accompanying RTL CSS file to replace the
3031
 * module's.
3032
 *
3033
 * @param $css
3034
 *   (optional) An array of CSS files. If no array is provided, the default
3035
 *   stylesheets array is used instead.
3036
 * @param $skip_alter
3037
 *   (optional) If set to TRUE, this function skips calling drupal_alter() on
3038
 *   $css, useful when the calling function passes a $css array that has already
3039
 *   been altered.
3040
 *
3041
 * @return
3042
 *   A string of XHTML CSS tags.
3043
 *
3044
 * @see drupal_add_css()
3045
 */
3046
function drupal_get_css($css = NULL, $skip_alter = FALSE) {
3047
  if (!isset($css)) {
3048
    $css = drupal_add_css();
3049
  }
3050

    
3051
  // Allow modules and themes to alter the CSS items.
3052
  if (!$skip_alter) {
3053
    drupal_alter('css', $css);
3054
  }
3055

    
3056
  // Sort CSS items, so that they appear in the correct order.
3057
  uasort($css, 'drupal_sort_css_js');
3058

    
3059
  // Provide the page with information about the individual CSS files used,
3060
  // information not otherwise available when CSS aggregation is enabled. The
3061
  // setting is attached later in this function, but is set here, so that CSS
3062
  // files removed below are still considered "used" and prevented from being
3063
  // added in a later AJAX request.
3064
  // Skip if no files were added to the page or jQuery.extend() will overwrite
3065
  // the Drupal.settings.ajaxPageState.css object with an empty array.
3066
  if (!empty($css)) {
3067
    // Cast the array to an object to be on the safe side even if not empty.
3068
    $setting['ajaxPageState']['css'] = (object) array_fill_keys(array_keys($css), 1);
3069
  }
3070

    
3071
  // Remove the overridden CSS files. Later CSS files override former ones.
3072
  $previous_item = array();
3073
  foreach ($css as $key => $item) {
3074
    if ($item['type'] == 'file') {
3075
      // If defined, force a unique basename for this file.
3076
      $basename = isset($item['basename']) ? $item['basename'] : drupal_basename($item['data']);
3077
      if (isset($previous_item[$basename])) {
3078
        // Remove the previous item that shared the same base name.
3079
        unset($css[$previous_item[$basename]]);
3080
      }
3081
      $previous_item[$basename] = $key;
3082
    }
3083
  }
3084

    
3085
  // Render the HTML needed to load the CSS.
3086
  $styles = array(
3087
    '#type' => 'styles',
3088
    '#items' => $css,
3089
  );
3090

    
3091
  if (!empty($setting)) {
3092
    $styles['#attached']['js'][] = array('type' => 'setting', 'data' => $setting);
3093
  }
3094

    
3095
  return drupal_render($styles);
3096
}
3097

    
3098
/**
3099
 * Sorts CSS and JavaScript resources.
3100
 *
3101
 * Callback for uasort() within:
3102
 * - drupal_get_css()
3103
 * - drupal_get_js()
3104
 *
3105
 * This sort order helps optimize front-end performance while providing modules
3106
 * and themes with the necessary control for ordering the CSS and JavaScript
3107
 * appearing on a page.
3108
 *
3109
 * @param $a
3110
 *   First item for comparison. The compared items should be associative arrays
3111
 *   of member items from drupal_add_css() or drupal_add_js().
3112
 * @param $b
3113
 *   Second item for comparison.
3114
 *
3115
 * @see drupal_add_css()
3116
 * @see drupal_add_js()
3117
 */
3118
function drupal_sort_css_js($a, $b) {
3119
  // First order by group, so that, for example, all items in the CSS_SYSTEM
3120
  // group appear before items in the CSS_DEFAULT group, which appear before
3121
  // all items in the CSS_THEME group. Modules may create additional groups by
3122
  // defining their own constants.
3123
  if ($a['group'] < $b['group']) {
3124
    return -1;
3125
  }
3126
  elseif ($a['group'] > $b['group']) {
3127
    return 1;
3128
  }
3129
  // Within a group, order all infrequently needed, page-specific files after
3130
  // common files needed throughout the website. Separating this way allows for
3131
  // the aggregate file generated for all of the common files to be reused
3132
  // across a site visit without being cut by a page using a less common file.
3133
  elseif ($a['every_page'] && !$b['every_page']) {
3134
    return -1;
3135
  }
3136
  elseif (!$a['every_page'] && $b['every_page']) {
3137
    return 1;
3138
  }
3139
  // Finally, order by weight.
3140
  elseif ($a['weight'] < $b['weight']) {
3141
    return -1;
3142
  }
3143
  elseif ($a['weight'] > $b['weight']) {
3144
    return 1;
3145
  }
3146
  else {
3147
    return 0;
3148
  }
3149
}
3150

    
3151
/**
3152
 * Default callback to group CSS items.
3153
 *
3154
 * This function arranges the CSS items that are in the #items property of the
3155
 * styles element into groups. Arranging the CSS items into groups serves two
3156
 * purposes. When aggregation is enabled, files within a group are aggregated
3157
 * into a single file, significantly improving page loading performance by
3158
 * minimizing network traffic overhead. When aggregation is disabled, grouping
3159
 * allows multiple files to be loaded from a single STYLE tag, enabling sites
3160
 * with many modules enabled or a complex theme being used to stay within IE's
3161
 * 31 CSS inclusion tag limit: http://drupal.org/node/228818.
3162
 *
3163
 * This function puts multiple items into the same group if they are groupable
3164
 * and if they are for the same 'media' and 'browsers'. Items of the 'file' type
3165
 * are groupable if their 'preprocess' flag is TRUE, items of the 'inline' type
3166
 * are always groupable, and items of the 'external' type are never groupable.
3167
 * This function also ensures that the process of grouping items does not change
3168
 * their relative order. This requirement may result in multiple groups for the
3169
 * same type, media, and browsers, if needed to accommodate other items in
3170
 * between.
3171
 *
3172
 * @param $css
3173
 *   An array of CSS items, as returned by drupal_add_css(), but after
3174
 *   alteration performed by drupal_get_css().
3175
 *
3176
 * @return
3177
 *   An array of CSS groups. Each group contains the same keys (e.g., 'media',
3178
 *   'data', etc.) as a CSS item from the $css parameter, with the value of
3179
 *   each key applying to the group as a whole. Each group also contains an
3180
 *   'items' key, which is the subset of items from $css that are in the group.
3181
 *
3182
 * @see drupal_pre_render_styles()
3183
 * @see system_element_info()
3184
 */
3185
function drupal_group_css($css) {
3186
  $groups = array();
3187
  // If a group can contain multiple items, we track the information that must
3188
  // be the same for each item in the group, so that when we iterate the next
3189
  // item, we can determine if it can be put into the current group, or if a
3190
  // new group needs to be made for it.
3191
  $current_group_keys = NULL;
3192
  // When creating a new group, we pre-increment $i, so by initializing it to
3193
  // -1, the first group will have index 0.
3194
  $i = -1;
3195
  foreach ($css as $item) {
3196
    // The browsers for which the CSS item needs to be loaded is part of the
3197
    // information that determines when a new group is needed, but the order of
3198
    // keys in the array doesn't matter, and we don't want a new group if all
3199
    // that's different is that order.
3200
    ksort($item['browsers']);
3201

    
3202
    // If the item can be grouped with other items, set $group_keys to an array
3203
    // of information that must be the same for all items in its group. If the
3204
    // item can't be grouped with other items, set $group_keys to FALSE. We
3205
    // put items into a group that can be aggregated together: whether they will
3206
    // be aggregated is up to the _drupal_css_aggregate() function or an
3207
    // override of that function specified in hook_css_alter(), but regardless
3208
    // of the details of that function, a group represents items that can be
3209
    // aggregated. Since a group may be rendered with a single HTML tag, all
3210
    // items in the group must share the same information that would need to be
3211
    // part of that HTML tag.
3212
    switch ($item['type']) {
3213
      case 'file':
3214
        // Group file items if their 'preprocess' flag is TRUE.
3215
        // Help ensure maximum reuse of aggregate files by only grouping
3216
        // together items that share the same 'group' value and 'every_page'
3217
        // flag. See drupal_add_css() for details about that.
3218
        $group_keys = $item['preprocess'] ? array($item['type'], $item['group'], $item['every_page'], $item['media'], $item['browsers']) : FALSE;
3219
        break;
3220
      case 'inline':
3221
        // Always group inline items.
3222
        $group_keys = array($item['type'], $item['media'], $item['browsers']);
3223
        break;
3224
      case 'external':
3225
        // Do not group external items.
3226
        $group_keys = FALSE;
3227
        break;
3228
    }
3229

    
3230
    // If the group keys don't match the most recent group we're working with,
3231
    // then a new group must be made.
3232
    if ($group_keys !== $current_group_keys) {
3233
      $i++;
3234
      // Initialize the new group with the same properties as the first item
3235
      // being placed into it. The item's 'data' and 'weight' properties are
3236
      // unique to the item and should not be carried over to the group.
3237
      $groups[$i] = $item;
3238
      unset($groups[$i]['data'], $groups[$i]['weight']);
3239
      $groups[$i]['items'] = array();
3240
      $current_group_keys = $group_keys ? $group_keys : NULL;
3241
    }
3242

    
3243
    // Add the item to the current group.
3244
    $groups[$i]['items'][] = $item;
3245
  }
3246
  return $groups;
3247
}
3248

    
3249
/**
3250
 * Default callback to aggregate CSS files and inline content.
3251
 *
3252
 * Having the browser load fewer CSS files results in much faster page loads
3253
 * than when it loads many small files. This function aggregates files within
3254
 * the same group into a single file unless the site-wide setting to do so is
3255
 * disabled (commonly the case during site development). To optimize download,
3256
 * it also compresses the aggregate files by removing comments, whitespace, and
3257
 * other unnecessary content. Additionally, this functions aggregates inline
3258
 * content together, regardless of the site-wide aggregation setting.
3259
 *
3260
 * @param $css_groups
3261
 *   An array of CSS groups as returned by drupal_group_css(). This function
3262
 *   modifies the group's 'data' property for each group that is aggregated.
3263
 *
3264
 * @see drupal_group_css()
3265
 * @see drupal_pre_render_styles()
3266
 * @see system_element_info()
3267
 */
3268
function drupal_aggregate_css(&$css_groups) {
3269
  $preprocess_css = (variable_get('preprocess_css', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
3270

    
3271
  // For each group that needs aggregation, aggregate its items.
3272
  foreach ($css_groups as $key => $group) {
3273
    switch ($group['type']) {
3274
      // If a file group can be aggregated into a single file, do so, and set
3275
      // the group's data property to the file path of the aggregate file.
3276
      case 'file':
3277
        if ($group['preprocess'] && $preprocess_css) {
3278
          $css_groups[$key]['data'] = drupal_build_css_cache($group['items']);
3279
        }
3280
        break;
3281
      // Aggregate all inline CSS content into the group's data property.
3282
      case 'inline':
3283
        $css_groups[$key]['data'] = '';
3284
        foreach ($group['items'] as $item) {
3285
          $css_groups[$key]['data'] .= drupal_load_stylesheet_content($item['data'], $item['preprocess']);
3286
        }
3287
        break;
3288
    }
3289
  }
3290
}
3291

    
3292
/**
3293
 * #pre_render callback to add the elements needed for CSS tags to be rendered.
3294
 *
3295
 * For production websites, LINK tags are preferable to STYLE tags with @import
3296
 * statements, because:
3297
 * - They are the standard tag intended for linking to a resource.
3298
 * - On Firefox 2 and perhaps other browsers, CSS files included with @import
3299
 *   statements don't get saved when saving the complete web page for offline
3300
 *   use: http://drupal.org/node/145218.
3301
 * - On IE, if only LINK tags and no @import statements are used, all the CSS
3302
 *   files are downloaded in parallel, resulting in faster page load, but if
3303
 *   @import statements are used and span across multiple STYLE tags, all the
3304
 *   ones from one STYLE tag must be downloaded before downloading begins for
3305
 *   the next STYLE tag. Furthermore, IE7 does not support media declaration on
3306
 *   the @import statement, so multiple STYLE tags must be used when different
3307
 *   files are for different media types. Non-IE browsers always download in
3308
 *   parallel, so this is an IE-specific performance quirk:
3309
 *   http://www.stevesouders.com/blog/2009/04/09/dont-use-import/.
3310
 *
3311
 * However, IE has an annoying limit of 31 total CSS inclusion tags
3312
 * (http://drupal.org/node/228818) and LINK tags are limited to one file per
3313
 * tag, whereas STYLE tags can contain multiple @import statements allowing
3314
 * multiple files to be loaded per tag. When CSS aggregation is disabled, a
3315
 * Drupal site can easily have more than 31 CSS files that need to be loaded, so
3316
 * using LINK tags exclusively would result in a site that would display
3317
 * incorrectly in IE. Depending on different needs, different strategies can be
3318
 * employed to decide when to use LINK tags and when to use STYLE tags.
3319
 *
3320
 * The strategy employed by this function is to use LINK tags for all aggregate
3321
 * files and for all files that cannot be aggregated (e.g., if 'preprocess' is
3322
 * set to FALSE or the type is 'external'), and to use STYLE tags for groups
3323
 * of files that could be aggregated together but aren't (e.g., if the site-wide
3324
 * aggregation setting is disabled). This results in all LINK tags when
3325
 * aggregation is enabled, a guarantee that as many or only slightly more tags
3326
 * are used with aggregation disabled than enabled (so that if the limit were to
3327
 * be crossed with aggregation enabled, the site developer would also notice the
3328
 * problem while aggregation is disabled), and an easy way for a developer to
3329
 * view HTML source while aggregation is disabled and know what files will be
3330
 * aggregated together when aggregation becomes enabled.
3331
 *
3332
 * This function evaluates the aggregation enabled/disabled condition on a group
3333
 * by group basis by testing whether an aggregate file has been made for the
3334
 * group rather than by testing the site-wide aggregation setting. This allows
3335
 * this function to work correctly even if modules have implemented custom
3336
 * logic for grouping and aggregating files.
3337
 *
3338
 * @param $element
3339
 *   A render array containing:
3340
 *   - '#items': The CSS items as returned by drupal_add_css() and altered by
3341
 *     drupal_get_css().
3342
 *   - '#group_callback': A function to call to group #items to enable the use
3343
 *     of fewer tags by aggregating files and/or using multiple @import
3344
 *     statements within a single tag.
3345
 *   - '#aggregate_callback': A function to call to aggregate the items within
3346
 *     the groups arranged by the #group_callback function.
3347
 *
3348
 * @return
3349
 *   A render array that will render to a string of XHTML CSS tags.
3350
 *
3351
 * @see drupal_get_css()
3352
 */
3353
function drupal_pre_render_styles($elements) {
3354
  // Group and aggregate the items.
3355
  if (isset($elements['#group_callback'])) {
3356
    $elements['#groups'] = $elements['#group_callback']($elements['#items']);
3357
  }
3358
  if (isset($elements['#aggregate_callback'])) {
3359
    $elements['#aggregate_callback']($elements['#groups']);
3360
  }
3361

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

    
3368
  // For inline CSS to validate as XHTML, all CSS containing XHTML needs to be
3369
  // wrapped in CDATA. To make that backwards compatible with HTML 4, we need to
3370
  // comment out the CDATA-tag.
3371
  $embed_prefix = "\n<!--/*--><![CDATA[/*><!--*/\n";
3372
  $embed_suffix = "\n/*]]>*/-->\n";
3373

    
3374
  // Defaults for LINK and STYLE elements.
3375
  $link_element_defaults = array(
3376
    '#type' => 'html_tag',
3377
    '#tag' => 'link',
3378
    '#attributes' => array(
3379
      'type' => 'text/css',
3380
      'rel' => 'stylesheet',
3381
    ),
3382
  );
3383
  $style_element_defaults = array(
3384
    '#type' => 'html_tag',
3385
    '#tag' => 'style',
3386
    '#attributes' => array(
3387
      'type' => 'text/css',
3388
    ),
3389
  );
3390

    
3391
  // Loop through each group.
3392
  foreach ($elements['#groups'] as $group) {
3393
    switch ($group['type']) {
3394
      // For file items, there are three possibilites.
3395
      // - The group has been aggregated: in this case, output a LINK tag for
3396
      //   the aggregate file.
3397
      // - The group can be aggregated but has not been (most likely because
3398
      //   the site administrator disabled the site-wide setting): in this case,
3399
      //   output as few STYLE tags for the group as possible, using @import
3400
      //   statement for each file in the group. This enables us to stay within
3401
      //   IE's limit of 31 total CSS inclusion tags.
3402
      // - The group contains items not eligible for aggregation (their
3403
      //   'preprocess' flag has been set to FALSE): in this case, output a LINK
3404
      //   tag for each file.
3405
      case 'file':
3406
        // The group has been aggregated into a single file: output a LINK tag
3407
        // for the aggregate file.
3408
        if (isset($group['data'])) {
3409
          $element = $link_element_defaults;
3410
          $element['#attributes']['href'] = file_create_url($group['data']);
3411
          $element['#attributes']['media'] = $group['media'];
3412
          $element['#browsers'] = $group['browsers'];
3413
          $elements[] = $element;
3414
        }
3415
        // The group can be aggregated, but hasn't been: combine multiple items
3416
        // into as few STYLE tags as possible.
3417
        elseif ($group['preprocess']) {
3418
          $import = array();
3419
          foreach ($group['items'] as $item) {
3420
            // A theme's .info file may have an entry for a file that doesn't
3421
            // exist as a way of overriding a module or base theme CSS file from
3422
            // being added to the page. Normally, file_exists() calls that need
3423
            // to run for every page request should be minimized, but this one
3424
            // is okay, because it only runs when CSS aggregation is disabled.
3425
            // On a server under heavy enough load that file_exists() calls need
3426
            // to be minimized, CSS aggregation should be enabled, in which case
3427
            // this code is not run. When aggregation is enabled,
3428
            // drupal_load_stylesheet() checks file_exists(), but only when
3429
            // building the aggregate file, which is then reused for many page
3430
            // requests.
3431
            if (file_exists($item['data'])) {
3432
              // The dummy query string needs to be added to the URL to control
3433
              // browser-caching. IE7 does not support a media type on the
3434
              // @import statement, so we instead specify the media for the
3435
              // group on the STYLE tag.
3436
              $import[] = '@import url("' . check_plain(file_create_url($item['data']) . '?' . $query_string) . '");';
3437
            }
3438
          }
3439
          // In addition to IE's limit of 31 total CSS inclusion tags, it also
3440
          // has a limit of 31 @import statements per STYLE tag.
3441
          while (!empty($import)) {
3442
            $import_batch = array_slice($import, 0, 31);
3443
            $import = array_slice($import, 31);
3444
            $element = $style_element_defaults;
3445
            $element['#value'] = implode("\n", $import_batch);
3446
            $element['#attributes']['media'] = $group['media'];
3447
            $element['#browsers'] = $group['browsers'];
3448
            $elements[] = $element;
3449
          }
3450
        }
3451
        // The group contains items ineligible for aggregation: output a LINK
3452
        // tag for each file.
3453
        else {
3454
          foreach ($group['items'] as $item) {
3455
            $element = $link_element_defaults;
3456
            // We do not check file_exists() here, because this code runs for
3457
            // files whose 'preprocess' is set to FALSE, and therefore, even
3458
            // when aggregation is enabled, and we want to avoid needlessly
3459
            // taxing a server that may be under heavy load. The file_exists()
3460
            // performed above for files whose 'preprocess' is TRUE is done for
3461
            // the benefit of theme .info files, but code that deals with files
3462
            // whose 'preprocess' is FALSE is responsible for ensuring the file
3463
            // exists.
3464
            // The dummy query string needs to be added to the URL to control
3465
            // browser-caching.
3466
            $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
3467
            $element['#attributes']['href'] = file_create_url($item['data']) . $query_string_separator . $query_string;
3468
            $element['#attributes']['media'] = $item['media'];
3469
            $element['#browsers'] = $group['browsers'];
3470
            $elements[] = $element;
3471
          }
3472
        }
3473
        break;
3474
      // For inline content, the 'data' property contains the CSS content. If
3475
      // the group's 'data' property is set, then output it in a single STYLE
3476
      // tag. Otherwise, output a separate STYLE tag for each item.
3477
      case 'inline':
3478
        if (isset($group['data'])) {
3479
          $element = $style_element_defaults;
3480
          $element['#value'] = $group['data'];
3481
          $element['#value_prefix'] = $embed_prefix;
3482
          $element['#value_suffix'] = $embed_suffix;
3483
          $element['#attributes']['media'] = $group['media'];
3484
          $element['#browsers'] = $group['browsers'];
3485
          $elements[] = $element;
3486
        }
3487
        else {
3488
          foreach ($group['items'] as $item) {
3489
            $element = $style_element_defaults;
3490
            $element['#value'] = $item['data'];
3491
            $element['#value_prefix'] = $embed_prefix;
3492
            $element['#value_suffix'] = $embed_suffix;
3493
            $element['#attributes']['media'] = $item['media'];
3494
            $element['#browsers'] = $group['browsers'];
3495
            $elements[] = $element;
3496
          }
3497
        }
3498
        break;
3499
      // Output a LINK tag for each external item. The item's 'data' property
3500
      // contains the full URL.
3501
      case 'external':
3502
        foreach ($group['items'] as $item) {
3503
          $element = $link_element_defaults;
3504
          $element['#attributes']['href'] = $item['data'];
3505
          $element['#attributes']['media'] = $item['media'];
3506
          $element['#browsers'] = $group['browsers'];
3507
          $elements[] = $element;
3508
        }
3509
        break;
3510
    }
3511
  }
3512

    
3513
  return $elements;
3514
}
3515

    
3516
/**
3517
 * Aggregates and optimizes CSS files into a cache file in the files directory.
3518
 *
3519
 * The file name for the CSS cache file is generated from the hash of the
3520
 * aggregated contents of the files in $css. This forces proxies and browsers
3521
 * to download new CSS when the CSS changes.
3522
 *
3523
 * The cache file name is retrieved on a page load via a lookup variable that
3524
 * contains an associative array. The array key is the hash of the file names
3525
 * in $css while the value is the cache file name. The cache file is generated
3526
 * in two cases. First, if there is no file name value for the key, which will
3527
 * happen if a new file name has been added to $css or after the lookup
3528
 * variable is emptied to force a rebuild of the cache. Second, the cache file
3529
 * is generated if it is missing on disk. Old cache files are not deleted
3530
 * immediately when the lookup variable is emptied, but are deleted after a set
3531
 * period by drupal_delete_file_if_stale(). This ensures that files referenced
3532
 * by a cached page will still be available.
3533
 *
3534
 * @param $css
3535
 *   An array of CSS files to aggregate and compress into one file.
3536
 *
3537
 * @return
3538
 *   The URI of the CSS cache file, or FALSE if the file could not be saved.
3539
 */
3540
function drupal_build_css_cache($css) {
3541
  $data = '';
3542
  $uri = '';
3543
  $map = variable_get('drupal_css_cache_files', array());
3544
  // Create a new array so that only the file names are used to create the hash.
3545
  // This prevents new aggregates from being created unnecessarily.
3546
  $css_data = array();
3547
  foreach ($css as $css_file) {
3548
    $css_data[] = $css_file['data'];
3549
  }
3550
  $key = hash('sha256', serialize($css_data));
3551
  if (isset($map[$key])) {
3552
    $uri = $map[$key];
3553
  }
3554

    
3555
  if (empty($uri) || !file_exists($uri)) {
3556
    // Build aggregate CSS file.
3557
    foreach ($css as $stylesheet) {
3558
      // Only 'file' stylesheets can be aggregated.
3559
      if ($stylesheet['type'] == 'file') {
3560
        $contents = drupal_load_stylesheet($stylesheet['data'], TRUE);
3561

    
3562
        // Build the base URL of this CSS file: start with the full URL.
3563
        $css_base_url = file_create_url($stylesheet['data']);
3564
        // Move to the parent.
3565
        $css_base_url = substr($css_base_url, 0, strrpos($css_base_url, '/'));
3566
        // Simplify to a relative URL if the stylesheet URL starts with the
3567
        // base URL of the website.
3568
        if (substr($css_base_url, 0, strlen($GLOBALS['base_root'])) == $GLOBALS['base_root']) {
3569
          $css_base_url = substr($css_base_url, strlen($GLOBALS['base_root']));
3570
        }
3571

    
3572
        _drupal_build_css_path(NULL, $css_base_url . '/');
3573
        // Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
3574
        $data .= preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);
3575
      }
3576
    }
3577

    
3578
    // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
3579
    // @import rules must proceed any other style, so we move those to the top.
3580
    $regexp = '/@import[^;]+;/i';
3581
    preg_match_all($regexp, $data, $matches);
3582
    $data = preg_replace($regexp, '', $data);
3583
    $data = implode('', $matches[0]) . $data;
3584

    
3585
    // Prefix filename to prevent blocking by firewalls which reject files
3586
    // starting with "ad*".
3587
    $filename = 'css_' . drupal_hash_base64($data) . '.css';
3588
    // Create the css/ within the files folder.
3589
    $csspath = 'public://css';
3590
    $uri = $csspath . '/' . $filename;
3591
    // Create the CSS file.
3592
    file_prepare_directory($csspath, FILE_CREATE_DIRECTORY);
3593
    if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
3594
      return FALSE;
3595
    }
3596
    // If CSS gzip compression is enabled, clean URLs are enabled (which means
3597
    // that rewrite rules are working) and the zlib extension is available then
3598
    // create a gzipped version of this file. This file is served conditionally
3599
    // to browsers that accept gzip using .htaccess rules.
3600
    if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
3601
      if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
3602
        return FALSE;
3603
      }
3604
    }
3605
    // Save the updated map.
3606
    $map[$key] = $uri;
3607
    variable_set('drupal_css_cache_files', $map);
3608
  }
3609
  return $uri;
3610
}
3611

    
3612
/**
3613
 * Prefixes all paths within a CSS file for drupal_build_css_cache().
3614
 */
3615
function _drupal_build_css_path($matches, $base = NULL) {
3616
  $_base = &drupal_static(__FUNCTION__);
3617
  // Store base path for preg_replace_callback.
3618
  if (isset($base)) {
3619
    $_base = $base;
3620
  }
3621

    
3622
  // Prefix with base and remove '../' segments where possible.
3623
  $path = $_base . $matches[1];
3624
  $last = '';
3625
  while ($path != $last) {
3626
    $last = $path;
3627
    $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
3628
  }
3629
  return 'url(' . $path . ')';
3630
}
3631

    
3632
/**
3633
 * Loads the stylesheet and resolves all @import commands.
3634
 *
3635
 * Loads a stylesheet and replaces @import commands with the contents of the
3636
 * imported file. Use this instead of file_get_contents when processing
3637
 * stylesheets.
3638
 *
3639
 * The returned contents are compressed removing white space and comments only
3640
 * when CSS aggregation is enabled. This optimization will not apply for
3641
 * color.module enabled themes with CSS aggregation turned off.
3642
 *
3643
 * @param $file
3644
 *   Name of the stylesheet to be processed.
3645
 * @param $optimize
3646
 *   Defines if CSS contents should be compressed or not.
3647
 * @param $reset_basepath
3648
 *   Used internally to facilitate recursive resolution of @import commands.
3649
 *
3650
 * @return
3651
 *   Contents of the stylesheet, including any resolved @import commands.
3652
 */
3653
function drupal_load_stylesheet($file, $optimize = NULL, $reset_basepath = TRUE) {
3654
  // These statics are not cache variables, so we don't use drupal_static().
3655
  static $_optimize, $basepath;
3656
  if ($reset_basepath) {
3657
    $basepath = '';
3658
  }
3659
  // Store the value of $optimize for preg_replace_callback with nested
3660
  // @import loops.
3661
  if (isset($optimize)) {
3662
    $_optimize = $optimize;
3663
  }
3664

    
3665
  // Stylesheets are relative one to each other. Start by adding a base path
3666
  // prefix provided by the parent stylesheet (if necessary).
3667
  if ($basepath && !file_uri_scheme($file)) {
3668
    $file = $basepath . '/' . $file;
3669
  }
3670
  // Store the parent base path to restore it later.
3671
  $parent_base_path = $basepath;
3672
  // Set the current base path to process possible child imports.
3673
  $basepath = dirname($file);
3674

    
3675
  // Load the CSS stylesheet. We suppress errors because themes may specify
3676
  // stylesheets in their .info file that don't exist in the theme's path,
3677
  // but are merely there to disable certain module CSS files.
3678
  $content = '';
3679
  if ($contents = @file_get_contents($file)) {
3680
    // Return the processed stylesheet.
3681
    $content = drupal_load_stylesheet_content($contents, $_optimize);
3682
  }
3683

    
3684
  // Restore the parent base path as the file and its childen are processed.
3685
  $basepath = $parent_base_path;
3686
  return $content;
3687
}
3688

    
3689
/**
3690
 * Processes the contents of a stylesheet for aggregation.
3691
 *
3692
 * @param $contents
3693
 *   The contents of the stylesheet.
3694
 * @param $optimize
3695
 *   (optional) Boolean whether CSS contents should be minified. Defaults to
3696
 *   FALSE.
3697
 *
3698
 * @return
3699
 *   Contents of the stylesheet including the imported stylesheets.
3700
 */
3701
function drupal_load_stylesheet_content($contents, $optimize = FALSE) {
3702
  // Remove multiple charset declarations for standards compliance (and fixing Safari problems).
3703
  $contents = preg_replace('/^@charset\s+[\'"](\S*?)\b[\'"];/i', '', $contents);
3704

    
3705
  if ($optimize) {
3706
    // Perform some safe CSS optimizations.
3707
    // Regexp to match comment blocks.
3708
    $comment     = '/\*[^*]*\*+(?:[^/*][^*]*\*+)*/';
3709
    // Regexp to match double quoted strings.
3710
    $double_quot = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
3711
    // Regexp to match single quoted strings.
3712
    $single_quot = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'";
3713
    // Strip all comment blocks, but keep double/single quoted strings.
3714
    $contents = preg_replace(
3715
      "<($double_quot|$single_quot)|$comment>Ss",
3716
      "$1",
3717
      $contents
3718
    );
3719
    // Remove certain whitespace.
3720
    // There are different conditions for removing leading and trailing
3721
    // whitespace.
3722
    // @see http://php.net/manual/regexp.reference.subpatterns.php
3723
    $contents = preg_replace('<
3724
      # Strip leading and trailing whitespace.
3725
        \s*([@{};,])\s*
3726
      # Strip only leading whitespace from:
3727
      # - Closing parenthesis: Retain "@media (bar) and foo".
3728
      | \s+([\)])
3729
      # Strip only trailing whitespace from:
3730
      # - Opening parenthesis: Retain "@media (bar) and foo".
3731
      # - Colon: Retain :pseudo-selectors.
3732
      | ([\(:])\s+
3733
    >xS',
3734
      // Only one of the three capturing groups will match, so its reference
3735
      // will contain the wanted value and the references for the
3736
      // two non-matching groups will be replaced with empty strings.
3737
      '$1$2$3',
3738
      $contents
3739
    );
3740
    // End the file with a new line.
3741
    $contents = trim($contents);
3742
    $contents .= "\n";
3743
  }
3744

    
3745
  // Replaces @import commands with the actual stylesheet content.
3746
  // This happens recursively but omits external files.
3747
  $contents = preg_replace_callback('/@import\s*(?:url\(\s*)?[\'"]?(?![a-z]+:)([^\'"\()]+)[\'"]?\s*\)?\s*;/', '_drupal_load_stylesheet', $contents);
3748
  return $contents;
3749
}
3750

    
3751
/**
3752
 * Loads stylesheets recursively and returns contents with corrected paths.
3753
 *
3754
 * This function is used for recursive loading of stylesheets and
3755
 * returns the stylesheet content with all url() paths corrected.
3756
 */
3757
function _drupal_load_stylesheet($matches) {
3758
  $filename = $matches[1];
3759
  // Load the imported stylesheet and replace @import commands in there as well.
3760
  $file = drupal_load_stylesheet($filename, NULL, FALSE);
3761

    
3762
  // Determine the file's directory.
3763
  $directory = dirname($filename);
3764
  // If the file is in the current directory, make sure '.' doesn't appear in
3765
  // the url() path.
3766
  $directory = $directory == '.' ? '' : $directory .'/';
3767

    
3768
  // Alter all internal url() paths. Leave external paths alone. We don't need
3769
  // to normalize absolute paths here (i.e. remove folder/... segments) because
3770
  // that will be done later.
3771
  return preg_replace('/url\(\s*([\'"]?)(?![a-z]+:|\/+)/i', 'url(\1'. $directory, $file);
3772
}
3773

    
3774
/**
3775
 * Deletes old cached CSS files.
3776
 */
3777
function drupal_clear_css_cache() {
3778
  variable_del('drupal_css_cache_files');
3779
  file_scan_directory('public://css', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
3780
}
3781

    
3782
/**
3783
 * Callback to delete files modified more than a set time ago.
3784
 */
3785
function drupal_delete_file_if_stale($uri) {
3786
  // Default stale file threshold is 30 days.
3787
  if (REQUEST_TIME - filemtime($uri) > variable_get('drupal_stale_file_threshold', 2592000)) {
3788
    file_unmanaged_delete($uri);
3789
  }
3790
}
3791

    
3792
/**
3793
 * Prepares a string for use as a CSS identifier (element, class, or ID name).
3794
 *
3795
 * http://www.w3.org/TR/CSS21/syndata.html#characters shows the syntax for valid
3796
 * CSS identifiers (including element names, classes, and IDs in selectors.)
3797
 *
3798
 * @param $identifier
3799
 *   The identifier to clean.
3800
 * @param $filter
3801
 *   An array of string replacements to use on the identifier.
3802
 *
3803
 * @return
3804
 *   The cleaned identifier.
3805
 */
3806
function drupal_clean_css_identifier($identifier, $filter = array(' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '')) {
3807
  // By default, we filter using Drupal's coding standards.
3808
  $identifier = strtr($identifier, $filter);
3809

    
3810
  // Valid characters in a CSS identifier are:
3811
  // - the hyphen (U+002D)
3812
  // - a-z (U+0030 - U+0039)
3813
  // - A-Z (U+0041 - U+005A)
3814
  // - the underscore (U+005F)
3815
  // - 0-9 (U+0061 - U+007A)
3816
  // - ISO 10646 characters U+00A1 and higher
3817
  // We strip out any character not in the above list.
3818
  $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);
3819

    
3820
  return $identifier;
3821
}
3822

    
3823
/**
3824
 * Prepares a string for use as a valid class name.
3825
 *
3826
 * Do not pass one string containing multiple classes as they will be
3827
 * incorrectly concatenated with dashes, i.e. "one two" will become "one-two".
3828
 *
3829
 * @param $class
3830
 *   The class name to clean.
3831
 *
3832
 * @return
3833
 *   The cleaned class name.
3834
 */
3835
function drupal_html_class($class) {
3836
  // The output of this function will never change, so this uses a normal
3837
  // static instead of drupal_static().
3838
  static $classes = array();
3839

    
3840
  if (!isset($classes[$class])) {
3841
    $classes[$class] = drupal_clean_css_identifier(drupal_strtolower($class));
3842
  }
3843
  return $classes[$class];
3844
}
3845

    
3846
/**
3847
 * Prepares a string for use as a valid HTML ID and guarantees uniqueness.
3848
 *
3849
 * This function ensures that each passed HTML ID value only exists once on the
3850
 * page. By tracking the already returned ids, this function enables forms,
3851
 * blocks, and other content to be output multiple times on the same page,
3852
 * without breaking (X)HTML validation.
3853
 *
3854
 * For already existing IDs, a counter is appended to the ID string. Therefore,
3855
 * JavaScript and CSS code should not rely on any value that was generated by
3856
 * this function and instead should rely on manually added CSS classes or
3857
 * similarly reliable constructs.
3858
 *
3859
 * Two consecutive hyphens separate the counter from the original ID. To manage
3860
 * uniqueness across multiple Ajax requests on the same page, Ajax requests
3861
 * POST an array of all IDs currently present on the page, which are used to
3862
 * prime this function's cache upon first invocation.
3863
 *
3864
 * To allow reverse-parsing of IDs submitted via Ajax, any multiple consecutive
3865
 * hyphens in the originally passed $id are replaced with a single hyphen.
3866
 *
3867
 * @param $id
3868
 *   The ID to clean.
3869
 *
3870
 * @return
3871
 *   The cleaned ID.
3872
 */
3873
function drupal_html_id($id) {
3874
  // If this is an Ajax request, then content returned by this page request will
3875
  // be merged with content already on the base page. The HTML IDs must be
3876
  // unique for the fully merged content. Therefore, initialize $seen_ids to
3877
  // take into account IDs that are already in use on the base page.
3878
  $seen_ids_init = &drupal_static(__FUNCTION__ . ':init');
3879
  if (!isset($seen_ids_init)) {
3880
    // Ideally, Drupal would provide an API to persist state information about
3881
    // prior page requests in the database, and we'd be able to add this
3882
    // function's $seen_ids static variable to that state information in order
3883
    // to have it properly initialized for this page request. However, no such
3884
    // page state API exists, so instead, ajax.js adds all of the in-use HTML
3885
    // IDs to the POST data of Ajax submissions. Direct use of $_POST is
3886
    // normally not recommended as it could open up security risks, but because
3887
    // the raw POST data is cast to a number before being returned by this
3888
    // function, this usage is safe.
3889
    if (empty($_POST['ajax_html_ids'])) {
3890
      $seen_ids_init = array();
3891
    }
3892
    else {
3893
      // This function ensures uniqueness by appending a counter to the base id
3894
      // requested by the calling function after the first occurrence of that
3895
      // requested id. $_POST['ajax_html_ids'] contains the ids as they were
3896
      // returned by this function, potentially with the appended counter, so
3897
      // we parse that to reconstruct the $seen_ids array.
3898
      if (isset($_POST['ajax_html_ids'][0]) && strpos($_POST['ajax_html_ids'][0], ',') === FALSE) {
3899
        $ajax_html_ids = $_POST['ajax_html_ids'];
3900
      }
3901
      else {
3902
        // jquery.form.js may send the server a comma-separated string as the
3903
        // first element of an array (see http://drupal.org/node/1575060), so
3904
        // we need to convert it to an array in that case.
3905
        $ajax_html_ids = explode(',', $_POST['ajax_html_ids'][0]);
3906
      }
3907
      foreach ($ajax_html_ids as $seen_id) {
3908
        // We rely on '--' being used solely for separating a base id from the
3909
        // counter, which this function ensures when returning an id.
3910
        $parts = explode('--', $seen_id, 2);
3911
        if (!empty($parts[1]) && is_numeric($parts[1])) {
3912
          list($seen_id, $i) = $parts;
3913
        }
3914
        else {
3915
          $i = 1;
3916
        }
3917
        if (!isset($seen_ids_init[$seen_id]) || ($i > $seen_ids_init[$seen_id])) {
3918
          $seen_ids_init[$seen_id] = $i;
3919
        }
3920
      }
3921
    }
3922
  }
3923
  $seen_ids = &drupal_static(__FUNCTION__, $seen_ids_init);
3924

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

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

    
3935
  // Removing multiple consecutive hyphens.
3936
  $id = preg_replace('/\-+/', '-', $id);
3937
  // Ensure IDs are unique by appending a counter after the first occurrence.
3938
  // The counter needs to be appended with a delimiter that does not exist in
3939
  // the base ID. Requiring a unique delimiter helps ensure that we really do
3940
  // return unique IDs and also helps us re-create the $seen_ids array during
3941
  // Ajax requests.
3942
  if (isset($seen_ids[$id])) {
3943
    $id = $id . '--' . ++$seen_ids[$id];
3944
  }
3945
  else {
3946
    $seen_ids[$id] = 1;
3947
  }
3948

    
3949
  return $id;
3950
}
3951

    
3952
/**
3953
 * Provides a standard HTML class name that identifies a page region.
3954
 *
3955
 * It is recommended that template preprocess functions apply this class to any
3956
 * page region that is output by the theme (Drupal core already handles this in
3957
 * the standard template preprocess implementation). Standardizing the class
3958
 * names in this way allows modules to implement certain features, such as
3959
 * drag-and-drop or dynamic Ajax loading, in a theme-independent way.
3960
 *
3961
 * @param $region
3962
 *   The name of the page region (for example, 'page_top' or 'content').
3963
 *
3964
 * @return
3965
 *   An HTML class that identifies the region (for example, 'region-page-top'
3966
 *   or 'region-content').
3967
 *
3968
 * @see template_preprocess_region()
3969
 */
3970
function drupal_region_class($region) {
3971
  return drupal_html_class("region-$region");
3972
}
3973

    
3974
/**
3975
 * Adds a JavaScript file, setting, or inline code to the page.
3976
 *
3977
 * The behavior of this function depends on the parameters it is called with.
3978
 * Generally, it handles the addition of JavaScript to the page, either as
3979
 * reference to an existing file or as inline code. The following actions can be
3980
 * performed using this function:
3981
 * - Add a file ('file'): Adds a reference to a JavaScript file to the page.
3982
 * - Add inline JavaScript code ('inline'): Executes a piece of JavaScript code
3983
 *   on the current page by placing the code directly in the page (for example,
3984
 *   to tell the user that a new message arrived, by opening a pop up, alert
3985
 *   box, etc.). This should only be used for JavaScript that cannot be executed
3986
 *   from a file. When adding inline code, make sure that you are not relying on
3987
 *   $() being the jQuery function. Wrap your code in
3988
 *   @code (function ($) {... })(jQuery); @endcode
3989
 *   or use jQuery() instead of $().
3990
 * - Add external JavaScript ('external'): Allows the inclusion of external
3991
 *   JavaScript files that are not hosted on the local server. Note that these
3992
 *   external JavaScript references do not get aggregated when preprocessing is
3993
 *   on.
3994
 * - Add settings ('setting'): Adds settings to Drupal's global storage of
3995
 *   JavaScript settings. Per-page settings are required by some modules to
3996
 *   function properly. All settings will be accessible at Drupal.settings.
3997
 *
3998
 * Examples:
3999
 * @code
4000
 *   drupal_add_js('misc/collapse.js');
4001
 *   drupal_add_js('misc/collapse.js', 'file');
4002
 *   drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
4003
 *   drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
4004
 *     array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
4005
 *   );
4006
 *   drupal_add_js('http://example.com/example.js', 'external');
4007
 *   drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');
4008
 * @endcode
4009
 *
4010
 * Calling drupal_static_reset('drupal_add_js') will clear all JavaScript added
4011
 * so far.
4012
 *
4013
 * If JavaScript aggregation is enabled, all JavaScript files added with
4014
 * $options['preprocess'] set to TRUE will be merged into one aggregate file.
4015
 * Preprocessed inline JavaScript will not be aggregated into this single file.
4016
 * Externally hosted JavaScripts are never aggregated.
4017
 *
4018
 * The reason for aggregating the files is outlined quite thoroughly here:
4019
 * http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
4020
 * to request overhead, one bigger file just loads faster than two smaller ones
4021
 * half its size."
4022
 *
4023
 * $options['preprocess'] should be only set to TRUE when a file is required for
4024
 * all typical visitors and most pages of a site. It is critical that all
4025
 * preprocessed files are added unconditionally on every page, even if the
4026
 * files are not needed on a page. This is normally done by calling
4027
 * drupal_add_js() in a hook_init() implementation.
4028
 *
4029
 * Non-preprocessed files should only be added to the page when they are
4030
 * actually needed.
4031
 *
4032
 * @param $data
4033
 *   (optional) If given, the value depends on the $options parameter, or
4034
 *   $options['type'] if $options is passed as an associative array:
4035
 *   - 'file': Path to the file relative to base_path().
4036
 *   - 'inline': The JavaScript code that should be placed in the given scope.
4037
 *   - 'external': The absolute path to an external JavaScript file that is not
4038
 *     hosted on the local server. These files will not be aggregated if
4039
 *     JavaScript aggregation is enabled.
4040
 *   - 'setting': An associative array with configuration options. The array is
4041
 *     merged directly into Drupal.settings. All modules should wrap their
4042
 *     actual configuration settings in another variable to prevent conflicts in
4043
 *     the Drupal.settings namespace. Items added with a string key will replace
4044
 *     existing settings with that key; items with numeric array keys will be
4045
 *     added to the existing settings array.
4046
 * @param $options
4047
 *   (optional) A string defining the type of JavaScript that is being added in
4048
 *   the $data parameter ('file'/'setting'/'inline'/'external'), or an
4049
 *   associative array. JavaScript settings should always pass the string
4050
 *   'setting' only. Other types can have the following elements in the array:
4051
 *   - type: The type of JavaScript that is to be added to the page. Allowed
4052
 *     values are 'file', 'inline', 'external' or 'setting'. Defaults
4053
 *     to 'file'.
4054
 *   - scope: The location in which you want to place the script. Possible
4055
 *     values are 'header' or 'footer'. If your theme implements different
4056
 *     regions, you can also use these. Defaults to 'header'.
4057
 *   - group: A number identifying the group in which to add the JavaScript.
4058
 *     Available constants are:
4059
 *     - JS_LIBRARY: Any libraries, settings, or jQuery plugins.
4060
 *     - JS_DEFAULT: Any module-layer JavaScript.
4061
 *     - JS_THEME: Any theme-layer JavaScript.
4062
 *     The group number serves as a weight: JavaScript within a lower weight
4063
 *     group is presented on the page before JavaScript within a higher weight
4064
 *     group.
4065
 *   - every_page: For optimal front-end performance when aggregation is
4066
 *     enabled, this should be set to TRUE if the JavaScript is present on every
4067
 *     page of the website for users for whom it is present at all. This
4068
 *     defaults to FALSE. It is set to TRUE for JavaScript files that are added
4069
 *     via module and theme .info files. Modules that add JavaScript within
4070
 *     hook_init() implementations, or from other code that ensures that the
4071
 *     JavaScript is added to all website pages, should also set this flag to
4072
 *     TRUE. All JavaScript files within the same group and that have the
4073
 *     'every_page' flag set to TRUE and do not have 'preprocess' set to FALSE
4074
 *     are aggregated together into a single aggregate file, and that aggregate
4075
 *     file can be reused across a user's entire site visit, leading to faster
4076
 *     navigation between pages. However, JavaScript that is only needed on
4077
 *     pages less frequently visited, can be added by code that only runs for
4078
 *     those particular pages, and that code should not set the 'every_page'
4079
 *     flag. This minimizes the size of the aggregate file that the user needs
4080
 *     to download when first visiting the website. JavaScript without the
4081
 *     'every_page' flag is aggregated into a separate aggregate file. This
4082
 *     other aggregate file is likely to change from page to page, and each new
4083
 *     aggregate file needs to be downloaded when first encountered, so it
4084
 *     should be kept relatively small by ensuring that most commonly needed
4085
 *     JavaScript is added to every page.
4086
 *   - weight: A number defining the order in which the JavaScript is added to
4087
 *     the page relative to other JavaScript with the same 'scope', 'group',
4088
 *     and 'every_page' value. In some cases, the order in which the JavaScript
4089
 *     is presented on the page is very important. jQuery, for example, must be
4090
 *     added to the page before any jQuery code is run, so jquery.js uses the
4091
 *     JS_LIBRARY group and a weight of -20, jquery.once.js (a library drupal.js
4092
 *     depends on) uses the JS_LIBRARY group and a weight of -19, drupal.js uses
4093
 *     the JS_LIBRARY group and a weight of -1, other libraries use the
4094
 *     JS_LIBRARY group and a weight of 0 or higher, and all other scripts use
4095
 *     one of the other group constants. The exact ordering of JavaScript is as
4096
 *     follows:
4097
 *     - First by scope, with 'header' first, 'footer' last, and any other
4098
 *       scopes provided by a custom theme coming in between, as determined by
4099
 *       the theme.
4100
 *     - Then by group.
4101
 *     - Then by the 'every_page' flag, with TRUE coming before FALSE.
4102
 *     - Then by weight.
4103
 *     - Then by the order in which the JavaScript was added. For example, all
4104
 *       else being the same, JavaScript added by a call to drupal_add_js() that
4105
 *       happened later in the page request gets added to the page after one for
4106
 *       which drupal_add_js() happened earlier in the page request.
4107
 *   - defer: If set to TRUE, the defer attribute is set on the <script>
4108
 *     tag. Defaults to FALSE.
4109
 *   - cache: If set to FALSE, the JavaScript file is loaded anew on every page
4110
 *     call; in other words, it is not cached. Used only when 'type' references
4111
 *     a JavaScript file. Defaults to TRUE.
4112
 *   - preprocess: If TRUE and JavaScript aggregation is enabled, the script
4113
 *     file will be aggregated. Defaults to TRUE.
4114
 *
4115
 * @return
4116
 *   The current array of JavaScript files, settings, and in-line code,
4117
 *   including Drupal defaults, anything previously added with calls to
4118
 *   drupal_add_js(), and this function call's additions.
4119
 *
4120
 * @see drupal_get_js()
4121
 */
4122
function drupal_add_js($data = NULL, $options = NULL) {
4123
  $javascript = &drupal_static(__FUNCTION__, array());
4124

    
4125
  // Construct the options, taking the defaults into consideration.
4126
  if (isset($options)) {
4127
    if (!is_array($options)) {
4128
      $options = array('type' => $options);
4129
    }
4130
  }
4131
  else {
4132
    $options = array();
4133
  }
4134
  $options += drupal_js_defaults($data);
4135

    
4136
  // Preprocess can only be set if caching is enabled.
4137
  $options['preprocess'] = $options['cache'] ? $options['preprocess'] : FALSE;
4138

    
4139
  // Tweak the weight so that files of the same weight are included in the
4140
  // order of the calls to drupal_add_js().
4141
  $options['weight'] += count($javascript) / 1000;
4142

    
4143
  if (isset($data)) {
4144
    // Add jquery.js and drupal.js, as well as the basePath setting, the
4145
    // first time a JavaScript file is added.
4146
    if (empty($javascript)) {
4147
      // url() generates the prefix using hook_url_outbound_alter(). Instead of
4148
      // running the hook_url_outbound_alter() again here, extract the prefix
4149
      // from url().
4150
      url('', array('prefix' => &$prefix));
4151
      $javascript = array(
4152
        'settings' => array(
4153
          'data' => array(
4154
            array('basePath' => base_path()),
4155
            array('pathPrefix' => empty($prefix) ? '' : $prefix),
4156
          ),
4157
          'type' => 'setting',
4158
          'scope' => 'header',
4159
          'group' => JS_LIBRARY,
4160
          'every_page' => TRUE,
4161
          'weight' => 0,
4162
        ),
4163
        'misc/drupal.js' => array(
4164
          'data' => 'misc/drupal.js',
4165
          'type' => 'file',
4166
          'scope' => 'header',
4167
          'group' => JS_LIBRARY,
4168
          'every_page' => TRUE,
4169
          'weight' => -1,
4170
          'preprocess' => TRUE,
4171
          'cache' => TRUE,
4172
          'defer' => FALSE,
4173
        ),
4174
      );
4175
      // Register all required libraries.
4176
      drupal_add_library('system', 'jquery', TRUE);
4177
      drupal_add_library('system', 'jquery.once', TRUE);
4178
    }
4179

    
4180
    switch ($options['type']) {
4181
      case 'setting':
4182
        // All JavaScript settings are placed in the header of the page with
4183
        // the library weight so that inline scripts appear afterwards.
4184
        $javascript['settings']['data'][] = $data;
4185
        break;
4186

    
4187
      case 'inline':
4188
        $javascript[] = $options;
4189
        break;
4190

    
4191
      default: // 'file' and 'external'
4192
        // Local and external files must keep their name as the associative key
4193
        // so the same JavaScript file is not added twice.
4194
        $javascript[$options['data']] = $options;
4195
    }
4196
  }
4197
  return $javascript;
4198
}
4199

    
4200
/**
4201
 * Constructs an array of the defaults that are used for JavaScript items.
4202
 *
4203
 * @param $data
4204
 *   (optional) The default data parameter for the JavaScript item array.
4205
 *
4206
 * @see drupal_get_js()
4207
 * @see drupal_add_js()
4208
 */
4209
function drupal_js_defaults($data = NULL) {
4210
  return array(
4211
    'type' => 'file',
4212
    'group' => JS_DEFAULT,
4213
    'every_page' => FALSE,
4214
    'weight' => 0,
4215
    'scope' => 'header',
4216
    'cache' => TRUE,
4217
    'defer' => FALSE,
4218
    'preprocess' => TRUE,
4219
    'version' => NULL,
4220
    'data' => $data,
4221
  );
4222
}
4223

    
4224
/**
4225
 * Returns a themed presentation of all JavaScript code for the current page.
4226
 *
4227
 * References to JavaScript files are placed in a certain order: first, all
4228
 * 'core' files, then all 'module' and finally all 'theme' JavaScript files
4229
 * are added to the page. Then, all settings are output, followed by 'inline'
4230
 * JavaScript code. If running update.php, all preprocessing is disabled.
4231
 *
4232
 * Note that hook_js_alter(&$javascript) is called during this function call
4233
 * to allow alterations of the JavaScript during its presentation. Calls to
4234
 * drupal_add_js() from hook_js_alter() will not be added to the output
4235
 * presentation. The correct way to add JavaScript during hook_js_alter()
4236
 * is to add another element to the $javascript array, deriving from
4237
 * drupal_js_defaults(). See locale_js_alter() for an example of this.
4238
 *
4239
 * @param $scope
4240
 *   (optional) The scope for which the JavaScript rules should be returned.
4241
 *   Defaults to 'header'.
4242
 * @param $javascript
4243
 *   (optional) An array with all JavaScript code. Defaults to the default
4244
 *   JavaScript array for the given scope.
4245
 * @param $skip_alter
4246
 *   (optional) If set to TRUE, this function skips calling drupal_alter() on
4247
 *   $javascript, useful when the calling function passes a $javascript array
4248
 *   that has already been altered.
4249
 *
4250
 * @return
4251
 *   All JavaScript code segments and includes for the scope as HTML tags.
4252
 *
4253
 * @see drupal_add_js()
4254
 * @see locale_js_alter()
4255
 * @see drupal_js_defaults()
4256
 */
4257
function drupal_get_js($scope = 'header', $javascript = NULL, $skip_alter = FALSE) {
4258
  if (!isset($javascript)) {
4259
    $javascript = drupal_add_js();
4260
  }
4261
  if (empty($javascript)) {
4262
    return '';
4263
  }
4264

    
4265
  // Allow modules to alter the JavaScript.
4266
  if (!$skip_alter) {
4267
    drupal_alter('js', $javascript);
4268
  }
4269

    
4270
  // Filter out elements of the given scope.
4271
  $items = array();
4272
  foreach ($javascript as $key => $item) {
4273
    if ($item['scope'] == $scope) {
4274
      $items[$key] = $item;
4275
    }
4276
  }
4277

    
4278
  $output = '';
4279
  // The index counter is used to keep aggregated and non-aggregated files in
4280
  // order by weight.
4281
  $index = 1;
4282
  $processed = array();
4283
  $files = array();
4284
  $preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
4285

    
4286
  // A dummy query-string is added to filenames, to gain control over
4287
  // browser-caching. The string changes on every update or full cache
4288
  // flush, forcing browsers to load a new copy of the files, as the
4289
  // URL changed. Files that should not be cached (see drupal_add_js())
4290
  // get REQUEST_TIME as query-string instead, to enforce reload on every
4291
  // page request.
4292
  $default_query_string = variable_get('css_js_query_string', '0');
4293

    
4294
  // For inline JavaScript to validate as XHTML, all JavaScript containing
4295
  // XHTML needs to be wrapped in CDATA. To make that backwards compatible
4296
  // with HTML 4, we need to comment out the CDATA-tag.
4297
  $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
4298
  $embed_suffix = "\n//--><!]]>\n";
4299

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

    
4304
  // Sort the JavaScript so that it appears in the correct order.
4305
  uasort($items, 'drupal_sort_css_js');
4306

    
4307
  // Provide the page with information about the individual JavaScript files
4308
  // used, information not otherwise available when aggregation is enabled.
4309
  $setting['ajaxPageState']['js'] = array_fill_keys(array_keys($items), 1);
4310
  unset($setting['ajaxPageState']['js']['settings']);
4311
  drupal_add_js($setting, 'setting');
4312

    
4313
  // If we're outputting the header scope, then this might be the final time
4314
  // that drupal_get_js() is running, so add the setting to this output as well
4315
  // as to the drupal_add_js() cache. If $items['settings'] doesn't exist, it's
4316
  // because drupal_get_js() was intentionally passed a $javascript argument
4317
  // stripped off settings, potentially in order to override how settings get
4318
  // output, so in this case, do not add the setting to this output.
4319
  if ($scope == 'header' && isset($items['settings'])) {
4320
    $items['settings']['data'][] = $setting;
4321
  }
4322

    
4323
  // Loop through the JavaScript to construct the rendered output.
4324
  $element = array(
4325
    '#tag' => 'script',
4326
    '#value' => '',
4327
    '#attributes' => array(
4328
      'type' => 'text/javascript',
4329
    ),
4330
  );
4331
  foreach ($items as $item) {
4332
    $query_string =  empty($item['version']) ? $default_query_string : $js_version_string . $item['version'];
4333

    
4334
    switch ($item['type']) {
4335
      case 'setting':
4336
        $js_element = $element;
4337
        $js_element['#value_prefix'] = $embed_prefix;
4338
        $js_element['#value'] = 'jQuery.extend(Drupal.settings, ' . drupal_json_encode(drupal_array_merge_deep_array($item['data'])) . ");";
4339
        $js_element['#value_suffix'] = $embed_suffix;
4340
        $output .= theme('html_tag', array('element' => $js_element));
4341
        break;
4342

    
4343
      case 'inline':
4344
        $js_element = $element;
4345
        if ($item['defer']) {
4346
          $js_element['#attributes']['defer'] = 'defer';
4347
        }
4348
        $js_element['#value_prefix'] = $embed_prefix;
4349
        $js_element['#value'] = $item['data'];
4350
        $js_element['#value_suffix'] = $embed_suffix;
4351
        $processed[$index++] = theme('html_tag', array('element' => $js_element));
4352
        break;
4353

    
4354
      case 'file':
4355
        $js_element = $element;
4356
        if (!$item['preprocess'] || !$preprocess_js) {
4357
          if ($item['defer']) {
4358
            $js_element['#attributes']['defer'] = 'defer';
4359
          }
4360
          $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
4361
          $js_element['#attributes']['src'] = file_create_url($item['data']) . $query_string_separator . ($item['cache'] ? $query_string : REQUEST_TIME);
4362
          $processed[$index++] = theme('html_tag', array('element' => $js_element));
4363
        }
4364
        else {
4365
          // By increasing the index for each aggregated file, we maintain
4366
          // the relative ordering of JS by weight. We also set the key such
4367
          // that groups are split by items sharing the same 'group' value and
4368
          // 'every_page' flag. While this potentially results in more aggregate
4369
          // files, it helps make each one more reusable across a site visit,
4370
          // leading to better front-end performance of a website as a whole.
4371
          // See drupal_add_js() for details.
4372
          $key = 'aggregate_' . $item['group'] . '_' . $item['every_page'] . '_' . $index;
4373
          $processed[$key] = '';
4374
          $files[$key][$item['data']] = $item;
4375
        }
4376
        break;
4377

    
4378
      case 'external':
4379
        $js_element = $element;
4380
        // Preprocessing for external JavaScript files is ignored.
4381
        if ($item['defer']) {
4382
          $js_element['#attributes']['defer'] = 'defer';
4383
        }
4384
        $js_element['#attributes']['src'] = $item['data'];
4385
        $processed[$index++] = theme('html_tag', array('element' => $js_element));
4386
        break;
4387
    }
4388
  }
4389

    
4390
  // Aggregate any remaining JS files that haven't already been output.
4391
  if ($preprocess_js && count($files) > 0) {
4392
    foreach ($files as $key => $file_set) {
4393
      $uri = drupal_build_js_cache($file_set);
4394
      // Only include the file if was written successfully. Errors are logged
4395
      // using watchdog.
4396
      if ($uri) {
4397
        $preprocess_file = file_create_url($uri);
4398
        $js_element = $element;
4399
        $js_element['#attributes']['src'] = $preprocess_file;
4400
        $processed[$key] = theme('html_tag', array('element' => $js_element));
4401
      }
4402
    }
4403
  }
4404

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

    
4410
/**
4411
 * Adds attachments to a render() structure.
4412
 *
4413
 * Libraries, JavaScript, CSS and other types of custom structures are attached
4414
 * to elements using the #attached property. The #attached property is an
4415
 * associative array, where the keys are the the attachment types and the values
4416
 * are the attached data. For example:
4417
 * @code
4418
 * $build['#attached'] = array(
4419
 *   'js' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.js'),
4420
 *   'css' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.css'),
4421
 * );
4422
 * @endcode
4423
 *
4424
 * 'js', 'css', and 'library' are types that get special handling. For any
4425
 * other kind of attached data, the array key must be the full name of the
4426
 * callback function and each value an array of arguments. For example:
4427
 * @code
4428
 * $build['#attached']['drupal_add_http_header'] = array(
4429
 *   array('Content-Type', 'application/rss+xml; charset=utf-8'),
4430
 * );
4431
 * @endcode
4432
 *
4433
 * External 'js' and 'css' files can also be loaded. For example:
4434
 * @code
4435
 * $build['#attached']['js'] = array(
4436
 *   'http://code.jquery.com/jquery-1.4.2.min.js' => array(
4437
 *     'type' => 'external',
4438
 *   ),
4439
 * );
4440
 * @endcode
4441
 *
4442
 * @param $elements
4443
 *   The structured array describing the data being rendered.
4444
 * @param $group
4445
 *   The default group of JavaScript and CSS being added. This is only applied
4446
 *   to the stylesheets and JavaScript items that don't have an explicit group
4447
 *   assigned to them.
4448
 * @param $dependency_check
4449
 *   When TRUE, will exit if a given library's dependencies are missing. When
4450
 *   set to FALSE, will continue to add the libraries, even though one or more
4451
 *   dependencies are missing. Defaults to FALSE.
4452
 * @param $every_page
4453
 *   Set to TRUE to indicate that the attachments are added to every page on the
4454
 *   site. Only attachments with the every_page flag set to TRUE can participate
4455
 *   in JavaScript/CSS aggregation.
4456
 *
4457
 * @return
4458
 *   FALSE if there were any missing library dependencies; TRUE if all library
4459
 *   dependencies were met.
4460
 *
4461
 * @see drupal_add_library()
4462
 * @see drupal_add_js()
4463
 * @see drupal_add_css()
4464
 * @see drupal_render()
4465
 */
4466
function drupal_process_attached($elements, $group = JS_DEFAULT, $dependency_check = FALSE, $every_page = NULL) {
4467
  // Add defaults to the special attached structures that should be processed differently.
4468
  $elements['#attached'] += array(
4469
    'library' => array(),
4470
    'js' => array(),
4471
    'css' => array(),
4472
  );
4473

    
4474
  // Add the libraries first.
4475
  $success = TRUE;
4476
  foreach ($elements['#attached']['library'] as $library) {
4477
    if (drupal_add_library($library[0], $library[1], $every_page) === FALSE) {
4478
      $success = FALSE;
4479
      // Exit if the dependency is missing.
4480
      if ($dependency_check) {
4481
        return $success;
4482
      }
4483
    }
4484
  }
4485
  unset($elements['#attached']['library']);
4486

    
4487
  // Add both the JavaScript and the CSS.
4488
  // The parameters for drupal_add_js() and drupal_add_css() require special
4489
  // handling.
4490
  foreach (array('js', 'css') as $type) {
4491
    foreach ($elements['#attached'][$type] as $data => $options) {
4492
      // If the value is not an array, it's a filename and passed as first
4493
      // (and only) argument.
4494
      if (!is_array($options)) {
4495
        $data = $options;
4496
        $options = NULL;
4497
      }
4498
      // In some cases, the first parameter ($data) is an array. Arrays can't be
4499
      // passed as keys in PHP, so we have to get $data from the value array.
4500
      if (is_numeric($data)) {
4501
        $data = $options['data'];
4502
        unset($options['data']);
4503
      }
4504
      // Apply the default group if it isn't explicitly given.
4505
      if (!isset($options['group'])) {
4506
        $options['group'] = $group;
4507
      }
4508
      // Set the every_page flag if one was passed.
4509
      if (isset($every_page)) {
4510
        $options['every_page'] = $every_page;
4511
      }
4512
      call_user_func('drupal_add_' . $type, $data, $options);
4513
    }
4514
    unset($elements['#attached'][$type]);
4515
  }
4516

    
4517
  // Add additional types of attachments specified in the render() structure.
4518
  // Libraries, JavaScript and CSS have been added already, as they require
4519
  // special handling.
4520
  foreach ($elements['#attached'] as $callback => $options) {
4521
    if (function_exists($callback)) {
4522
      foreach ($elements['#attached'][$callback] as $args) {
4523
        call_user_func_array($callback, $args);
4524
      }
4525
    }
4526
  }
4527

    
4528
  return $success;
4529
}
4530

    
4531
/**
4532
 * Adds JavaScript to change the state of an element based on another element.
4533
 *
4534
 * A "state" means a certain property on a DOM element, such as "visible" or
4535
 * "checked". A state can be applied to an element, depending on the state of
4536
 * another element on the page. In general, states depend on HTML attributes and
4537
 * DOM element properties, which change due to user interaction.
4538
 *
4539
 * Since states are driven by JavaScript only, it is important to understand
4540
 * that all states are applied on presentation only, none of the states force
4541
 * any server-side logic, and that they will not be applied for site visitors
4542
 * without JavaScript support. All modules implementing states have to make
4543
 * sure that the intended logic also works without JavaScript being enabled.
4544
 *
4545
 * #states is an associative array in the form of:
4546
 * @code
4547
 * array(
4548
 *   STATE1 => CONDITIONS_ARRAY1,
4549
 *   STATE2 => CONDITIONS_ARRAY2,
4550
 *   ...
4551
 * )
4552
 * @endcode
4553
 * Each key is the name of a state to apply to the element, such as 'visible'.
4554
 * Each value is a list of conditions that denote when the state should be
4555
 * applied.
4556
 *
4557
 * Multiple different states may be specified to act on complex conditions:
4558
 * @code
4559
 * array(
4560
 *   'visible' => CONDITIONS,
4561
 *   'checked' => OTHER_CONDITIONS,
4562
 * )
4563
 * @endcode
4564
 *
4565
 * Every condition is a key/value pair, whose key is a jQuery selector that
4566
 * denotes another element on the page, and whose value is an array of
4567
 * conditions, which must bet met on that element:
4568
 * @code
4569
 * array(
4570
 *   'visible' => array(
4571
 *     JQUERY_SELECTOR => REMOTE_CONDITIONS,
4572
 *     JQUERY_SELECTOR => REMOTE_CONDITIONS,
4573
 *     ...
4574
 *   ),
4575
 * )
4576
 * @endcode
4577
 * All conditions must be met for the state to be applied.
4578
 *
4579
 * Each remote condition is a key/value pair specifying conditions on the other
4580
 * element that need to be met to apply the state to the element:
4581
 * @code
4582
 * array(
4583
 *   'visible' => array(
4584
 *     ':input[name="remote_checkbox"]' => array('checked' => TRUE),
4585
 *   ),
4586
 * )
4587
 * @endcode
4588
 *
4589
 * For example, to show a textfield only when a checkbox is checked:
4590
 * @code
4591
 * $form['toggle_me'] = array(
4592
 *   '#type' => 'checkbox',
4593
 *   '#title' => t('Tick this box to type'),
4594
 * );
4595
 * $form['settings'] = array(
4596
 *   '#type' => 'textfield',
4597
 *   '#states' => array(
4598
 *     // Only show this field when the 'toggle_me' checkbox is enabled.
4599
 *     'visible' => array(
4600
 *       ':input[name="toggle_me"]' => array('checked' => TRUE),
4601
 *     ),
4602
 *   ),
4603
 * );
4604
 * @endcode
4605
 *
4606
 * The following states may be applied to an element:
4607
 * - enabled
4608
 * - disabled
4609
 * - required
4610
 * - optional
4611
 * - visible
4612
 * - invisible
4613
 * - checked
4614
 * - unchecked
4615
 * - expanded
4616
 * - collapsed
4617
 *
4618
 * The following states may be used in remote conditions:
4619
 * - empty
4620
 * - filled
4621
 * - checked
4622
 * - unchecked
4623
 * - expanded
4624
 * - collapsed
4625
 * - value
4626
 *
4627
 * The following states exist for both elements and remote conditions, but are
4628
 * not fully implemented and may not change anything on the element:
4629
 * - relevant
4630
 * - irrelevant
4631
 * - valid
4632
 * - invalid
4633
 * - touched
4634
 * - untouched
4635
 * - readwrite
4636
 * - readonly
4637
 *
4638
 * When referencing select lists and radio buttons in remote conditions, a
4639
 * 'value' condition must be used:
4640
 * @code
4641
 *   '#states' => array(
4642
 *     // Show the settings if 'bar' has been selected for 'foo'.
4643
 *     'visible' => array(
4644
 *       ':input[name="foo"]' => array('value' => 'bar'),
4645
 *     ),
4646
 *   ),
4647
 * @endcode
4648
 *
4649
 * @param $elements
4650
 *   A renderable array element having a #states property as described above.
4651
 *
4652
 * @see form_example_states_form()
4653
 */
4654
function drupal_process_states(&$elements) {
4655
  $elements['#attached']['library'][] = array('system', 'drupal.states');
4656
  $elements['#attached']['js'][] = array(
4657
    'type' => 'setting',
4658
    'data' => array('states' => array('#' . $elements['#id'] => $elements['#states'])),
4659
  );
4660
}
4661

    
4662
/**
4663
 * Adds multiple JavaScript or CSS files at the same time.
4664
 *
4665
 * A library defines a set of JavaScript and/or CSS files, optionally using
4666
 * settings, and optionally requiring another library. For example, a library
4667
 * can be a jQuery plugin, a JavaScript framework, or a CSS framework. This
4668
 * function allows modules to load a library defined/shipped by itself or a
4669
 * depending module, without having to add all files of the library separately.
4670
 * Each library is only loaded once.
4671
 *
4672
 * @param $module
4673
 *   The name of the module that registered the library.
4674
 * @param $name
4675
 *   The name of the library to add.
4676
 * @param $every_page
4677
 *   Set to TRUE if this library is added to every page on the site. Only items
4678
 *   with the every_page flag set to TRUE can participate in aggregation.
4679
 *
4680
 * @return
4681
 *   TRUE if the library was successfully added; FALSE if the library or one of
4682
 *   its dependencies could not be added.
4683
 *
4684
 * @see drupal_get_library()
4685
 * @see hook_library()
4686
 * @see hook_library_alter()
4687
 */
4688
function drupal_add_library($module, $name, $every_page = NULL) {
4689
  $added = &drupal_static(__FUNCTION__, array());
4690

    
4691
  // Only process the library if it exists and it was not added already.
4692
  if (!isset($added[$module][$name])) {
4693
    if ($library = drupal_get_library($module, $name)) {
4694
      // Add all components within the library.
4695
      $elements['#attached'] = array(
4696
        'library' => $library['dependencies'],
4697
        'js' => $library['js'],
4698
        'css' => $library['css'],
4699
      );
4700
      $added[$module][$name] = drupal_process_attached($elements, JS_LIBRARY, TRUE, $every_page);
4701
    }
4702
    else {
4703
      // Requested library does not exist.
4704
      $added[$module][$name] = FALSE;
4705
    }
4706
  }
4707

    
4708
  return $added[$module][$name];
4709
}
4710

    
4711
/**
4712
 * Retrieves information for a JavaScript/CSS library.
4713
 *
4714
 * Library information is statically cached. Libraries are keyed by module for
4715
 * several reasons:
4716
 * - Libraries are not unique. Multiple modules might ship with the same library
4717
 *   in a different version or variant. This registry cannot (and does not
4718
 *   attempt to) prevent library conflicts.
4719
 * - Modules implementing and thereby depending on a library that is registered
4720
 *   by another module can only rely on that module's library.
4721
 * - Two (or more) modules can still register the same library and use it
4722
 *   without conflicts in case the libraries are loaded on certain pages only.
4723
 *
4724
 * @param $module
4725
 *   The name of a module that registered a library.
4726
 * @param $name
4727
 *   (optional) The name of a registered library to retrieve. By default, all
4728
 *   libraries registered by $module are returned.
4729
 *
4730
 * @return
4731
 *   The definition of the requested library, if $name was passed and it exists,
4732
 *   or FALSE if it does not exist. If no $name was passed, an associative array
4733
 *   of libraries registered by $module is returned (which may be empty).
4734
 *
4735
 * @see drupal_add_library()
4736
 * @see hook_library()
4737
 * @see hook_library_alter()
4738
 *
4739
 * @todo The purpose of drupal_get_*() is completely different to other page
4740
 *   requisite API functions; find and use a different name.
4741
 */
4742
function drupal_get_library($module, $name = NULL) {
4743
  $libraries = &drupal_static(__FUNCTION__, array());
4744

    
4745
  if (!isset($libraries[$module])) {
4746
    // Retrieve all libraries associated with the module.
4747
    $module_libraries = module_invoke($module, 'library');
4748
    if (empty($module_libraries)) {
4749
      $module_libraries = array();
4750
    }
4751
    // Allow modules to alter the module's registered libraries.
4752
    drupal_alter('library', $module_libraries, $module);
4753

    
4754
    foreach ($module_libraries as $key => $data) {
4755
      if (is_array($data)) {
4756
        // Add default elements to allow for easier processing.
4757
        $module_libraries[$key] += array('dependencies' => array(), 'js' => array(), 'css' => array());
4758
        foreach ($module_libraries[$key]['js'] as $file => $options) {
4759
          $module_libraries[$key]['js'][$file]['version'] = $module_libraries[$key]['version'];
4760
        }
4761
      }
4762
    }
4763
    $libraries[$module] = $module_libraries;
4764
  }
4765
  if (isset($name)) {
4766
    if (!isset($libraries[$module][$name])) {
4767
      $libraries[$module][$name] = FALSE;
4768
    }
4769
    return $libraries[$module][$name];
4770
  }
4771
  return $libraries[$module];
4772
}
4773

    
4774
/**
4775
 * Assists in adding the tableDrag JavaScript behavior to a themed table.
4776
 *
4777
 * Draggable tables should be used wherever an outline or list of sortable items
4778
 * needs to be arranged by an end-user. Draggable tables are very flexible and
4779
 * can manipulate the value of form elements placed within individual columns.
4780
 *
4781
 * To set up a table to use drag and drop in place of weight select-lists or in
4782
 * place of a form that contains parent relationships, the form must be themed
4783
 * into a table. The table must have an ID attribute set. If using
4784
 * theme_table(), the ID may be set as follows:
4785
 * @code
4786
 * $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'my-module-table')));
4787
 * return $output;
4788
 * @endcode
4789
 *
4790
 * In the theme function for the form, a special class must be added to each
4791
 * form element within the same column, "grouping" them together.
4792
 *
4793
 * In a situation where a single weight column is being sorted in the table, the
4794
 * classes could be added like this (in the theme function):
4795
 * @code
4796
 * $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
4797
 * @endcode
4798
 *
4799
 * Each row of the table must also have a class of "draggable" in order to
4800
 * enable the drag handles:
4801
 * @code
4802
 * $row = array(...);
4803
 * $rows[] = array(
4804
 *   'data' => $row,
4805
 *   'class' => array('draggable'),
4806
 * );
4807
 * @endcode
4808
 *
4809
 * When tree relationships are present, the two additional classes
4810
 * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
4811
 * - Rows with the 'tabledrag-leaf' class cannot have child rows.
4812
 * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
4813
 *
4814
 * Calling drupal_add_tabledrag() would then be written as such:
4815
 * @code
4816
 * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
4817
 * @endcode
4818
 *
4819
 * In a more complex case where there are several groups in one column (such as
4820
 * the block regions on the admin/structure/block page), a separate subgroup
4821
 * class must also be added to differentiate the groups.
4822
 * @code
4823
 * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
4824
 * @endcode
4825
 *
4826
 * $group is still 'my-element-weight', and the additional $subgroup variable
4827
 * will be passed in as 'my-elements-weight-' . $region. This also means that
4828
 * you'll need to call drupal_add_tabledrag() once for every region added.
4829
 *
4830
 * @code
4831
 * foreach ($regions as $region) {
4832
 *   drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight', 'my-elements-weight-' . $region);
4833
 * }
4834
 * @endcode
4835
 *
4836
 * In a situation where tree relationships are present, adding multiple
4837
 * subgroups is not necessary, because the table will contain indentations that
4838
 * provide enough information about the sibling and parent relationships. See
4839
 * theme_menu_overview_form() for an example creating a table containing parent
4840
 * relationships.
4841
 *
4842
 * Note that this function should be called from the theme layer, such as in a
4843
 * .tpl.php file, theme_ function, or in a template_preprocess function, not in
4844
 * a form declaration. Though the same JavaScript could be added to the page
4845
 * using drupal_add_js() directly, this function helps keep template files
4846
 * clean and readable. It also prevents tabledrag.js from being added twice
4847
 * accidentally.
4848
 *
4849
 * @param $table_id
4850
 *   String containing the target table's id attribute. If the table does not
4851
 *   have an id, one will need to be set, such as <table id="my-module-table">.
4852
 * @param $action
4853
 *   String describing the action to be done on the form item. Either 'match'
4854
 *   'depth', or 'order'. Match is typically used for parent relationships.
4855
 *   Order is typically used to set weights on other form elements with the same
4856
 *   group. Depth updates the target element with the current indentation.
4857
 * @param $relationship
4858
 *   String describing where the $action variable should be performed. Either
4859
 *   'parent', 'sibling', 'group', or 'self'. Parent will only look for fields
4860
 *   up the tree. Sibling will look for fields in the same group in rows above
4861
 *   and below it. Self affects the dragged row itself. Group affects the
4862
 *   dragged row, plus any children below it (the entire dragged group).
4863
 * @param $group
4864
 *   A class name applied on all related form elements for this action.
4865
 * @param $subgroup
4866
 *   (optional) If the group has several subgroups within it, this string should
4867
 *   contain the class name identifying fields in the same subgroup.
4868
 * @param $source
4869
 *   (optional) If the $action is 'match', this string should contain the class
4870
 *   name identifying what field will be used as the source value when matching
4871
 *   the value in $subgroup.
4872
 * @param $hidden
4873
 *   (optional) The column containing the field elements may be entirely hidden
4874
 *   from view dynamically when the JavaScript is loaded. Set to FALSE if the
4875
 *   column should not be hidden.
4876
 * @param $limit
4877
 *   (optional) Limit the maximum amount of parenting in this table.
4878
 * @see block-admin-display-form.tpl.php
4879
 * @see theme_menu_overview_form()
4880
 */
4881
function drupal_add_tabledrag($table_id, $action, $relationship, $group, $subgroup = NULL, $source = NULL, $hidden = TRUE, $limit = 0) {
4882
  $js_added = &drupal_static(__FUNCTION__, FALSE);
4883
  if (!$js_added) {
4884
    // Add the table drag JavaScript to the page before the module JavaScript
4885
    // to ensure that table drag behaviors are registered before any module
4886
    // uses it.
4887
    drupal_add_library('system', 'jquery.cookie');
4888
    drupal_add_js('misc/tabledrag.js', array('weight' => -1));
4889
    $js_added = TRUE;
4890
  }
4891

    
4892
  // If a subgroup or source isn't set, assume it is the same as the group.
4893
  $target = isset($subgroup) ? $subgroup : $group;
4894
  $source = isset($source) ? $source : $target;
4895
  $settings['tableDrag'][$table_id][$group][] = array(
4896
    'target' => $target,
4897
    'source' => $source,
4898
    'relationship' => $relationship,
4899
    'action' => $action,
4900
    'hidden' => $hidden,
4901
    'limit' => $limit,
4902
  );
4903
  drupal_add_js($settings, 'setting');
4904
}
4905

    
4906
/**
4907
 * Aggregates JavaScript files into a cache file in the files directory.
4908
 *
4909
 * The file name for the JavaScript cache file is generated from the hash of
4910
 * the aggregated contents of the files in $files. This forces proxies and
4911
 * browsers to download new JavaScript when the JavaScript changes.
4912
 *
4913
 * The cache file name is retrieved on a page load via a lookup variable that
4914
 * contains an associative array. The array key is the hash of the names in
4915
 * $files while the value is the cache file name. The cache file is generated
4916
 * in two cases. First, if there is no file name value for the key, which will
4917
 * happen if a new file name has been added to $files or after the lookup
4918
 * variable is emptied to force a rebuild of the cache. Second, the cache file
4919
 * is generated if it is missing on disk. Old cache files are not deleted
4920
 * immediately when the lookup variable is emptied, but are deleted after a set
4921
 * period by drupal_delete_file_if_stale(). This ensures that files referenced
4922
 * by a cached page will still be available.
4923
 *
4924
 * @param $files
4925
 *   An array of JavaScript files to aggregate and compress into one file.
4926
 *
4927
 * @return
4928
 *   The URI of the cache file, or FALSE if the file could not be saved.
4929
 */
4930
function drupal_build_js_cache($files) {
4931
  $contents = '';
4932
  $uri = '';
4933
  $map = variable_get('drupal_js_cache_files', array());
4934
  // Create a new array so that only the file names are used to create the hash.
4935
  // This prevents new aggregates from being created unnecessarily.
4936
  $js_data = array();
4937
  foreach ($files as $file) {
4938
    $js_data[] = $file['data'];
4939
  }
4940
  $key = hash('sha256', serialize($js_data));
4941
  if (isset($map[$key])) {
4942
    $uri = $map[$key];
4943
  }
4944

    
4945
  if (empty($uri) || !file_exists($uri)) {
4946
    // Build aggregate JS file.
4947
    foreach ($files as $path => $info) {
4948
      if ($info['preprocess']) {
4949
        // Append a ';' and a newline after each JS file to prevent them from running together.
4950
        $contents .= file_get_contents($path) . ";\n";
4951
      }
4952
    }
4953
    // Prefix filename to prevent blocking by firewalls which reject files
4954
    // starting with "ad*".
4955
    $filename = 'js_' . drupal_hash_base64($contents) . '.js';
4956
    // Create the js/ within the files folder.
4957
    $jspath = 'public://js';
4958
    $uri = $jspath . '/' . $filename;
4959
    // Create the JS file.
4960
    file_prepare_directory($jspath, FILE_CREATE_DIRECTORY);
4961
    if (!file_exists($uri) && !file_unmanaged_save_data($contents, $uri, FILE_EXISTS_REPLACE)) {
4962
      return FALSE;
4963
    }
4964
    // If JS gzip compression is enabled, clean URLs are enabled (which means
4965
    // that rewrite rules are working) and the zlib extension is available then
4966
    // create a gzipped version of this file. This file is served conditionally
4967
    // to browsers that accept gzip using .htaccess rules.
4968
    if (variable_get('js_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
4969
      if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($contents, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
4970
        return FALSE;
4971
      }
4972
    }
4973
    $map[$key] = $uri;
4974
    variable_set('drupal_js_cache_files', $map);
4975
  }
4976
  return $uri;
4977
}
4978

    
4979
/**
4980
 * Deletes old cached JavaScript files and variables.
4981
 */
4982
function drupal_clear_js_cache() {
4983
  variable_del('javascript_parsed');
4984
  variable_del('drupal_js_cache_files');
4985
  file_scan_directory('public://js', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
4986
}
4987

    
4988
/**
4989
 * Converts a PHP variable into its JavaScript equivalent.
4990
 *
4991
 * We use HTML-safe strings, with several characters escaped.
4992
 *
4993
 * @see drupal_json_decode()
4994
 * @see drupal_json_encode_helper()
4995
 * @ingroup php_wrappers
4996
 */
4997
function drupal_json_encode($var) {
4998
  // The PHP version cannot change within a request.
4999
  static $php530;
5000

    
5001
  if (!isset($php530)) {
5002
    $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
5003
  }
5004

    
5005
  if ($php530) {
5006
    // Encode <, >, ', &, and " using the json_encode() options parameter.
5007
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
5008
  }
5009

    
5010
  // json_encode() escapes <, >, ', &, and " using its options parameter, but
5011
  // does not support this parameter prior to PHP 5.3.0.  Use a helper instead.
5012
  include_once DRUPAL_ROOT . '/includes/json-encode.inc';
5013
  return drupal_json_encode_helper($var);
5014
}
5015

    
5016
/**
5017
 * Converts an HTML-safe JSON string into its PHP equivalent.
5018
 *
5019
 * @see drupal_json_encode()
5020
 * @ingroup php_wrappers
5021
 */
5022
function drupal_json_decode($var) {
5023
  return json_decode($var, TRUE);
5024
}
5025

    
5026
/**
5027
 * Returns data in JSON format.
5028
 *
5029
 * This function should be used for JavaScript callback functions returning
5030
 * data in JSON format. It sets the header for JavaScript output.
5031
 *
5032
 * @param $var
5033
 *   (optional) If set, the variable will be converted to JSON and output.
5034
 */
5035
function drupal_json_output($var = NULL) {
5036
  // We are returning JSON, so tell the browser.
5037
  drupal_add_http_header('Content-Type', 'application/json');
5038

    
5039
  if (isset($var)) {
5040
    echo drupal_json_encode($var);
5041
  }
5042
}
5043

    
5044
/**
5045
 * Ensures the private key variable used to generate tokens is set.
5046
 *
5047
 * @return
5048
 *   The private key.
5049
 */
5050
function drupal_get_private_key() {
5051
  if (!($key = variable_get('drupal_private_key', 0))) {
5052
    $key = drupal_random_key();
5053
    variable_set('drupal_private_key', $key);
5054
  }
5055
  return $key;
5056
}
5057

    
5058
/**
5059
 * Generates a token based on $value, the user session, and the private key.
5060
 *
5061
 * @param $value
5062
 *   An additional value to base the token on.
5063
 *
5064
 * The generated token is based on the session ID of the current user. Normally,
5065
 * anonymous users do not have a session, so the generated token will be
5066
 * different on every page request. To generate a token for users without a
5067
 * session, manually start a session prior to calling this function.
5068
 *
5069
 * @return string
5070
 *   A 43-character URL-safe token for validation, based on the user session ID,
5071
 *   the hash salt provided from drupal_get_hash_salt(), and the
5072
 *   'drupal_private_key' configuration variable.
5073
 *
5074
 * @see drupal_get_hash_salt()
5075
 */
5076
function drupal_get_token($value = '') {
5077
  return drupal_hmac_base64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());
5078
}
5079

    
5080
/**
5081
 * Validates a token based on $value, the user session, and the private key.
5082
 *
5083
 * @param $token
5084
 *   The token to be validated.
5085
 * @param $value
5086
 *   An additional value to base the token on.
5087
 * @param $skip_anonymous
5088
 *   Set to true to skip token validation for anonymous users.
5089
 *
5090
 * @return
5091
 *   True for a valid token, false for an invalid token. When $skip_anonymous
5092
 *   is true, the return value will always be true for anonymous users.
5093
 */
5094
function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
5095
  global $user;
5096
  return (($skip_anonymous && $user->uid == 0) || ($token === drupal_get_token($value)));
5097
}
5098

    
5099
function _drupal_bootstrap_full() {
5100
  static $called = FALSE;
5101

    
5102
  if ($called) {
5103
    return;
5104
  }
5105
  $called = TRUE;
5106
  require_once DRUPAL_ROOT . '/' . variable_get('path_inc', 'includes/path.inc');
5107
  require_once DRUPAL_ROOT . '/includes/theme.inc';
5108
  require_once DRUPAL_ROOT . '/includes/pager.inc';
5109
  require_once DRUPAL_ROOT . '/' . variable_get('menu_inc', 'includes/menu.inc');
5110
  require_once DRUPAL_ROOT . '/includes/tablesort.inc';
5111
  require_once DRUPAL_ROOT . '/includes/file.inc';
5112
  require_once DRUPAL_ROOT . '/includes/unicode.inc';
5113
  require_once DRUPAL_ROOT . '/includes/image.inc';
5114
  require_once DRUPAL_ROOT . '/includes/form.inc';
5115
  require_once DRUPAL_ROOT . '/includes/mail.inc';
5116
  require_once DRUPAL_ROOT . '/includes/actions.inc';
5117
  require_once DRUPAL_ROOT . '/includes/ajax.inc';
5118
  require_once DRUPAL_ROOT . '/includes/token.inc';
5119
  require_once DRUPAL_ROOT . '/includes/errors.inc';
5120

    
5121
  // Detect string handling method
5122
  unicode_check();
5123
  // Undo magic quotes
5124
  fix_gpc_magic();
5125
  // Load all enabled modules
5126
  module_load_all();
5127
  // Make sure all stream wrappers are registered.
5128
  file_get_stream_wrappers();
5129
  // Ensure mt_rand is reseeded, to prevent random values from one page load
5130
  // being exploited to predict random values in subsequent page loads.
5131
  $seed = unpack("L", drupal_random_bytes(4));
5132
  mt_srand($seed[1]);
5133

    
5134
  $test_info = &$GLOBALS['drupal_test_info'];
5135
  if (!empty($test_info['in_child_site'])) {
5136
    // Running inside the simpletest child site, log fatal errors to test
5137
    // specific file directory.
5138
    ini_set('log_errors', 1);
5139
    ini_set('error_log', 'public://error.log');
5140
  }
5141

    
5142
  // Initialize $_GET['q'] prior to invoking hook_init().
5143
  drupal_path_initialize();
5144

    
5145
  // Let all modules take action before the menu system handles the request.
5146
  // We do not want this while running update.php.
5147
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
5148
    // Prior to invoking hook_init(), initialize the theme (potentially a custom
5149
    // one for this page), so that:
5150
    // - Modules with hook_init() implementations that call theme() or
5151
    //   theme_get_registry() don't initialize the incorrect theme.
5152
    // - The theme can have hook_*_alter() implementations affect page building
5153
    //   (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
5154
    //   ahead of when rendering starts.
5155
    menu_set_custom_theme();
5156
    drupal_theme_initialize();
5157
    module_invoke_all('init');
5158
  }
5159
}
5160

    
5161
/**
5162
 * Stores the current page in the cache.
5163
 *
5164
 * If page_compression is enabled, a gzipped version of the page is stored in
5165
 * the cache to avoid compressing the output on each request. The cache entry
5166
 * is unzipped in the relatively rare event that the page is requested by a
5167
 * client without gzip support.
5168
 *
5169
 * Page compression requires the PHP zlib extension
5170
 * (http://php.net/manual/ref.zlib.php).
5171
 *
5172
 * @see drupal_page_header()
5173
 */
5174
function drupal_page_set_cache() {
5175
  global $base_root;
5176

    
5177
  if (drupal_page_is_cacheable()) {
5178

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

    
5182
    $cache = (object) array(
5183
      'cid' => $base_root . request_uri(),
5184
      'data' => array(
5185
        'path' => $_GET['q'],
5186
        'body' => ob_get_clean(),
5187
        'title' => drupal_get_title(),
5188
        'headers' => array(),
5189
        // We need to store whether page was compressed or not,
5190
        // because by the time it is read, the configuration might change.
5191
        'page_compressed' => $page_compressed,
5192
      ),
5193
      'expire' => CACHE_TEMPORARY,
5194
      'created' => REQUEST_TIME,
5195
    );
5196

    
5197
    // Restore preferred header names based on the lower-case names returned
5198
    // by drupal_get_http_header().
5199
    $header_names = _drupal_set_preferred_header_name();
5200
    foreach (drupal_get_http_header() as $name_lower => $value) {
5201
      $cache->data['headers'][$header_names[$name_lower]] = $value;
5202
      if ($name_lower == 'expires') {
5203
        // Use the actual timestamp from an Expires header if available.
5204
        $cache->expire = strtotime($value);
5205
      }
5206
    }
5207

    
5208
    if ($cache->data['body']) {
5209
      if ($page_compressed) {
5210
        $cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
5211
      }
5212
      cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire);
5213
    }
5214
    return $cache;
5215
  }
5216
}
5217

    
5218
/**
5219
 * Executes a cron run when called.
5220
 *
5221
 * Do not call this function from a test. Use $this->cronRun() instead.
5222
 *
5223
 * @return
5224
 *   TRUE if cron ran successfully.
5225
 */
5226
function drupal_cron_run() {
5227
  // Allow execution to continue even if the request gets canceled.
5228
  @ignore_user_abort(TRUE);
5229

    
5230
  // Prevent session information from being saved while cron is running.
5231
  $original_session_saving = drupal_save_session();
5232
  drupal_save_session(FALSE);
5233

    
5234
  // Force the current user to anonymous to ensure consistent permissions on
5235
  // cron runs.
5236
  $original_user = $GLOBALS['user'];
5237
  $GLOBALS['user'] = drupal_anonymous_user();
5238

    
5239
  // Try to allocate enough time to run all the hook_cron implementations.
5240
  drupal_set_time_limit(240);
5241

    
5242
  $return = FALSE;
5243
  // Grab the defined cron queues.
5244
  $queues = module_invoke_all('cron_queue_info');
5245
  drupal_alter('cron_queue_info', $queues);
5246

    
5247
  // Try to acquire cron lock.
5248
  if (!lock_acquire('cron', 240.0)) {
5249
    // Cron is still running normally.
5250
    watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
5251
  }
5252
  else {
5253
    // Make sure every queue exists. There is no harm in trying to recreate an
5254
    // existing queue.
5255
    foreach ($queues as $queue_name => $info) {
5256
      DrupalQueue::get($queue_name)->createQueue();
5257
    }
5258
    // Register shutdown callback.
5259
    drupal_register_shutdown_function('drupal_cron_cleanup');
5260

    
5261
    // Iterate through the modules calling their cron handlers (if any):
5262
    foreach (module_implements('cron') as $module) {
5263
      // Do not let an exception thrown by one module disturb another.
5264
      try {
5265
        module_invoke($module, 'cron');
5266
      }
5267
      catch (Exception $e) {
5268
        watchdog_exception('cron', $e);
5269
      }
5270
    }
5271

    
5272
    // Record cron time.
5273
    variable_set('cron_last', REQUEST_TIME);
5274
    watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
5275

    
5276
    // Release cron lock.
5277
    lock_release('cron');
5278

    
5279
    // Return TRUE so other functions can check if it did run successfully
5280
    $return = TRUE;
5281
  }
5282

    
5283
  foreach ($queues as $queue_name => $info) {
5284
    if (!empty($info['skip on cron'])) {
5285
      // Do not run if queue wants to skip.
5286
      continue;
5287
    }
5288
    $function = $info['worker callback'];
5289
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
5290
    $queue = DrupalQueue::get($queue_name);
5291
    while (time() < $end && ($item = $queue->claimItem())) {
5292
      try {
5293
        $function($item->data);
5294
        $queue->deleteItem($item);
5295
      }
5296
      catch (Exception $e) {
5297
        // In case of exception log it and leave the item in the queue
5298
        // to be processed again later.
5299
        watchdog_exception('cron', $e);
5300
      }
5301
    }
5302
  }
5303
  // Restore the user.
5304
  $GLOBALS['user'] = $original_user;
5305
  drupal_save_session($original_session_saving);
5306

    
5307
  return $return;
5308
}
5309

    
5310
/**
5311
 * Shutdown function: Performs cron cleanup.
5312
 *
5313
 * @see drupal_cron_run()
5314
 * @see drupal_register_shutdown_function()
5315
 */
5316
function drupal_cron_cleanup() {
5317
  // See if the semaphore is still locked.
5318
  if (variable_get('cron_semaphore', FALSE)) {
5319
    watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);
5320

    
5321
    // Release cron semaphore.
5322
    variable_del('cron_semaphore');
5323
  }
5324
}
5325

    
5326
/**
5327
 * Returns information about system object files (modules, themes, etc.).
5328
 *
5329
 * This function is used to find all or some system object files (module files,
5330
 * theme files, etc.) that exist on the site. It searches in several locations,
5331
 * depending on what type of object you are looking for. For instance, if you
5332
 * are looking for modules and call:
5333
 * @code
5334
 * drupal_system_listing("/\.module$/", "modules", 'name', 0);
5335
 * @endcode
5336
 * this function will search the site-wide modules directory (i.e., /modules/),
5337
 * your installation profile's directory (i.e.,
5338
 * /profiles/your_site_profile/modules/), the all-sites directory (i.e.,
5339
 * /sites/all/modules/), and your site-specific directory (i.e.,
5340
 * /sites/your_site_dir/modules/), in that order, and return information about
5341
 * all of the files ending in .module in those directories.
5342
 *
5343
 * The information is returned in an associative array, which can be keyed on
5344
 * the file name ($key = 'filename'), the file name without the extension ($key
5345
 * = 'name'), or the full file stream URI ($key = 'uri'). If you use a key of
5346
 * 'filename' or 'name', files found later in the search will take precedence
5347
 * over files found earlier (unless they belong to a module or theme not
5348
 * compatible with Drupal core); if you choose a key of 'uri', you will get all
5349
 * files found.
5350
 *
5351
 * @param string $mask
5352
 *   The preg_match() regular expression for the files to find.
5353
 * @param string $directory
5354
 *   The subdirectory name in which the files are found. For example,
5355
 *   'modules' will search in sub-directories of the top-level /modules
5356
 *   directory, sub-directories of /sites/all/modules/, etc.
5357
 * @param string $key
5358
 *   The key to be used for the associative array returned. Possible values are
5359
 *   'uri', for the file's URI; 'filename', for the basename of the file; and
5360
 *   'name' for the name of the file without the extension. If you choose 'name'
5361
 *   or 'filename', only the highest-precedence file will be returned.
5362
 * @param int $min_depth
5363
 *   Minimum depth of directories to return files from, relative to each
5364
 *   directory searched. For instance, a minimum depth of 2 would find modules
5365
 *   inside /modules/node/tests, but not modules directly in /modules/node.
5366
 *
5367
 * @return array
5368
 *   An associative array of file objects, keyed on the chosen key. Each element
5369
 *   in the array is an object containing file information, with properties:
5370
 *   - 'uri': Full URI of the file.
5371
 *   - 'filename': File name.
5372
 *   - 'name': Name of file without the extension.
5373
 */
5374
function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
5375
  $config = conf_path();
5376

    
5377
  $searchdir = array($directory);
5378
  $files = array();
5379

    
5380
  // The 'profiles' directory contains pristine collections of modules and
5381
  // themes as organized by a distribution. It is pristine in the same way
5382
  // that /modules is pristine for core; users should avoid changing anything
5383
  // there in favor of sites/all or sites/<domain> directories.
5384
  $profiles = array();
5385
  $profile = drupal_get_profile();
5386
  // For SimpleTest to be able to test modules packaged together with a
5387
  // distribution we need to include the profile of the parent site (in which
5388
  // test runs are triggered).
5389
  if (drupal_valid_test_ua()) {
5390
    $testing_profile = variable_get('simpletest_parent_profile', FALSE);
5391
    if ($testing_profile && $testing_profile != $profile) {
5392
      $profiles[] = $testing_profile;
5393
    }
5394
  }
5395
  // In case both profile directories contain the same extension, the actual
5396
  // profile always has precedence.
5397
  $profiles[] = $profile;
5398
  foreach ($profiles as $profile) {
5399
    if (file_exists("profiles/$profile/$directory")) {
5400
      $searchdir[] = "profiles/$profile/$directory";
5401
    }
5402
  }
5403

    
5404
  // Always search sites/all/* as well as the global directories.
5405
  $searchdir[] = 'sites/all/' . $directory;
5406

    
5407
  if (file_exists("$config/$directory")) {
5408
    $searchdir[] = "$config/$directory";
5409
  }
5410

    
5411
  // Get current list of items.
5412
  if (!function_exists('file_scan_directory')) {
5413
    require_once DRUPAL_ROOT . '/includes/file.inc';
5414
  }
5415
  foreach ($searchdir as $dir) {
5416
    $files_to_add = file_scan_directory($dir, $mask, array('key' => $key, 'min_depth' => $min_depth));
5417

    
5418
    // Duplicate files found in later search directories take precedence over
5419
    // earlier ones, so we want them to overwrite keys in our resulting
5420
    // $files array.
5421
    // The exception to this is if the later file is from a module or theme not
5422
    // compatible with Drupal core. This may occur during upgrades of Drupal
5423
    // core when new modules exist in core while older contrib modules with the
5424
    // same name exist in a directory such as sites/all/modules/.
5425
    foreach (array_intersect_key($files_to_add, $files) as $file_key => $file) {
5426
      // If it has no info file, then we just behave liberally and accept the
5427
      // new resource on the list for merging.
5428
      if (file_exists($info_file = dirname($file->uri) . '/' . $file->name . '.info')) {
5429
        // Get the .info file for the module or theme this file belongs to.
5430
        $info = drupal_parse_info_file($info_file);
5431

    
5432
        // If the module or theme is incompatible with Drupal core, remove it
5433
        // from the array for the current search directory, so it is not
5434
        // overwritten when merged with the $files array.
5435
        if (isset($info['core']) && $info['core'] != DRUPAL_CORE_COMPATIBILITY) {
5436
          unset($files_to_add[$file_key]);
5437
        }
5438
      }
5439
    }
5440
    $files = array_merge($files, $files_to_add);
5441
  }
5442

    
5443
  return $files;
5444
}
5445

    
5446
/**
5447
 * Sets the main page content value for later use.
5448
 *
5449
 * Given the nature of the Drupal page handling, this will be called once with
5450
 * a string or array. We store that and return it later as the block is being
5451
 * displayed.
5452
 *
5453
 * @param $content
5454
 *   A string or renderable array representing the body of the page.
5455
 *
5456
 * @return
5457
 *   If called without $content, a renderable array representing the body of
5458
 *   the page.
5459
 */
5460
function drupal_set_page_content($content = NULL) {
5461
  $content_block = &drupal_static(__FUNCTION__, NULL);
5462
  $main_content_display = &drupal_static('system_main_content_added', FALSE);
5463

    
5464
  if (!empty($content)) {
5465
    $content_block = (is_array($content) ? $content : array('main' => array('#markup' => $content)));
5466
  }
5467
  else {
5468
    // Indicate that the main content has been requested. We assume that
5469
    // the module requesting the content will be adding it to the page.
5470
    // A module can indicate that it does not handle the content by setting
5471
    // the static variable back to FALSE after calling this function.
5472
    $main_content_display = TRUE;
5473
    return $content_block;
5474
  }
5475
}
5476

    
5477
/**
5478
 * #pre_render callback to render #browsers into #prefix and #suffix.
5479
 *
5480
 * @param $elements
5481
 *   A render array with a '#browsers' property. The '#browsers' property can
5482
 *   contain any or all of the following keys:
5483
 *   - 'IE': If FALSE, the element is not rendered by Internet Explorer. If
5484
 *     TRUE, the element is rendered by Internet Explorer. Can also be a string
5485
 *     containing an expression for Internet Explorer to evaluate as part of a
5486
 *     conditional comment. For example, this can be set to 'lt IE 7' for the
5487
 *     element to be rendered in Internet Explorer 6, but not in Internet
5488
 *     Explorer 7 or higher. Defaults to TRUE.
5489
 *   - '!IE': If FALSE, the element is not rendered by browsers other than
5490
 *     Internet Explorer. If TRUE, the element is rendered by those browsers.
5491
 *     Defaults to TRUE.
5492
 *   Examples:
5493
 *   - To render an element in all browsers, '#browsers' can be left out or set
5494
 *     to array('IE' => TRUE, '!IE' => TRUE).
5495
 *   - To render an element in Internet Explorer only, '#browsers' can be set
5496
 *     to array('!IE' => FALSE).
5497
 *   - To render an element in Internet Explorer 6 only, '#browsers' can be set
5498
 *     to array('IE' => 'lt IE 7', '!IE' => FALSE).
5499
 *   - To render an element in Internet Explorer 8 and higher and in all other
5500
 *     browsers, '#browsers' can be set to array('IE' => 'gte IE 8').
5501
 *
5502
 * @return
5503
 *   The passed-in element with markup for conditional comments potentially
5504
 *   added to '#prefix' and '#suffix'.
5505
 */
5506
function drupal_pre_render_conditional_comments($elements) {
5507
  $browsers = isset($elements['#browsers']) ? $elements['#browsers'] : array();
5508
  $browsers += array(
5509
    'IE' => TRUE,
5510
    '!IE' => TRUE,
5511
  );
5512

    
5513
  // If rendering in all browsers, no need for conditional comments.
5514
  if ($browsers['IE'] === TRUE && $browsers['!IE']) {
5515
    return $elements;
5516
  }
5517

    
5518
  // Determine the conditional comment expression for Internet Explorer to
5519
  // evaluate.
5520
  if ($browsers['IE'] === TRUE) {
5521
    $expression = 'IE';
5522
  }
5523
  elseif ($browsers['IE'] === FALSE) {
5524
    $expression = '!IE';
5525
  }
5526
  else {
5527
    $expression = $browsers['IE'];
5528
  }
5529

    
5530
  // Wrap the element's potentially existing #prefix and #suffix properties with
5531
  // conditional comment markup. The conditional comment expression is evaluated
5532
  // by Internet Explorer only. To control the rendering by other browsers,
5533
  // either the "downlevel-hidden" or "downlevel-revealed" technique must be
5534
  // used. See http://en.wikipedia.org/wiki/Conditional_comment for details.
5535
  $elements += array(
5536
    '#prefix' => '',
5537
    '#suffix' => '',
5538
  );
5539
  if (!$browsers['!IE']) {
5540
    // "downlevel-hidden".
5541
    $elements['#prefix'] = "\n<!--[if $expression]>\n" . $elements['#prefix'];
5542
    $elements['#suffix'] .= "<![endif]-->\n";
5543
  }
5544
  else {
5545
    // "downlevel-revealed".
5546
    $elements['#prefix'] = "\n<!--[if $expression]><!-->\n" . $elements['#prefix'];
5547
    $elements['#suffix'] .= "<!--<![endif]-->\n";
5548
  }
5549

    
5550
  return $elements;
5551
}
5552

    
5553
/**
5554
 * #pre_render callback to render a link into #markup.
5555
 *
5556
 * Doing so during pre_render gives modules a chance to alter the link parts.
5557
 *
5558
 * @param $elements
5559
 *   A structured array whose keys form the arguments to l():
5560
 *   - #title: The link text to pass as argument to l().
5561
 *   - #href: The URL path component to pass as argument to l().
5562
 *   - #options: (optional) An array of options to pass to l().
5563
 *
5564
 * @return
5565
 *   The passed-in elements containing a rendered link in '#markup'.
5566
 */
5567
function drupal_pre_render_link($element) {
5568
  // By default, link options to pass to l() are normally set in #options.
5569
  $element += array('#options' => array());
5570
  // However, within the scope of renderable elements, #attributes is a valid
5571
  // way to specify attributes, too. Take them into account, but do not override
5572
  // attributes from #options.
5573
  if (isset($element['#attributes'])) {
5574
    $element['#options'] += array('attributes' => array());
5575
    $element['#options']['attributes'] += $element['#attributes'];
5576
  }
5577

    
5578
  // This #pre_render callback can be invoked from inside or outside of a Form
5579
  // API context, and depending on that, a HTML ID may be already set in
5580
  // different locations. #options should have precedence over Form API's #id.
5581
  // #attributes have been taken over into #options above already.
5582
  if (isset($element['#options']['attributes']['id'])) {
5583
    $element['#id'] = $element['#options']['attributes']['id'];
5584
  }
5585
  elseif (isset($element['#id'])) {
5586
    $element['#options']['attributes']['id'] = $element['#id'];
5587
  }
5588

    
5589
  // Conditionally invoke ajax_pre_render_element(), if #ajax is set.
5590
  if (isset($element['#ajax']) && !isset($element['#ajax_processed'])) {
5591
    // If no HTML ID was found above, automatically create one.
5592
    if (!isset($element['#id'])) {
5593
      $element['#id'] = $element['#options']['attributes']['id'] = drupal_html_id('ajax-link');
5594
    }
5595
    // If #ajax['path] was not specified, use the href as Ajax request URL.
5596
    if (!isset($element['#ajax']['path'])) {
5597
      $element['#ajax']['path'] = $element['#href'];
5598
      $element['#ajax']['options'] = $element['#options'];
5599
    }
5600
    $element = ajax_pre_render_element($element);
5601
  }
5602

    
5603
  $element['#markup'] = l($element['#title'], $element['#href'], $element['#options']);
5604
  return $element;
5605
}
5606

    
5607
/**
5608
 * #pre_render callback that collects child links into a single array.
5609
 *
5610
 * This function can be added as a pre_render callback for a renderable array,
5611
 * usually one which will be themed by theme_links(). It iterates through all
5612
 * unrendered children of the element, collects any #links properties it finds,
5613
 * merges them into the parent element's #links array, and prevents those
5614
 * children from being rendered separately.
5615
 *
5616
 * The purpose of this is to allow links to be logically grouped into related
5617
 * categories, so that each child group can be rendered as its own list of
5618
 * links if drupal_render() is called on it, but calling drupal_render() on the
5619
 * parent element will still produce a single list containing all the remaining
5620
 * links, regardless of what group they were in.
5621
 *
5622
 * A typical example comes from node links, which are stored in a renderable
5623
 * array similar to this:
5624
 * @code
5625
 * $node->content['links'] = array(
5626
 *   '#theme' => 'links__node',
5627
 *   '#pre_render' => array('drupal_pre_render_links'),
5628
 *   'comment' => array(
5629
 *     '#theme' => 'links__node__comment',
5630
 *     '#links' => array(
5631
 *       // An array of links associated with node comments, suitable for
5632
 *       // passing in to theme_links().
5633
 *     ),
5634
 *   ),
5635
 *   'statistics' => array(
5636
 *     '#theme' => 'links__node__statistics',
5637
 *     '#links' => array(
5638
 *       // An array of links associated with node statistics, suitable for
5639
 *       // passing in to theme_links().
5640
 *     ),
5641
 *   ),
5642
 *   'translation' => array(
5643
 *     '#theme' => 'links__node__translation',
5644
 *     '#links' => array(
5645
 *       // An array of links associated with node translation, suitable for
5646
 *       // passing in to theme_links().
5647
 *     ),
5648
 *   ),
5649
 * );
5650
 * @endcode
5651
 *
5652
 * In this example, the links are grouped by functionality, which can be
5653
 * helpful to themers who want to display certain kinds of links independently.
5654
 * For example, adding this code to node.tpl.php will result in the comment
5655
 * links being rendered as a single list:
5656
 * @code
5657
 * print render($content['links']['comment']);
5658
 * @endcode
5659
 *
5660
 * (where $node->content has been transformed into $content before handing
5661
 * control to the node.tpl.php template).
5662
 *
5663
 * The pre_render function defined here allows the above flexibility, but also
5664
 * allows the following code to be used to render all remaining links into a
5665
 * single list, regardless of their group:
5666
 * @code
5667
 * print render($content['links']);
5668
 * @endcode
5669
 *
5670
 * In the above example, this will result in the statistics and translation
5671
 * links being rendered together in a single list (but not the comment links,
5672
 * which were rendered previously on their own).
5673
 *
5674
 * Because of the way this function works, the individual properties of each
5675
 * group (for example, a group-specific #theme property such as
5676
 * 'links__node__comment' in the example above, or any other property such as
5677
 * #attributes or #pre_render that is attached to it) are only used when that
5678
 * group is rendered on its own. When the group is rendered together with other
5679
 * children, these child-specific properties are ignored, and only the overall
5680
 * properties of the parent are used.
5681
 */
5682
function drupal_pre_render_links($element) {
5683
  $element += array('#links' => array());
5684
  foreach (element_children($element) as $key) {
5685
    $child = &$element[$key];
5686
    // If the child has links which have not been printed yet and the user has
5687
    // access to it, merge its links in to the parent.
5688
    if (isset($child['#links']) && empty($child['#printed']) && (!isset($child['#access']) || $child['#access'])) {
5689
      $element['#links'] += $child['#links'];
5690
      // Mark the child as having been printed already (so that its links
5691
      // cannot be mistakenly rendered twice).
5692
      $child['#printed'] = TRUE;
5693
    }
5694
  }
5695
  return $element;
5696
}
5697

    
5698
/**
5699
 * #pre_render callback to append contents in #markup to #children.
5700
 *
5701
 * This needs to be a #pre_render callback, because eventually assigned
5702
 * #theme_wrappers will expect the element's rendered content in #children.
5703
 * Note that if also a #theme is defined for the element, then the result of
5704
 * the theme callback will override #children.
5705
 *
5706
 * @param $elements
5707
 *   A structured array using the #markup key.
5708
 *
5709
 * @return
5710
 *   The passed-in elements, but #markup appended to #children.
5711
 *
5712
 * @see drupal_render()
5713
 */
5714
function drupal_pre_render_markup($elements) {
5715
  $elements['#children'] = $elements['#markup'];
5716
  return $elements;
5717
}
5718

    
5719
/**
5720
 * Renders the page, including all theming.
5721
 *
5722
 * @param $page
5723
 *   A string or array representing the content of a page. The array consists of
5724
 *   the following keys:
5725
 *   - #type: Value is always 'page'. This pushes the theming through
5726
 *     page.tpl.php (required).
5727
 *   - #show_messages: Suppress drupal_get_message() items. Used by Batch
5728
 *     API (optional).
5729
 *
5730
 * @see hook_page_alter()
5731
 * @see element_info()
5732
 */
5733
function drupal_render_page($page) {
5734
  $main_content_display = &drupal_static('system_main_content_added', FALSE);
5735

    
5736
  // Allow menu callbacks to return strings or arbitrary arrays to render.
5737
  // If the array returned is not of #type page directly, we need to fill
5738
  // in the page with defaults.
5739
  if (is_string($page) || (is_array($page) && (!isset($page['#type']) || ($page['#type'] != 'page')))) {
5740
    drupal_set_page_content($page);
5741
    $page = element_info('page');
5742
  }
5743

    
5744
  // Modules can add elements to $page as needed in hook_page_build().
5745
  foreach (module_implements('page_build') as $module) {
5746
    $function = $module . '_page_build';
5747
    $function($page);
5748
  }
5749
  // Modules alter the $page as needed. Blocks are populated into regions like
5750
  // 'sidebar_first', 'footer', etc.
5751
  drupal_alter('page', $page);
5752

    
5753
  // If no module has taken care of the main content, add it to the page now.
5754
  // This allows the site to still be usable even if no modules that
5755
  // control page regions (for example, the Block module) are enabled.
5756
  if (!$main_content_display) {
5757
    $page['content']['system_main'] = drupal_set_page_content();
5758
  }
5759

    
5760
  return drupal_render($page);
5761
}
5762

    
5763
/**
5764
 * Renders HTML given a structured array tree.
5765
 *
5766
 * Recursively iterates over each of the array elements, generating HTML code.
5767
 *
5768
 * Renderable arrays have two kinds of key/value pairs: properties and
5769
 * children. Properties have keys starting with '#' and their values influence
5770
 * how the array will be rendered. Children are all elements whose keys do not
5771
 * start with a '#'. Their values should be renderable arrays themselves,
5772
 * which will be rendered during the rendering of the parent array. The markup
5773
 * provided by the children is typically inserted into the markup generated by
5774
 * the parent array.
5775
 *
5776
 * HTML generation for a renderable array, and the treatment of any children,
5777
 * is controlled by two properties containing theme functions, #theme and
5778
 * #theme_wrappers.
5779
 *
5780
 * #theme is the theme function called first. If it is set and the element has
5781
 * any children, it is the responsibility of the theme function to render
5782
 * these children. For elements that are not allowed to have any children,
5783
 * e.g. buttons or textfields, the theme function can be used to render the
5784
 * element itself. If #theme is not present and the element has children, each
5785
 * child is itself rendered by a call to drupal_render(), and the results are
5786
 * concatenated.
5787
 *
5788
 * The #theme_wrappers property contains an array of theme functions which will
5789
 * be called, in order, after #theme has run. These can be used to add further
5790
 * markup around the rendered children; e.g., fieldsets add the required markup
5791
 * for a fieldset around their rendered child elements. All wrapper theme
5792
 * functions have to include the element's #children property in their output,
5793
 * as it contains the output of the previous theme functions and the rendered
5794
 * children.
5795
 *
5796
 * For example, for the form element type, by default only the #theme_wrappers
5797
 * property is set, which adds the form markup around the rendered child
5798
 * elements of the form. This allows you to set the #theme property on a
5799
 * specific form to a custom theme function, giving you complete control over
5800
 * the placement of the form's children while not at all having to deal with
5801
 * the form markup itself.
5802
 *
5803
 * drupal_render() can optionally cache the rendered output of elements to
5804
 * improve performance. To use drupal_render() caching, set the element's #cache
5805
 * property to an associative array with one or several of the following keys:
5806
 * - 'keys': An array of one or more keys that identify the element. If 'keys'
5807
 *   is set, the cache ID is created automatically from these keys. See
5808
 *   drupal_render_cid_create().
5809
 * - 'granularity' (optional): Define the cache granularity using binary
5810
 *   combinations of the cache granularity constants, e.g.
5811
 *   DRUPAL_CACHE_PER_USER to cache for each user separately or
5812
 *   DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE to cache separately for each
5813
 *   page and role. If not specified the element is cached globally for each
5814
 *   theme and language.
5815
 * - 'cid': Specify the cache ID directly. Either 'keys' or 'cid' is required.
5816
 *   If 'cid' is set, 'keys' and 'granularity' are ignored. Use only if you
5817
 *   have special requirements.
5818
 * - 'expire': Set to one of the cache lifetime constants.
5819
 * - 'bin': Specify a cache bin to cache the element in. Defaults to 'cache'.
5820
 *
5821
 * This function is usually called from within another function, like
5822
 * drupal_get_form() or a theme function. Elements are sorted internally
5823
 * using uasort(). Since this is expensive, when passing already sorted
5824
 * elements to drupal_render(), for example from a database query, set
5825
 * $elements['#sorted'] = TRUE to avoid sorting them a second time.
5826
 *
5827
 * drupal_render() flags each element with a '#printed' status to indicate that
5828
 * the element has been rendered, which allows individual elements of a given
5829
 * array to be rendered independently and prevents them from being rendered
5830
 * more than once on subsequent calls to drupal_render() (e.g., as part of a
5831
 * larger array). If the same array or array element is passed more than once
5832
 * to drupal_render(), it simply returns an empty string.
5833
 *
5834
 * @param array $elements
5835
 *   The structured array describing the data to be rendered.
5836
 *
5837
 * @return string
5838
 *   The rendered HTML.
5839
 */
5840
function drupal_render(&$elements) {
5841
  // Early-return nothing if user does not have access.
5842
  if (empty($elements) || (isset($elements['#access']) && !$elements['#access'])) {
5843
    return '';
5844
  }
5845

    
5846
  // Do not print elements twice.
5847
  if (!empty($elements['#printed'])) {
5848
    return '';
5849
  }
5850

    
5851
  // Try to fetch the element's markup from cache and return.
5852
  if (isset($elements['#cache'])) {
5853
    $cached_output = drupal_render_cache_get($elements);
5854
    if ($cached_output !== FALSE) {
5855
      return $cached_output;
5856
    }
5857
  }
5858

    
5859
  // If #markup is set, ensure #type is set. This allows to specify just #markup
5860
  // on an element without setting #type.
5861
  if (isset($elements['#markup']) && !isset($elements['#type'])) {
5862
    $elements['#type'] = 'markup';
5863
  }
5864

    
5865
  // If the default values for this element have not been loaded yet, populate
5866
  // them.
5867
  if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
5868
    $elements += element_info($elements['#type']);
5869
  }
5870

    
5871
  // Make any final changes to the element before it is rendered. This means
5872
  // that the $element or the children can be altered or corrected before the
5873
  // element is rendered into the final text.
5874
  if (isset($elements['#pre_render'])) {
5875
    foreach ($elements['#pre_render'] as $function) {
5876
      if (function_exists($function)) {
5877
        $elements = $function($elements);
5878
      }
5879
    }
5880
  }
5881

    
5882
  // Allow #pre_render to abort rendering.
5883
  if (!empty($elements['#printed'])) {
5884
    return '';
5885
  }
5886

    
5887
  // Get the children of the element, sorted by weight.
5888
  $children = element_children($elements, TRUE);
5889

    
5890
  // Initialize this element's #children, unless a #pre_render callback already
5891
  // preset #children.
5892
  if (!isset($elements['#children'])) {
5893
    $elements['#children'] = '';
5894
  }
5895
  // Call the element's #theme function if it is set. Then any children of the
5896
  // element have to be rendered there.
5897
  if (isset($elements['#theme'])) {
5898
    $elements['#children'] = theme($elements['#theme'], $elements);
5899
  }
5900
  // If #theme was not set and the element has children, render them now.
5901
  // This is the same process as drupal_render_children() but is inlined
5902
  // for speed.
5903
  if ($elements['#children'] == '') {
5904
    foreach ($children as $key) {
5905
      $elements['#children'] .= drupal_render($elements[$key]);
5906
    }
5907
  }
5908

    
5909
  // Let the theme functions in #theme_wrappers add markup around the rendered
5910
  // children.
5911
  if (isset($elements['#theme_wrappers'])) {
5912
    foreach ($elements['#theme_wrappers'] as $theme_wrapper) {
5913
      $elements['#children'] = theme($theme_wrapper, $elements);
5914
    }
5915
  }
5916

    
5917
  // Filter the outputted content and make any last changes before the
5918
  // content is sent to the browser. The changes are made on $content
5919
  // which allows the output'ed text to be filtered.
5920
  if (isset($elements['#post_render'])) {
5921
    foreach ($elements['#post_render'] as $function) {
5922
      if (function_exists($function)) {
5923
        $elements['#children'] = $function($elements['#children'], $elements);
5924
      }
5925
    }
5926
  }
5927

    
5928
  // Add any JavaScript state information associated with the element.
5929
  if (!empty($elements['#states'])) {
5930
    drupal_process_states($elements);
5931
  }
5932

    
5933
  // Add additional libraries, CSS, JavaScript an other custom
5934
  // attached data associated with this element.
5935
  if (!empty($elements['#attached'])) {
5936
    drupal_process_attached($elements);
5937
  }
5938

    
5939
  $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
5940
  $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
5941
  $output = $prefix . $elements['#children'] . $suffix;
5942

    
5943
  // Cache the processed element if #cache is set.
5944
  if (isset($elements['#cache'])) {
5945
    drupal_render_cache_set($output, $elements);
5946
  }
5947

    
5948
  $elements['#printed'] = TRUE;
5949
  return $output;
5950
}
5951

    
5952
/**
5953
 * Renders children of an element and concatenates them.
5954
 *
5955
 * @param array $element
5956
 *   The structured array whose children shall be rendered.
5957
 * @param array $children_keys
5958
 *   (optional) If the keys of the element's children are already known, they
5959
 *   can be passed in to save another run of element_children().
5960
 *
5961
 * @return string
5962
 *   The rendered HTML of all children of the element.
5963

    
5964
 * @see drupal_render()
5965
 */
5966
function drupal_render_children(&$element, $children_keys = NULL) {
5967
  if ($children_keys === NULL) {
5968
    $children_keys = element_children($element);
5969
  }
5970
  $output = '';
5971
  foreach ($children_keys as $key) {
5972
    if (!empty($element[$key])) {
5973
      $output .= drupal_render($element[$key]);
5974
    }
5975
  }
5976
  return $output;
5977
}
5978

    
5979
/**
5980
 * Renders an element.
5981
 *
5982
 * This function renders an element using drupal_render(). The top level
5983
 * element is shown with show() before rendering, so it will always be rendered
5984
 * even if hide() had been previously used on it.
5985
 *
5986
 * @param $element
5987
 *   The element to be rendered.
5988
 *
5989
 * @return
5990
 *   The rendered element.
5991
 *
5992
 * @see drupal_render()
5993
 * @see show()
5994
 * @see hide()
5995
 */
5996
function render(&$element) {
5997
  if (is_array($element)) {
5998
    show($element);
5999
    return drupal_render($element);
6000
  }
6001
  else {
6002
    // Safe-guard for inappropriate use of render() on flat variables: return
6003
    // the variable as-is.
6004
    return $element;
6005
  }
6006
}
6007

    
6008
/**
6009
 * Hides an element from later rendering.
6010
 *
6011
 * The first time render() or drupal_render() is called on an element tree,
6012
 * as each element in the tree is rendered, it is marked with a #printed flag
6013
 * and the rendered children of the element are cached. Subsequent calls to
6014
 * render() or drupal_render() will not traverse the child tree of this element
6015
 * again: they will just use the cached children. So if you want to hide an
6016
 * element, be sure to call hide() on the element before its parent tree is
6017
 * rendered for the first time, as it will have no effect on subsequent
6018
 * renderings of the parent tree.
6019
 *
6020
 * @param $element
6021
 *   The element to be hidden.
6022
 *
6023
 * @return
6024
 *   The element.
6025
 *
6026
 * @see render()
6027
 * @see show()
6028
 */
6029
function hide(&$element) {
6030
  $element['#printed'] = TRUE;
6031
  return $element;
6032
}
6033

    
6034
/**
6035
 * Shows a hidden element for later rendering.
6036
 *
6037
 * You can also use render($element), which shows the element while rendering
6038
 * it.
6039
 *
6040
 * The first time render() or drupal_render() is called on an element tree,
6041
 * as each element in the tree is rendered, it is marked with a #printed flag
6042
 * and the rendered children of the element are cached. Subsequent calls to
6043
 * render() or drupal_render() will not traverse the child tree of this element
6044
 * again: they will just use the cached children. So if you want to show an
6045
 * element, be sure to call show() on the element before its parent tree is
6046
 * rendered for the first time, as it will have no effect on subsequent
6047
 * renderings of the parent tree.
6048
 *
6049
 * @param $element
6050
 *   The element to be shown.
6051
 *
6052
 * @return
6053
 *   The element.
6054
 *
6055
 * @see render()
6056
 * @see hide()
6057
 */
6058
function show(&$element) {
6059
  $element['#printed'] = FALSE;
6060
  return $element;
6061
}
6062

    
6063
/**
6064
 * Gets the rendered output of a renderable element from the cache.
6065
 *
6066
 * @param $elements
6067
 *   A renderable array.
6068
 *
6069
 * @return
6070
 *   A markup string containing the rendered content of the element, or FALSE
6071
 *   if no cached copy of the element is available.
6072
 *
6073
 * @see drupal_render()
6074
 * @see drupal_render_cache_set()
6075
 */
6076
function drupal_render_cache_get($elements) {
6077
  if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
6078
    return FALSE;
6079
  }
6080
  $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
6081

    
6082
  if (!empty($cid) && $cache = cache_get($cid, $bin)) {
6083
    // Add additional libraries, JavaScript, CSS and other data attached
6084
    // to this element.
6085
    if (isset($cache->data['#attached'])) {
6086
      drupal_process_attached($cache->data);
6087
    }
6088
    // Return the rendered output.
6089
    return $cache->data['#markup'];
6090
  }
6091
  return FALSE;
6092
}
6093

    
6094
/**
6095
 * Caches the rendered output of a renderable element.
6096
 *
6097
 * This is called by drupal_render() if the #cache property is set on an
6098
 * element.
6099
 *
6100
 * @param $markup
6101
 *   The rendered output string of $elements.
6102
 * @param $elements
6103
 *   A renderable array.
6104
 *
6105
 * @see drupal_render_cache_get()
6106
 */
6107
function drupal_render_cache_set(&$markup, $elements) {
6108
  // Create the cache ID for the element.
6109
  if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
6110
    return FALSE;
6111
  }
6112

    
6113
  // Cache implementations are allowed to modify the markup, to support
6114
  // replacing markup with edge-side include commands. The supporting cache
6115
  // backend will store the markup in some other key (like
6116
  // $data['#real-value']) and return an include command instead. When the
6117
  // ESI command is executed by the content accelerator, the real value can
6118
  // be retrieved and used.
6119
  $data['#markup'] = &$markup;
6120
  // Persist attached data associated with this element.
6121
  $attached = drupal_render_collect_attached($elements, TRUE);
6122
  if ($attached) {
6123
    $data['#attached'] = $attached;
6124
  }
6125
  $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
6126
  $expire = isset($elements['#cache']['expire']) ? $elements['#cache']['expire'] : CACHE_PERMANENT;
6127
  cache_set($cid, $data, $bin, $expire);
6128
}
6129

    
6130
/**
6131
 * Collects #attached for an element and its children into a single array.
6132
 *
6133
 * When caching elements, it is necessary to collect all libraries, JavaScript
6134
 * and CSS into a single array, from both the element itself and all child
6135
 * elements. This allows drupal_render() to add these back to the page when the
6136
 * element is returned from cache.
6137
 *
6138
 * @param $elements
6139
 *   The element to collect #attached from.
6140
 * @param $return
6141
 *   Whether to return the attached elements and reset the internal static.
6142
 *
6143
 * @return
6144
 *   The #attached array for this element and its descendants.
6145
 */
6146
function drupal_render_collect_attached($elements, $return = FALSE) {
6147
  $attached = &drupal_static(__FUNCTION__, array());
6148

    
6149
  // Collect all #attached for this element.
6150
  if (isset($elements['#attached'])) {
6151
    foreach ($elements['#attached'] as $key => $value) {
6152
      if (!isset($attached[$key])) {
6153
        $attached[$key] = array();
6154
      }
6155
      $attached[$key] = array_merge($attached[$key], $value);
6156
    }
6157
  }
6158
  if ($children = element_children($elements)) {
6159
    foreach ($children as $child) {
6160
      drupal_render_collect_attached($elements[$child]);
6161
    }
6162
  }
6163

    
6164
  // If this was the first call to the function, return all attached elements
6165
  // and reset the static cache.
6166
  if ($return) {
6167
    $return = $attached;
6168
    $attached = array();
6169
    return $return;
6170
  }
6171
}
6172

    
6173
/**
6174
 * Prepares an element for caching based on a query.
6175
 *
6176
 * This smart caching strategy saves Drupal from querying and rendering to HTML
6177
 * when the underlying query is unchanged.
6178
 *
6179
 * Expensive queries should use the query builder to create the query and then
6180
 * call this function. Executing the query and formatting results should happen
6181
 * in a #pre_render callback.
6182
 *
6183
 * @param $query
6184
 *   A select query object as returned by db_select().
6185
 * @param $function
6186
 *   The name of the function doing this caching. A _pre_render suffix will be
6187
 *   added to this string and is also part of the cache key in
6188
 *   drupal_render_cache_set() and drupal_render_cache_get().
6189
 * @param $expire
6190
 *   The cache expire time, passed eventually to cache_set().
6191
 * @param $granularity
6192
 *   One or more granularity constants passed to drupal_render_cid_parts().
6193
 *
6194
 * @return
6195
 *   A renderable array with the following keys and values:
6196
 *   - #query: The passed-in $query.
6197
 *   - #pre_render: $function with a _pre_render suffix.
6198
 *   - #cache: An associative array prepared for drupal_render_cache_set().
6199
 */
6200
function drupal_render_cache_by_query($query, $function, $expire = CACHE_TEMPORARY, $granularity = NULL) {
6201
  $cache_keys = array_merge(array($function), drupal_render_cid_parts($granularity));
6202
  $query->preExecute();
6203
  $cache_keys[] = hash('sha256', serialize(array((string) $query, $query->getArguments())));
6204
  return array(
6205
    '#query' => $query,
6206
    '#pre_render' => array($function . '_pre_render'),
6207
    '#cache' => array(
6208
      'keys' => $cache_keys,
6209
      'expire' => $expire,
6210
    ),
6211
  );
6212
}
6213

    
6214
/**
6215
 * Returns cache ID parts for building a cache ID.
6216
 *
6217
 * @param $granularity
6218
 *   One or more cache granularity constants. For example, to cache separately
6219
 *   for each user, use DRUPAL_CACHE_PER_USER. To cache separately for each
6220
 *   page and role, use the expression:
6221
 *   @code
6222
 *   DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE
6223
 *   @endcode
6224
 *
6225
 * @return
6226
 *   An array of cache ID parts, always containing the active theme. If the
6227
 *   locale module is enabled it also contains the active language. If
6228
 *   $granularity was passed in, more parts are added.
6229
 */
6230
function drupal_render_cid_parts($granularity = NULL) {
6231
  global $theme, $base_root, $user;
6232

    
6233
  $cid_parts[] = $theme;
6234
  // If Locale is enabled but we have only one language we do not need it as cid
6235
  // part.
6236
  if (drupal_multilingual()) {
6237
    foreach (language_types_configurable() as $language_type) {
6238
      $cid_parts[] = $GLOBALS[$language_type]->language;
6239
    }
6240
  }
6241

    
6242
  if (!empty($granularity)) {
6243
    // 'PER_ROLE' and 'PER_USER' are mutually exclusive. 'PER_USER' can be a
6244
    // resource drag for sites with many users, so when a module is being
6245
    // equivocal, we favor the less expensive 'PER_ROLE' pattern.
6246
    if ($granularity & DRUPAL_CACHE_PER_ROLE) {
6247
      $cid_parts[] = 'r.' . implode(',', array_keys($user->roles));
6248
    }
6249
    elseif ($granularity & DRUPAL_CACHE_PER_USER) {
6250
      $cid_parts[] = "u.$user->uid";
6251
    }
6252

    
6253
    if ($granularity & DRUPAL_CACHE_PER_PAGE) {
6254
      $cid_parts[] = $base_root . request_uri();
6255
    }
6256
  }
6257

    
6258
  return $cid_parts;
6259
}
6260

    
6261
/**
6262
 * Creates the cache ID for a renderable element.
6263
 *
6264
 * This creates the cache ID string, either by returning the #cache['cid']
6265
 * property if present or by building the cache ID out of the #cache['keys']
6266
 * and, optionally, the #cache['granularity'] properties.
6267
 *
6268
 * @param $elements
6269
 *   A renderable array.
6270
 *
6271
 * @return
6272
 *   The cache ID string, or FALSE if the element may not be cached.
6273
 */
6274
function drupal_render_cid_create($elements) {
6275
  if (isset($elements['#cache']['cid'])) {
6276
    return $elements['#cache']['cid'];
6277
  }
6278
  elseif (isset($elements['#cache']['keys'])) {
6279
    $granularity = isset($elements['#cache']['granularity']) ? $elements['#cache']['granularity'] : NULL;
6280
    // Merge in additional cache ID parts based provided by drupal_render_cid_parts().
6281
    $cid_parts = array_merge($elements['#cache']['keys'], drupal_render_cid_parts($granularity));
6282
    return implode(':', $cid_parts);
6283
  }
6284
  return FALSE;
6285
}
6286

    
6287
/**
6288
 * Function used by uasort to sort structured arrays by weight.
6289
 */
6290
function element_sort($a, $b) {
6291
  $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
6292
  $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
6293
  if ($a_weight == $b_weight) {
6294
    return 0;
6295
  }
6296
  return ($a_weight < $b_weight) ? -1 : 1;
6297
}
6298

    
6299
/**
6300
 * Array sorting callback; sorts elements by title.
6301
 */
6302
function element_sort_by_title($a, $b) {
6303
  $a_title = (is_array($a) && isset($a['#title'])) ? $a['#title'] : '';
6304
  $b_title = (is_array($b) && isset($b['#title'])) ? $b['#title'] : '';
6305
  return strnatcasecmp($a_title, $b_title);
6306
}
6307

    
6308
/**
6309
 * Retrieves the default properties for the defined element type.
6310
 *
6311
 * @param $type
6312
 *   An element type as defined by hook_element_info().
6313
 */
6314
function element_info($type) {
6315
  // Use the advanced drupal_static() pattern, since this is called very often.
6316
  static $drupal_static_fast;
6317
  if (!isset($drupal_static_fast)) {
6318
    $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__);
6319
  }
6320
  $cache = &$drupal_static_fast['cache'];
6321

    
6322
  if (!isset($cache)) {
6323
    $cache = module_invoke_all('element_info');
6324
    foreach ($cache as $element_type => $info) {
6325
      $cache[$element_type]['#type'] = $element_type;
6326
    }
6327
    // Allow modules to alter the element type defaults.
6328
    drupal_alter('element_info', $cache);
6329
  }
6330

    
6331
  return isset($cache[$type]) ? $cache[$type] : array();
6332
}
6333

    
6334
/**
6335
 * Retrieves a single property for the defined element type.
6336
 *
6337
 * @param $type
6338
 *   An element type as defined by hook_element_info().
6339
 * @param $property_name
6340
 *   The property within the element type that should be returned.
6341
 * @param $default
6342
 *   (Optional) The value to return if the element type does not specify a
6343
 *   value for the property. Defaults to NULL.
6344
 */
6345
function element_info_property($type, $property_name, $default = NULL) {
6346
  return (($info = element_info($type)) && array_key_exists($property_name, $info)) ? $info[$property_name] : $default;
6347
}
6348

    
6349
/**
6350
 * Sorts a structured array by the 'weight' element.
6351
 *
6352
 * Note that the sorting is by the 'weight' array element, not by the render
6353
 * element property '#weight'.
6354
 *
6355
 * Callback for uasort() used in various functions.
6356
 *
6357
 * @param $a
6358
 *   First item for comparison. The compared items should be associative arrays
6359
 *   that optionally include a 'weight' element. For items without a 'weight'
6360
 *   element, a default value of 0 will be used.
6361
 * @param $b
6362
 *   Second item for comparison.
6363
 */
6364
function drupal_sort_weight($a, $b) {
6365
  $a_weight = (is_array($a) && isset($a['weight'])) ? $a['weight'] : 0;
6366
  $b_weight = (is_array($b) && isset($b['weight'])) ? $b['weight'] : 0;
6367
  if ($a_weight == $b_weight) {
6368
    return 0;
6369
  }
6370
  return ($a_weight < $b_weight) ? -1 : 1;
6371
}
6372

    
6373
/**
6374
 * Array sorting callback; sorts elements by 'title' key.
6375
 */
6376
function drupal_sort_title($a, $b) {
6377
  if (!isset($b['title'])) {
6378
    return -1;
6379
  }
6380
  if (!isset($a['title'])) {
6381
    return 1;
6382
  }
6383
  return strcasecmp($a['title'], $b['title']);
6384
}
6385

    
6386
/**
6387
 * Checks if the key is a property.
6388
 */
6389
function element_property($key) {
6390
  return $key[0] == '#';
6391
}
6392

    
6393
/**
6394
 * Gets properties of a structured array element (keys beginning with '#').
6395
 */
6396
function element_properties($element) {
6397
  return array_filter(array_keys((array) $element), 'element_property');
6398
}
6399

    
6400
/**
6401
 * Checks if the key is a child.
6402
 */
6403
function element_child($key) {
6404
  return !isset($key[0]) || $key[0] != '#';
6405
}
6406

    
6407
/**
6408
 * Identifies the children of an element array, optionally sorted by weight.
6409
 *
6410
 * The children of a element array are those key/value pairs whose key does
6411
 * not start with a '#'. See drupal_render() for details.
6412
 *
6413
 * @param $elements
6414
 *   The element array whose children are to be identified.
6415
 * @param $sort
6416
 *   Boolean to indicate whether the children should be sorted by weight.
6417
 *
6418
 * @return
6419
 *   The array keys of the element's children.
6420
 */
6421
function element_children(&$elements, $sort = FALSE) {
6422
  // Do not attempt to sort elements which have already been sorted.
6423
  $sort = isset($elements['#sorted']) ? !$elements['#sorted'] : $sort;
6424

    
6425
  // Filter out properties from the element, leaving only children.
6426
  $children = array();
6427
  $sortable = FALSE;
6428
  foreach ($elements as $key => $value) {
6429
    if ($key === '' || $key[0] !== '#') {
6430
      $children[$key] = $value;
6431
      if (is_array($value) && isset($value['#weight'])) {
6432
        $sortable = TRUE;
6433
      }
6434
    }
6435
  }
6436
  // Sort the children if necessary.
6437
  if ($sort && $sortable) {
6438
    uasort($children, 'element_sort');
6439
    // Put the sorted children back into $elements in the correct order, to
6440
    // preserve sorting if the same element is passed through
6441
    // element_children() twice.
6442
    foreach ($children as $key => $child) {
6443
      unset($elements[$key]);
6444
      $elements[$key] = $child;
6445
    }
6446
    $elements['#sorted'] = TRUE;
6447
  }
6448

    
6449
  return array_keys($children);
6450
}
6451

    
6452
/**
6453
 * Returns the visible children of an element.
6454
 *
6455
 * @param $elements
6456
 *   The parent element.
6457
 *
6458
 * @return
6459
 *   The array keys of the element's visible children.
6460
 */
6461
function element_get_visible_children(array $elements) {
6462
  $visible_children = array();
6463

    
6464
  foreach (element_children($elements) as $key) {
6465
    $child = $elements[$key];
6466

    
6467
    // Skip un-accessible children.
6468
    if (isset($child['#access']) && !$child['#access']) {
6469
      continue;
6470
    }
6471

    
6472
    // Skip value and hidden elements, since they are not rendered.
6473
    if (isset($child['#type']) && in_array($child['#type'], array('value', 'hidden'))) {
6474
      continue;
6475
    }
6476

    
6477
    $visible_children[$key] = $child;
6478
  }
6479

    
6480
  return array_keys($visible_children);
6481
}
6482

    
6483
/**
6484
 * Sets HTML attributes based on element properties.
6485
 *
6486
 * @param $element
6487
 *   The renderable element to process.
6488
 * @param $map
6489
 *   An associative array whose keys are element property names and whose values
6490
 *   are the HTML attribute names to set for corresponding the property; e.g.,
6491
 *   array('#propertyname' => 'attributename'). If both names are identical
6492
 *   except for the leading '#', then an attribute name value is sufficient and
6493
 *   no property name needs to be specified.
6494
 */
6495
function element_set_attributes(array &$element, array $map) {
6496
  foreach ($map as $property => $attribute) {
6497
    // If the key is numeric, the attribute name needs to be taken over.
6498
    if (is_int($property)) {
6499
      $property = '#' . $attribute;
6500
    }
6501
    // Do not overwrite already existing attributes.
6502
    if (isset($element[$property]) && !isset($element['#attributes'][$attribute])) {
6503
      $element['#attributes'][$attribute] = $element[$property];
6504
    }
6505
  }
6506
}
6507

    
6508
/**
6509
 * Recursively computes the difference of arrays with additional index check.
6510
 *
6511
 * This is a version of array_diff_assoc() that supports multidimensional
6512
 * arrays.
6513
 *
6514
 * @param array $array1
6515
 *   The array to compare from.
6516
 * @param array $array2
6517
 *   The array to compare to.
6518
 *
6519
 * @return array
6520
 *   Returns an array containing all the values from array1 that are not present
6521
 *   in array2.
6522
 */
6523
function drupal_array_diff_assoc_recursive($array1, $array2) {
6524
  $difference = array();
6525

    
6526
  foreach ($array1 as $key => $value) {
6527
    if (is_array($value)) {
6528
      if (!array_key_exists($key, $array2) || !is_array($array2[$key])) {
6529
        $difference[$key] = $value;
6530
      }
6531
      else {
6532
        $new_diff = drupal_array_diff_assoc_recursive($value, $array2[$key]);
6533
        if (!empty($new_diff)) {
6534
          $difference[$key] = $new_diff;
6535
        }
6536
      }
6537
    }
6538
    elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
6539
      $difference[$key] = $value;
6540
    }
6541
  }
6542

    
6543
  return $difference;
6544
}
6545

    
6546
/**
6547
 * Sets a value in a nested array with variable depth.
6548
 *
6549
 * This helper function should be used when the depth of the array element you
6550
 * are changing may vary (that is, the number of parent keys is variable). It
6551
 * is primarily used for form structures and renderable arrays.
6552
 *
6553
 * Example:
6554
 * @code
6555
 * // Assume you have a 'signature' element somewhere in a form. It might be:
6556
 * $form['signature_settings']['signature'] = array(
6557
 *   '#type' => 'text_format',
6558
 *   '#title' => t('Signature'),
6559
 * );
6560
 * // Or, it might be further nested:
6561
 * $form['signature_settings']['user']['signature'] = array(
6562
 *   '#type' => 'text_format',
6563
 *   '#title' => t('Signature'),
6564
 * );
6565
 * @endcode
6566
 *
6567
 * To deal with the situation, the code needs to figure out the route to the
6568
 * element, given an array of parents that is either
6569
 * @code array('signature_settings', 'signature') @endcode in the first case or
6570
 * @code array('signature_settings', 'user', 'signature') @endcode in the second
6571
 * case.
6572
 *
6573
 * Without this helper function the only way to set the signature element in one
6574
 * line would be using eval(), which should be avoided:
6575
 * @code
6576
 * // Do not do this! Avoid eval().
6577
 * eval('$form[\'' . implode("']['", $parents) . '\'] = $element;');
6578
 * @endcode
6579
 *
6580
 * Instead, use this helper function:
6581
 * @code
6582
 * drupal_array_set_nested_value($form, $parents, $element);
6583
 * @endcode
6584
 *
6585
 * However if the number of array parent keys is static, the value should always
6586
 * be set directly rather than calling this function. For instance, for the
6587
 * first example we could just do:
6588
 * @code
6589
 * $form['signature_settings']['signature'] = $element;
6590
 * @endcode
6591
 *
6592
 * @param $array
6593
 *   A reference to the array to modify.
6594
 * @param $parents
6595
 *   An array of parent keys, starting with the outermost key.
6596
 * @param $value
6597
 *   The value to set.
6598
 * @param $force
6599
 *   (Optional) If TRUE, the value is forced into the structure even if it
6600
 *   requires the deletion of an already existing non-array parent value. If
6601
 *   FALSE, PHP throws an error if trying to add into a value that is not an
6602
 *   array. Defaults to FALSE.
6603
 *
6604
 * @see drupal_array_get_nested_value()
6605
 */
6606
function drupal_array_set_nested_value(array &$array, array $parents, $value, $force = FALSE) {
6607
  $ref = &$array;
6608
  foreach ($parents as $parent) {
6609
    // PHP auto-creates container arrays and NULL entries without error if $ref
6610
    // is NULL, but throws an error if $ref is set, but not an array.
6611
    if ($force && isset($ref) && !is_array($ref)) {
6612
      $ref = array();
6613
    }
6614
    $ref = &$ref[$parent];
6615
  }
6616
  $ref = $value;
6617
}
6618

    
6619
/**
6620
 * Retrieves a value from a nested array with variable depth.
6621
 *
6622
 * This helper function should be used when the depth of the array element being
6623
 * retrieved may vary (that is, the number of parent keys is variable). It is
6624
 * primarily used for form structures and renderable arrays.
6625
 *
6626
 * Without this helper function the only way to get a nested array value with
6627
 * variable depth in one line would be using eval(), which should be avoided:
6628
 * @code
6629
 * // Do not do this! Avoid eval().
6630
 * // May also throw a PHP notice, if the variable array keys do not exist.
6631
 * eval('$value = $array[\'' . implode("']['", $parents) . "'];");
6632
 * @endcode
6633
 *
6634
 * Instead, use this helper function:
6635
 * @code
6636
 * $value = drupal_array_get_nested_value($form, $parents);
6637
 * @endcode
6638
 *
6639
 * The return value will be NULL, regardless of whether the actual value is NULL
6640
 * or whether the requested key does not exist. If it is required to know
6641
 * whether the nested array key actually exists, pass a third argument that is
6642
 * altered by reference:
6643
 * @code
6644
 * $key_exists = NULL;
6645
 * $value = drupal_array_get_nested_value($form, $parents, $key_exists);
6646
 * if ($key_exists) {
6647
 *   // ... do something with $value ...
6648
 * }
6649
 * @endcode
6650
 *
6651
 * However if the number of array parent keys is static, the value should always
6652
 * be retrieved directly rather than calling this function. For instance:
6653
 * @code
6654
 * $value = $form['signature_settings']['signature'];
6655
 * @endcode
6656
 *
6657
 * @param $array
6658
 *   The array from which to get the value.
6659
 * @param $parents
6660
 *   An array of parent keys of the value, starting with the outermost key.
6661
 * @param $key_exists
6662
 *   (optional) If given, an already defined variable that is altered by
6663
 *   reference.
6664
 *
6665
 * @return
6666
 *   The requested nested value. Possibly NULL if the value is NULL or not all
6667
 *   nested parent keys exist. $key_exists is altered by reference and is a
6668
 *   Boolean that indicates whether all nested parent keys exist (TRUE) or not
6669
 *   (FALSE). This allows to distinguish between the two possibilities when NULL
6670
 *   is returned.
6671
 *
6672
 * @see drupal_array_set_nested_value()
6673
 */
6674
function &drupal_array_get_nested_value(array &$array, array $parents, &$key_exists = NULL) {
6675
  $ref = &$array;
6676
  foreach ($parents as $parent) {
6677
    if (is_array($ref) && array_key_exists($parent, $ref)) {
6678
      $ref = &$ref[$parent];
6679
    }
6680
    else {
6681
      $key_exists = FALSE;
6682
      $null = NULL;
6683
      return $null;
6684
    }
6685
  }
6686
  $key_exists = TRUE;
6687
  return $ref;
6688
}
6689

    
6690
/**
6691
 * Determines whether a nested array contains the requested keys.
6692
 *
6693
 * This helper function should be used when the depth of the array element to be
6694
 * checked may vary (that is, the number of parent keys is variable). See
6695
 * drupal_array_set_nested_value() for details. It is primarily used for form
6696
 * structures and renderable arrays.
6697
 *
6698
 * If it is required to also get the value of the checked nested key, use
6699
 * drupal_array_get_nested_value() instead.
6700
 *
6701
 * If the number of array parent keys is static, this helper function is
6702
 * unnecessary and the following code can be used instead:
6703
 * @code
6704
 * $value_exists = isset($form['signature_settings']['signature']);
6705
 * $key_exists = array_key_exists('signature', $form['signature_settings']);
6706
 * @endcode
6707
 *
6708
 * @param $array
6709
 *   The array with the value to check for.
6710
 * @param $parents
6711
 *   An array of parent keys of the value, starting with the outermost key.
6712
 *
6713
 * @return
6714
 *   TRUE if all the parent keys exist, FALSE otherwise.
6715
 *
6716
 * @see drupal_array_get_nested_value()
6717
 */
6718
function drupal_array_nested_key_exists(array $array, array $parents) {
6719
  // Although this function is similar to PHP's array_key_exists(), its
6720
  // arguments should be consistent with drupal_array_get_nested_value().
6721
  $key_exists = NULL;
6722
  drupal_array_get_nested_value($array, $parents, $key_exists);
6723
  return $key_exists;
6724
}
6725

    
6726
/**
6727
 * Provides theme registration for themes across .inc files.
6728
 */
6729
function drupal_common_theme() {
6730
  return array(
6731
    // From theme.inc.
6732
    'html' => array(
6733
      'render element' => 'page',
6734
      'template' => 'html',
6735
    ),
6736
    'page' => array(
6737
      'render element' => 'page',
6738
      'template' => 'page',
6739
    ),
6740
    'region' => array(
6741
      'render element' => 'elements',
6742
      'template' => 'region',
6743
    ),
6744
    'status_messages' => array(
6745
      'variables' => array('display' => NULL),
6746
    ),
6747
    'link' => array(
6748
      'variables' => array('text' => NULL, 'path' => NULL, 'options' => array()),
6749
    ),
6750
    'links' => array(
6751
      'variables' => array('links' => NULL, 'attributes' => array('class' => array('links')), 'heading' => array()),
6752
    ),
6753
    'image' => array(
6754
      // HTML 4 and XHTML 1.0 always require an alt attribute. The HTML 5 draft
6755
      // allows the alt attribute to be omitted in some cases. Therefore,
6756
      // default the alt attribute to an empty string, but allow code calling
6757
      // theme('image') to pass explicit NULL for it to be omitted. Usually,
6758
      // neither omission nor an empty string satisfies accessibility
6759
      // requirements, so it is strongly encouraged for code calling
6760
      // theme('image') to pass a meaningful value for the alt variable.
6761
      // - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
6762
      // - http://www.w3.org/TR/xhtml1/dtds.html
6763
      // - http://dev.w3.org/html5/spec/Overview.html#alt
6764
      // The title attribute is optional in all cases, so it is omitted by
6765
      // default.
6766
      'variables' => array('path' => NULL, 'width' => NULL, 'height' => NULL, 'alt' => '', 'title' => NULL, 'attributes' => array()),
6767
    ),
6768
    'breadcrumb' => array(
6769
      'variables' => array('breadcrumb' => NULL),
6770
    ),
6771
    'help' => array(
6772
      'variables' => array(),
6773
    ),
6774
    'table' => array(
6775
      'variables' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL, 'colgroups' => array(), 'sticky' => TRUE, 'empty' => ''),
6776
    ),
6777
    'tablesort_indicator' => array(
6778
      'variables' => array('style' => NULL),
6779
    ),
6780
    'mark' => array(
6781
      'variables' => array('type' => MARK_NEW),
6782
    ),
6783
    'item_list' => array(
6784
      'variables' => array('items' => array(), 'title' => NULL, 'type' => 'ul', 'attributes' => array()),
6785
    ),
6786
    'more_help_link' => array(
6787
      'variables' => array('url' => NULL),
6788
    ),
6789
    'feed_icon' => array(
6790
      'variables' => array('url' => NULL, 'title' => NULL),
6791
    ),
6792
    'more_link' => array(
6793
      'variables' => array('url' => NULL, 'title' => NULL)
6794
    ),
6795
    'username' => array(
6796
      'variables' => array('account' => NULL),
6797
    ),
6798
    'progress_bar' => array(
6799
      'variables' => array('percent' => NULL, 'message' => NULL),
6800
    ),
6801
    'indentation' => array(
6802
      'variables' => array('size' => 1),
6803
    ),
6804
    'html_tag' => array(
6805
      'render element' => 'element',
6806
    ),
6807
    // From theme.maintenance.inc.
6808
    'maintenance_page' => array(
6809
      'variables' => array('content' => NULL, 'show_messages' => TRUE),
6810
      'template' => 'maintenance-page',
6811
    ),
6812
    'update_page' => array(
6813
      'variables' => array('content' => NULL, 'show_messages' => TRUE),
6814
    ),
6815
    'install_page' => array(
6816
      'variables' => array('content' => NULL),
6817
    ),
6818
    'task_list' => array(
6819
      'variables' => array('items' => NULL, 'active' => NULL),
6820
    ),
6821
    'authorize_message' => array(
6822
      'variables' => array('message' => NULL, 'success' => TRUE),
6823
    ),
6824
    'authorize_report' => array(
6825
      'variables' => array('messages' => array()),
6826
    ),
6827
    // From pager.inc.
6828
    'pager' => array(
6829
      'variables' => array('tags' => array(), 'element' => 0, 'parameters' => array(), 'quantity' => 9),
6830
    ),
6831
    'pager_first' => array(
6832
      'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
6833
    ),
6834
    'pager_previous' => array(
6835
      'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
6836
    ),
6837
    'pager_next' => array(
6838
      'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
6839
    ),
6840
    'pager_last' => array(
6841
      'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
6842
    ),
6843
    'pager_link' => array(
6844
      'variables' => array('text' => NULL, 'page_new' => NULL, 'element' => NULL, 'parameters' => array(), 'attributes' => array()),
6845
    ),
6846
    // From menu.inc.
6847
    'menu_link' => array(
6848
      'render element' => 'element',
6849
    ),
6850
    'menu_tree' => array(
6851
      'render element' => 'tree',
6852
    ),
6853
    'menu_local_task' => array(
6854
      'render element' => 'element',
6855
    ),
6856
    'menu_local_action' => array(
6857
      'render element' => 'element',
6858
    ),
6859
    'menu_local_tasks' => array(
6860
      'variables' => array('primary' => array(), 'secondary' => array()),
6861
    ),
6862
    // From form.inc.
6863
    'select' => array(
6864
      'render element' => 'element',
6865
    ),
6866
    'fieldset' => array(
6867
      'render element' => 'element',
6868
    ),
6869
    'radio' => array(
6870
      'render element' => 'element',
6871
    ),
6872
    'radios' => array(
6873
      'render element' => 'element',
6874
    ),
6875
    'date' => array(
6876
      'render element' => 'element',
6877
    ),
6878
    'exposed_filters' => array(
6879
      'render element' => 'form',
6880
    ),
6881
    'checkbox' => array(
6882
      'render element' => 'element',
6883
    ),
6884
    'checkboxes' => array(
6885
      'render element' => 'element',
6886
    ),
6887
    'button' => array(
6888
      'render element' => 'element',
6889
    ),
6890
    'image_button' => array(
6891
      'render element' => 'element',
6892
    ),
6893
    'hidden' => array(
6894
      'render element' => 'element',
6895
    ),
6896
    'textfield' => array(
6897
      'render element' => 'element',
6898
    ),
6899
    'form' => array(
6900
      'render element' => 'element',
6901
    ),
6902
    'textarea' => array(
6903
      'render element' => 'element',
6904
    ),
6905
    'password' => array(
6906
      'render element' => 'element',
6907
    ),
6908
    'file' => array(
6909
      'render element' => 'element',
6910
    ),
6911
    'tableselect' => array(
6912
      'render element' => 'element',
6913
    ),
6914
    'form_element' => array(
6915
      'render element' => 'element',
6916
    ),
6917
    'form_required_marker' => array(
6918
      'render element' => 'element',
6919
    ),
6920
    'form_element_label' => array(
6921
      'render element' => 'element',
6922
    ),
6923
    'vertical_tabs' => array(
6924
      'render element' => 'element',
6925
    ),
6926
    'container' => array(
6927
      'render element' => 'element',
6928
    ),
6929
  );
6930
}
6931

    
6932
/**
6933
 * @addtogroup schemaapi
6934
 * @{
6935
 */
6936

    
6937
/**
6938
 * Creates all tables defined in a module's hook_schema().
6939
 *
6940
 * Note: This function does not pass the module's schema through
6941
 * hook_schema_alter(). The module's tables will be created exactly as the
6942
 * module defines them.
6943
 *
6944
 * @param $module
6945
 *   The module for which the tables will be created.
6946
 */
6947
function drupal_install_schema($module) {
6948
  $schema = drupal_get_schema_unprocessed($module);
6949
  _drupal_schema_initialize($schema, $module, FALSE);
6950

    
6951
  foreach ($schema as $name => $table) {
6952
    db_create_table($name, $table);
6953
  }
6954
}
6955

    
6956
/**
6957
 * Removes all tables defined in a module's hook_schema().
6958
 *
6959
 * Note: This function does not pass the module's schema through
6960
 * hook_schema_alter(). The module's tables will be created exactly as the
6961
 * module defines them.
6962
 *
6963
 * @param $module
6964
 *   The module for which the tables will be removed.
6965
 *
6966
 * @return
6967
 *   An array of arrays with the following key/value pairs:
6968
 *    - success: a boolean indicating whether the query succeeded.
6969
 *    - query: the SQL query(s) executed, passed through check_plain().
6970
 */
6971
function drupal_uninstall_schema($module) {
6972
  $schema = drupal_get_schema_unprocessed($module);
6973
  _drupal_schema_initialize($schema, $module, FALSE);
6974

    
6975
  foreach ($schema as $table) {
6976
    if (db_table_exists($table['name'])) {
6977
      db_drop_table($table['name']);
6978
    }
6979
  }
6980
}
6981

    
6982
/**
6983
 * Returns the unprocessed and unaltered version of a module's schema.
6984
 *
6985
 * Use this function only if you explicitly need the original
6986
 * specification of a schema, as it was defined in a module's
6987
 * hook_schema(). No additional default values will be set,
6988
 * hook_schema_alter() is not invoked and these unprocessed
6989
 * definitions won't be cached.
6990
 *
6991
 * This function can be used to retrieve a schema specification in
6992
 * hook_schema(), so it allows you to derive your tables from existing
6993
 * specifications.
6994
 *
6995
 * It is also used by drupal_install_schema() and
6996
 * drupal_uninstall_schema() to ensure that a module's tables are
6997
 * created exactly as specified without any changes introduced by a
6998
 * module that implements hook_schema_alter().
6999
 *
7000
 * @param $module
7001
 *   The module to which the table belongs.
7002
 * @param $table
7003
 *   The name of the table. If not given, the module's complete schema
7004
 *   is returned.
7005
 */
7006
function drupal_get_schema_unprocessed($module, $table = NULL) {
7007
  // Load the .install file to get hook_schema.
7008
  module_load_install($module);
7009
  $schema = module_invoke($module, 'schema');
7010

    
7011
  if (isset($table) && isset($schema[$table])) {
7012
    return $schema[$table];
7013
  }
7014
  elseif (!empty($schema)) {
7015
    return $schema;
7016
  }
7017
  return array();
7018
}
7019

    
7020
/**
7021
 * Fills in required default values for table definitions from hook_schema().
7022
 *
7023
 * @param $schema
7024
 *   The schema definition array as it was returned by the module's
7025
 *   hook_schema().
7026
 * @param $module
7027
 *   The module for which hook_schema() was invoked.
7028
 * @param $remove_descriptions
7029
 *   (optional) Whether to additionally remove 'description' keys of all tables
7030
 *   and fields to improve performance of serialize() and unserialize().
7031
 *   Defaults to TRUE.
7032
 */
7033
function _drupal_schema_initialize(&$schema, $module, $remove_descriptions = TRUE) {
7034
  // Set the name and module key for all tables.
7035
  foreach ($schema as $name => &$table) {
7036
    if (empty($table['module'])) {
7037
      $table['module'] = $module;
7038
    }
7039
    if (!isset($table['name'])) {
7040
      $table['name'] = $name;
7041
    }
7042
    if ($remove_descriptions) {
7043
      unset($table['description']);
7044
      foreach ($table['fields'] as &$field) {
7045
        unset($field['description']);
7046
      }
7047
    }
7048
  }
7049
}
7050

    
7051
/**
7052
 * Retrieves a list of fields from a table schema.
7053
 *
7054
 * The returned list is suitable for use in an SQL query.
7055
 *
7056
 * @param $table
7057
 *   The name of the table from which to retrieve fields.
7058
 * @param
7059
 *   An optional prefix to to all fields.
7060
 *
7061
 * @return An array of fields.
7062
 */
7063
function drupal_schema_fields_sql($table, $prefix = NULL) {
7064
  $schema = drupal_get_schema($table);
7065
  $fields = array_keys($schema['fields']);
7066
  if ($prefix) {
7067
    $columns = array();
7068
    foreach ($fields as $field) {
7069
      $columns[] = "$prefix.$field";
7070
    }
7071
    return $columns;
7072
  }
7073
  else {
7074
    return $fields;
7075
  }
7076
}
7077

    
7078
/**
7079
 * Saves (inserts or updates) a record to the database based upon the schema.
7080
 *
7081
 * Do not use drupal_write_record() within hook_update_N() functions, since the
7082
 * database schema cannot be relied upon when a user is running a series of
7083
 * updates. Instead, use db_insert() or db_update() to save the record.
7084
 *
7085
 * @param $table
7086
 *   The name of the table; this must be defined by a hook_schema()
7087
 *   implementation.
7088
 * @param $record
7089
 *   An object or array representing the record to write, passed in by
7090
 *   reference. If inserting a new record, values not provided in $record will
7091
 *   be populated in $record and in the database with the default values from
7092
 *   the schema, as well as a single serial (auto-increment) field (if present).
7093
 *   If updating an existing record, only provided values are updated in the
7094
 *   database, and $record is not modified.
7095
 * @param $primary_keys
7096
 *   To indicate that this is a new record to be inserted, omit this argument.
7097
 *   If this is an update, this argument specifies the primary keys' field
7098
 *   names. If there is only 1 field in the key, you may pass in a string; if
7099
 *   there are multiple fields in the key, pass in an array.
7100
 *
7101
 * @return
7102
 *   If the record insert or update failed, returns FALSE. If it succeeded,
7103
 *   returns SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
7104
 */
7105
function drupal_write_record($table, &$record, $primary_keys = array()) {
7106
  // Standardize $primary_keys to an array.
7107
  if (is_string($primary_keys)) {
7108
    $primary_keys = array($primary_keys);
7109
  }
7110

    
7111
  $schema = drupal_get_schema($table);
7112
  if (empty($schema)) {
7113
    return FALSE;
7114
  }
7115

    
7116
  $object = (object) $record;
7117
  $fields = array();
7118

    
7119
  // Go through the schema to determine fields to write.
7120
  foreach ($schema['fields'] as $field => $info) {
7121
    if ($info['type'] == 'serial') {
7122
      // Skip serial types if we are updating.
7123
      if (!empty($primary_keys)) {
7124
        continue;
7125
      }
7126
      // Track serial field so we can helpfully populate them after the query.
7127
      // NOTE: Each table should come with one serial field only.
7128
      $serial = $field;
7129
    }
7130

    
7131
    // Skip field if it is in $primary_keys as it is unnecessary to update a
7132
    // field to the value it is already set to.
7133
    if (in_array($field, $primary_keys)) {
7134
      continue;
7135
    }
7136

    
7137
    if (!property_exists($object, $field)) {
7138
      // Skip fields that are not provided, default values are already known
7139
      // by the database.
7140
      continue;
7141
    }
7142

    
7143
    // Build array of fields to update or insert.
7144
    if (empty($info['serialize'])) {
7145
      $fields[$field] = $object->$field;
7146
    }
7147
    else {
7148
      $fields[$field] = serialize($object->$field);
7149
    }
7150

    
7151
    // Type cast to proper datatype, except when the value is NULL and the
7152
    // column allows this.
7153
    //
7154
    // MySQL PDO silently casts e.g. FALSE and '' to 0 when inserting the value
7155
    // into an integer column, but PostgreSQL PDO does not. Also type cast NULL
7156
    // when the column does not allow this.
7157
    if (isset($object->$field) || !empty($info['not null'])) {
7158
      if ($info['type'] == 'int' || $info['type'] == 'serial') {
7159
        $fields[$field] = (int) $fields[$field];
7160
      }
7161
      elseif ($info['type'] == 'float') {
7162
        $fields[$field] = (float) $fields[$field];
7163
      }
7164
      else {
7165
        $fields[$field] = (string) $fields[$field];
7166
      }
7167
    }
7168
  }
7169

    
7170
  if (empty($fields)) {
7171
    return;
7172
  }
7173

    
7174
  // Build the SQL.
7175
  if (empty($primary_keys)) {
7176
    // We are doing an insert.
7177
    $options = array('return' => Database::RETURN_INSERT_ID);
7178
    if (isset($serial) && isset($fields[$serial])) {
7179
      // If the serial column has been explicitly set with an ID, then we don't
7180
      // require the database to return the last insert id.
7181
      if ($fields[$serial]) {
7182
        $options['return'] = Database::RETURN_AFFECTED;
7183
      }
7184
      // If a serial column does exist with no value (i.e. 0) then remove it as
7185
      // the database will insert the correct value for us.
7186
      else {
7187
        unset($fields[$serial]);
7188
      }
7189
    }
7190
    $query = db_insert($table, $options)->fields($fields);
7191
    $return = SAVED_NEW;
7192
  }
7193
  else {
7194
    $query = db_update($table)->fields($fields);
7195
    foreach ($primary_keys as $key) {
7196
      $query->condition($key, $object->$key);
7197
    }
7198
    $return = SAVED_UPDATED;
7199
  }
7200

    
7201
  // Execute the SQL.
7202
  if ($query_return = $query->execute()) {
7203
    if (isset($serial)) {
7204
      // If the database was not told to return the last insert id, it will be
7205
      // because we already know it.
7206
      if (isset($options) && $options['return'] != Database::RETURN_INSERT_ID) {
7207
        $object->$serial = $fields[$serial];
7208
      }
7209
      else {
7210
        $object->$serial = $query_return;
7211
      }
7212
    }
7213
  }
7214
  // If we have a single-field primary key but got no insert ID, the
7215
  // query failed. Note that we explicitly check for FALSE, because
7216
  // a valid update query which doesn't change any values will return
7217
  // zero (0) affected rows.
7218
  elseif ($query_return === FALSE && count($primary_keys) == 1) {
7219
    $return = FALSE;
7220
  }
7221

    
7222
  // If we are inserting, populate empty fields with default values.
7223
  if (empty($primary_keys)) {
7224
    foreach ($schema['fields'] as $field => $info) {
7225
      if (isset($info['default']) && !property_exists($object, $field)) {
7226
        $object->$field = $info['default'];
7227
      }
7228
    }
7229
  }
7230

    
7231
  // If we began with an array, convert back.
7232
  if (is_array($record)) {
7233
    $record = (array) $object;
7234
  }
7235

    
7236
  return $return;
7237
}
7238

    
7239
/**
7240
 * @} End of "addtogroup schemaapi".
7241
 */
7242

    
7243
/**
7244
 * Parses Drupal module and theme .info files.
7245
 *
7246
 * Info files are NOT for placing arbitrary theme and module-specific settings.
7247
 * Use variable_get() and variable_set() for that.
7248
 *
7249
 * Information stored in a module .info file:
7250
 * - name: The real name of the module for display purposes.
7251
 * - description: A brief description of the module.
7252
 * - dependencies: An array of shortnames of other modules this module requires.
7253
 * - package: The name of the package of modules this module belongs to.
7254
 *
7255
 * See forum.info for an example of a module .info file.
7256
 *
7257
 * Information stored in a theme .info file:
7258
 * - name: The real name of the theme for display purposes.
7259
 * - description: Brief description.
7260
 * - screenshot: Path to screenshot relative to the theme's .info file.
7261
 * - engine: Theme engine; typically phptemplate.
7262
 * - base: Name of a base theme, if applicable; e.g., base = zen.
7263
 * - regions: Listed regions; e.g., region[left] = Left sidebar.
7264
 * - features: Features available; e.g., features[] = logo.
7265
 * - stylesheets: Theme stylesheets; e.g., stylesheets[all][] = my-style.css.
7266
 * - scripts: Theme scripts; e.g., scripts[] = my-script.js.
7267
 *
7268
 * See bartik.info for an example of a theme .info file.
7269
 *
7270
 * @param $filename
7271
 *   The file we are parsing. Accepts file with relative or absolute path.
7272
 *
7273
 * @return
7274
 *   The info array.
7275
 *
7276
 * @see drupal_parse_info_format()
7277
 */
7278
function drupal_parse_info_file($filename) {
7279
  $info = &drupal_static(__FUNCTION__, array());
7280

    
7281
  if (!isset($info[$filename])) {
7282
    if (!file_exists($filename)) {
7283
      $info[$filename] = array();
7284
    }
7285
    else {
7286
      $data = file_get_contents($filename);
7287
      $info[$filename] = drupal_parse_info_format($data);
7288
    }
7289
  }
7290
  return $info[$filename];
7291
}
7292

    
7293
/**
7294
 * Parses data in Drupal's .info format.
7295
 *
7296
 * Data should be in an .ini-like format to specify values. White-space
7297
 * generally doesn't matter, except inside values:
7298
 * @code
7299
 *   key = value
7300
 *   key = "value"
7301
 *   key = 'value'
7302
 *   key = "multi-line
7303
 *   value"
7304
 *   key = 'multi-line
7305
 *   value'
7306
 *   key
7307
 *   =
7308
 *   'value'
7309
 * @endcode
7310
 *
7311
 * Arrays are created using a HTTP GET alike syntax:
7312
 * @code
7313
 *   key[] = "numeric array"
7314
 *   key[index] = "associative array"
7315
 *   key[index][] = "nested numeric array"
7316
 *   key[index][index] = "nested associative array"
7317
 * @endcode
7318
 *
7319
 * PHP constants are substituted in, but only when used as the entire value.
7320
 * Comments should start with a semi-colon at the beginning of a line.
7321
 *
7322
 * @param $data
7323
 *   A string to parse.
7324
 *
7325
 * @return
7326
 *   The info array.
7327
 *
7328
 * @see drupal_parse_info_file()
7329
 */
7330
function drupal_parse_info_format($data) {
7331
  $info = array();
7332
  $constants = get_defined_constants();
7333

    
7334
  if (preg_match_all('
7335
    @^\s*                           # Start at the beginning of a line, ignoring leading whitespace
7336
    ((?:
7337
      [^=;\[\]]|                    # Key names cannot contain equal signs, semi-colons or square brackets,
7338
      \[[^\[\]]*\]                  # unless they are balanced and not nested
7339
    )+?)
7340
    \s*=\s*                         # Key/value pairs are separated by equal signs (ignoring white-space)
7341
    (?:
7342
      ("(?:[^"]|(?<=\\\\)")*")|     # Double-quoted string, which may contain slash-escaped quotes/slashes
7343
      (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
7344
      ([^\r\n]*?)                   # Non-quoted string
7345
    )\s*$                           # Stop at the next end of a line, ignoring trailing whitespace
7346
    @msx', $data, $matches, PREG_SET_ORDER)) {
7347
    foreach ($matches as $match) {
7348
      // Fetch the key and value string.
7349
      $i = 0;
7350
      foreach (array('key', 'value1', 'value2', 'value3') as $var) {
7351
        $$var = isset($match[++$i]) ? $match[$i] : '';
7352
      }
7353
      $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
7354

    
7355
      // Parse array syntax.
7356
      $keys = preg_split('/\]?\[/', rtrim($key, ']'));
7357
      $last = array_pop($keys);
7358
      $parent = &$info;
7359

    
7360
      // Create nested arrays.
7361
      foreach ($keys as $key) {
7362
        if ($key == '') {
7363
          $key = count($parent);
7364
        }
7365
        if (!isset($parent[$key]) || !is_array($parent[$key])) {
7366
          $parent[$key] = array();
7367
        }
7368
        $parent = &$parent[$key];
7369
      }
7370

    
7371
      // Handle PHP constants.
7372
      if (isset($constants[$value])) {
7373
        $value = $constants[$value];
7374
      }
7375

    
7376
      // Insert actual value.
7377
      if ($last == '') {
7378
        $last = count($parent);
7379
      }
7380
      $parent[$last] = $value;
7381
    }
7382
  }
7383

    
7384
  return $info;
7385
}
7386

    
7387
/**
7388
 * Returns a list of severity levels, as defined in RFC 3164.
7389
 *
7390
 * @return
7391
 *   Array of the possible severity levels for log messages.
7392
 *
7393
 * @see http://www.ietf.org/rfc/rfc3164.txt
7394
 * @see watchdog()
7395
 * @ingroup logging_severity_levels
7396
 */
7397
function watchdog_severity_levels() {
7398
  return array(
7399
    WATCHDOG_EMERGENCY => t('emergency'),
7400
    WATCHDOG_ALERT     => t('alert'),
7401
    WATCHDOG_CRITICAL  => t('critical'),
7402
    WATCHDOG_ERROR     => t('error'),
7403
    WATCHDOG_WARNING   => t('warning'),
7404
    WATCHDOG_NOTICE    => t('notice'),
7405
    WATCHDOG_INFO      => t('info'),
7406
    WATCHDOG_DEBUG     => t('debug'),
7407
  );
7408
}
7409

    
7410

    
7411
/**
7412
 * Explodes a string of tags into an array.
7413
 *
7414
 * @see drupal_implode_tags()
7415
 */
7416
function drupal_explode_tags($tags) {
7417
  // This regexp allows the following types of user input:
7418
  // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
7419
  $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
7420
  preg_match_all($regexp, $tags, $matches);
7421
  $typed_tags = array_unique($matches[1]);
7422

    
7423
  $tags = array();
7424
  foreach ($typed_tags as $tag) {
7425
    // If a user has escaped a term (to demonstrate that it is a group,
7426
    // or includes a comma or quote character), we remove the escape
7427
    // formatting so to save the term into the database as the user intends.
7428
    $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
7429
    if ($tag != "") {
7430
      $tags[] = $tag;
7431
    }
7432
  }
7433

    
7434
  return $tags;
7435
}
7436

    
7437
/**
7438
 * Implodes an array of tags into a string.
7439
 *
7440
 * @see drupal_explode_tags()
7441
 */
7442
function drupal_implode_tags($tags) {
7443
  $encoded_tags = array();
7444
  foreach ($tags as $tag) {
7445
    // Commas and quotes in tag names are special cases, so encode them.
7446
    if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
7447
      $tag = '"' . str_replace('"', '""', $tag) . '"';
7448
    }
7449

    
7450
    $encoded_tags[] = $tag;
7451
  }
7452
  return implode(', ', $encoded_tags);
7453
}
7454

    
7455
/**
7456
 * Flushes all cached data on the site.
7457
 *
7458
 * Empties cache tables, rebuilds the menu cache and theme registries, and
7459
 * invokes a hook so that other modules' cache data can be cleared as well.
7460
 */
7461
function drupal_flush_all_caches() {
7462
  // Change query-strings on css/js files to enforce reload for all users.
7463
  _drupal_flush_css_js();
7464

    
7465
  registry_rebuild();
7466
  drupal_clear_css_cache();
7467
  drupal_clear_js_cache();
7468

    
7469
  // Rebuild the theme data. Note that the module data is rebuilt above, as
7470
  // part of registry_rebuild().
7471
  system_rebuild_theme_data();
7472
  drupal_theme_rebuild();
7473

    
7474
  entity_info_cache_clear();
7475
  node_types_rebuild();
7476
  // node_menu() defines menu items based on node types so it needs to come
7477
  // after node types are rebuilt.
7478
  menu_rebuild();
7479

    
7480
  // Synchronize to catch any actions that were added or removed.
7481
  actions_synchronize();
7482

    
7483
  // Don't clear cache_form - in-progress form submissions may break.
7484
  // Ordered so clearing the page cache will always be the last action.
7485
  $core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
7486
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
7487
  foreach ($cache_tables as $table) {
7488
    cache_clear_all('*', $table, TRUE);
7489
  }
7490

    
7491
  // Rebuild the bootstrap module list. We do this here so that developers
7492
  // can get new hook_boot() implementations registered without having to
7493
  // write a hook_update_N() function.
7494
  _system_update_bootstrap_status();
7495
}
7496

    
7497
/**
7498
 * Changes the dummy query string added to all CSS and JavaScript files.
7499
 *
7500
 * Changing the dummy query string appended to CSS and JavaScript files forces
7501
 * all browsers to reload fresh files.
7502
 */
7503
function _drupal_flush_css_js() {
7504
  // The timestamp is converted to base 36 in order to make it more compact.
7505
  variable_set('css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
7506
}
7507

    
7508
/**
7509
 * Outputs debug information.
7510
 *
7511
 * The debug information is passed on to trigger_error() after being converted
7512
 * to a string using _drupal_debug_message().
7513
 *
7514
 * @param $data
7515
 *   Data to be output.
7516
 * @param $label
7517
 *   Label to prefix the data.
7518
 * @param $print_r
7519
 *   Flag to switch between print_r() and var_export() for data conversion to
7520
 *   string. Set $print_r to TRUE when dealing with a recursive data structure
7521
 *   as var_export() will generate an error.
7522
 */
7523
function debug($data, $label = NULL, $print_r = FALSE) {
7524
  // Print $data contents to string.
7525
  $string = check_plain($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
7526

    
7527
  // Display values with pre-formatting to increase readability.
7528
  $string = '<pre>' . $string . '</pre>';
7529

    
7530
  trigger_error(trim($label ? "$label: $string" : $string));
7531
}
7532

    
7533
/**
7534
 * Parses a dependency for comparison by drupal_check_incompatibility().
7535
 *
7536
 * @param $dependency
7537
 *   A dependency string, for example 'foo (>=7.x-4.5-beta5, 3.x)'.
7538
 *
7539
 * @return
7540
 *   An associative array with three keys:
7541
 *   - 'name' includes the name of the thing to depend on (e.g. 'foo').
7542
 *   - 'original_version' contains the original version string (which can be
7543
 *     used in the UI for reporting incompatibilities).
7544
 *   - 'versions' is a list of associative arrays, each containing the keys
7545
 *     'op' and 'version'. 'op' can be one of: '=', '==', '!=', '<>', '<',
7546
 *     '<=', '>', or '>='. 'version' is one piece like '4.5-beta3'.
7547
 *   Callers should pass this structure to drupal_check_incompatibility().
7548
 *
7549
 * @see drupal_check_incompatibility()
7550
 */
7551
function drupal_parse_dependency($dependency) {
7552
  // We use named subpatterns and support every op that version_compare
7553
  // supports. Also, op is optional and defaults to equals.
7554
  $p_op = '(?P<operation>!=|==|=|<|<=|>|>=|<>)?';
7555
  // Core version is always optional: 7.x-2.x and 2.x is treated the same.
7556
  $p_core = '(?:' . preg_quote(DRUPAL_CORE_COMPATIBILITY) . '-)?';
7557
  $p_major = '(?P<major>\d+)';
7558
  // By setting the minor version to x, branches can be matched.
7559
  $p_minor = '(?P<minor>(?:\d+|x)(?:-[A-Za-z]+\d+)?)';
7560
  $value = array();
7561
  $parts = explode('(', $dependency, 2);
7562
  $value['name'] = trim($parts[0]);
7563
  if (isset($parts[1])) {
7564
    $value['original_version'] = ' (' . $parts[1];
7565
    foreach (explode(',', $parts[1]) as $version) {
7566
      if (preg_match("/^\s*$p_op\s*$p_core$p_major\.$p_minor/", $version, $matches)) {
7567
        $op = !empty($matches['operation']) ? $matches['operation'] : '=';
7568
        if ($matches['minor'] == 'x') {
7569
          // Drupal considers "2.x" to mean any version that begins with
7570
          // "2" (e.g. 2.0, 2.9 are all "2.x"). PHP's version_compare(),
7571
          // on the other hand, treats "x" as a string; so to
7572
          // version_compare(), "2.x" is considered less than 2.0. This
7573
          // means that >=2.x and <2.x are handled by version_compare()
7574
          // as we need, but > and <= are not.
7575
          if ($op == '>' || $op == '<=') {
7576
            $matches['major']++;
7577
          }
7578
          // Equivalence can be checked by adding two restrictions.
7579
          if ($op == '=' || $op == '==') {
7580
            $value['versions'][] = array('op' => '<', 'version' => ($matches['major'] + 1) . '.x');
7581
            $op = '>=';
7582
          }
7583
        }
7584
        $value['versions'][] = array('op' => $op, 'version' => $matches['major'] . '.' . $matches['minor']);
7585
      }
7586
    }
7587
  }
7588
  return $value;
7589
}
7590

    
7591
/**
7592
 * Checks whether a version is compatible with a given dependency.
7593
 *
7594
 * @param $v
7595
 *   The parsed dependency structure from drupal_parse_dependency().
7596
 * @param $current_version
7597
 *   The version to check against (like 4.2).
7598
 *
7599
 * @return
7600
 *   NULL if compatible, otherwise the original dependency version string that
7601
 *   caused the incompatibility.
7602
 *
7603
 * @see drupal_parse_dependency()
7604
 */
7605
function drupal_check_incompatibility($v, $current_version) {
7606
  if (!empty($v['versions'])) {
7607
    foreach ($v['versions'] as $required_version) {
7608
      if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
7609
        return $v['original_version'];
7610
      }
7611
    }
7612
  }
7613
}
7614

    
7615
/**
7616
 * Get the entity info array of an entity type.
7617
 *
7618
 * @param $entity_type
7619
 *   The entity type, e.g. node, for which the info shall be returned, or NULL
7620
 *   to return an array with info about all types.
7621
 *
7622
 * @see hook_entity_info()
7623
 * @see hook_entity_info_alter()
7624
 */
7625
function entity_get_info($entity_type = NULL) {
7626
  global $language;
7627

    
7628
  // Use the advanced drupal_static() pattern, since this is called very often.
7629
  static $drupal_static_fast;
7630
  if (!isset($drupal_static_fast)) {
7631
    $drupal_static_fast['entity_info'] = &drupal_static(__FUNCTION__);
7632
  }
7633
  $entity_info = &$drupal_static_fast['entity_info'];
7634

    
7635
  // hook_entity_info() includes translated strings, so each language is cached
7636
  // separately.
7637
  $langcode = $language->language;
7638

    
7639
  if (empty($entity_info)) {
7640
    if ($cache = cache_get("entity_info:$langcode")) {
7641
      $entity_info = $cache->data;
7642
    }
7643
    else {
7644
      $entity_info = module_invoke_all('entity_info');
7645
      // Merge in default values.
7646
      foreach ($entity_info as $name => $data) {
7647
        $entity_info[$name] += array(
7648
          'fieldable' => FALSE,
7649
          'controller class' => 'DrupalDefaultEntityController',
7650
          'static cache' => TRUE,
7651
          'field cache' => TRUE,
7652
          'load hook' => $name . '_load',
7653
          'bundles' => array(),
7654
          'view modes' => array(),
7655
          'entity keys' => array(),
7656
          'translation' => array(),
7657
        );
7658
        $entity_info[$name]['entity keys'] += array(
7659
          'revision' => '',
7660
          'bundle' => '',
7661
        );
7662
        foreach ($entity_info[$name]['view modes'] as $view_mode => $view_mode_info) {
7663
          $entity_info[$name]['view modes'][$view_mode] += array(
7664
            'custom settings' => FALSE,
7665
          );
7666
        }
7667
        // If no bundle key is provided, assume a single bundle, named after
7668
        // the entity type.
7669
        if (empty($entity_info[$name]['entity keys']['bundle']) && empty($entity_info[$name]['bundles'])) {
7670
          $entity_info[$name]['bundles'] = array($name => array('label' => $entity_info[$name]['label']));
7671
        }
7672
        // Prepare entity schema fields SQL info for
7673
        // DrupalEntityControllerInterface::buildQuery().
7674
        if (isset($entity_info[$name]['base table'])) {
7675
          $entity_info[$name]['schema_fields_sql']['base table'] = drupal_schema_fields_sql($entity_info[$name]['base table']);
7676
          if (isset($entity_info[$name]['revision table'])) {
7677
            $entity_info[$name]['schema_fields_sql']['revision table'] = drupal_schema_fields_sql($entity_info[$name]['revision table']);
7678
          }
7679
        }
7680
      }
7681
      // Let other modules alter the entity info.
7682
      drupal_alter('entity_info', $entity_info);
7683
      cache_set("entity_info:$langcode", $entity_info);
7684
    }
7685
  }
7686

    
7687
  if (empty($entity_type)) {
7688
    return $entity_info;
7689
  }
7690
  elseif (isset($entity_info[$entity_type])) {
7691
    return $entity_info[$entity_type];
7692
  }
7693
}
7694

    
7695
/**
7696
 * Resets the cached information about entity types.
7697
 */
7698
function entity_info_cache_clear() {
7699
  drupal_static_reset('entity_get_info');
7700
  // Clear all languages.
7701
  cache_clear_all('entity_info:', 'cache', TRUE);
7702
}
7703

    
7704
/**
7705
 * Helper function to extract id, vid, and bundle name from an entity.
7706
 *
7707
 * @param $entity_type
7708
 *   The entity type; e.g. 'node' or 'user'.
7709
 * @param $entity
7710
 *   The entity from which to extract values.
7711
 *
7712
 * @return
7713
 *   A numerically indexed array (not a hash table) containing these
7714
 *   elements:
7715
 *   - 0: Primary ID of the entity.
7716
 *   - 1: Revision ID of the entity, or NULL if $entity_type is not versioned.
7717
 *   - 2: Bundle name of the entity, or NULL if $entity_type has no bundles.
7718
 */
7719
function entity_extract_ids($entity_type, $entity) {
7720
  $info = entity_get_info($entity_type);
7721

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

    
7726
  if (!empty($info['entity keys']['bundle'])) {
7727
    // Explicitly fail for malformed entities missing the bundle property.
7728
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
7729
      throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
7730
    }
7731
    $bundle = $entity->{$info['entity keys']['bundle']};
7732
  }
7733
  else {
7734
    // The entity type provides no bundle key: assume a single bundle, named
7735
    // after the entity type.
7736
    $bundle = $entity_type;
7737
  }
7738

    
7739
  return array($id, $vid, $bundle);
7740
}
7741

    
7742
/**
7743
 * Helper function to assemble an object structure with initial ids.
7744
 *
7745
 * This function can be seen as reciprocal to entity_extract_ids().
7746
 *
7747
 * @param $entity_type
7748
 *   The entity type; e.g. 'node' or 'user'.
7749
 * @param $ids
7750
 *   A numerically indexed array, as returned by entity_extract_ids().
7751
 *
7752
 * @return
7753
 *   An entity structure, initialized with the ids provided.
7754
 *
7755
 * @see entity_extract_ids()
7756
 */
7757
function entity_create_stub_entity($entity_type, $ids) {
7758
  $entity = new stdClass();
7759
  $info = entity_get_info($entity_type);
7760
  $entity->{$info['entity keys']['id']} = $ids[0];
7761
  if (!empty($info['entity keys']['revision']) && isset($ids[1])) {
7762
    $entity->{$info['entity keys']['revision']} = $ids[1];
7763
  }
7764
  if (!empty($info['entity keys']['bundle']) && isset($ids[2])) {
7765
    $entity->{$info['entity keys']['bundle']} = $ids[2];
7766
  }
7767
  return $entity;
7768
}
7769

    
7770
/**
7771
 * Load entities from the database.
7772
 *
7773
 * The entities are stored in a static memory cache, and will not require
7774
 * database access if loaded again during the same page request.
7775
 *
7776
 * The actual loading is done through a class that has to implement the
7777
 * DrupalEntityControllerInterface interface. By default,
7778
 * DrupalDefaultEntityController is used. Entity types can specify that a
7779
 * different class should be used by setting the 'controller class' key in
7780
 * hook_entity_info(). These classes can either implement the
7781
 * DrupalEntityControllerInterface interface, or, most commonly, extend the
7782
 * DrupalDefaultEntityController class. See node_entity_info() and the
7783
 * NodeController in node.module as an example.
7784
 *
7785
 * @param $entity_type
7786
 *   The entity type to load, e.g. node or user.
7787
 * @param $ids
7788
 *   An array of entity IDs, or FALSE to load all entities.
7789
 * @param $conditions
7790
 *   (deprecated) An associative array of conditions on the base table, where
7791
 *   the keys are the database fields and the values are the values those
7792
 *   fields must have. Instead, it is preferable to use EntityFieldQuery to
7793
 *   retrieve a list of entity IDs loadable by this function.
7794
 * @param $reset
7795
 *   Whether to reset the internal cache for the requested entity type.
7796
 *
7797
 * @return
7798
 *   An array of entity objects indexed by their ids. When no results are
7799
 *   found, an empty array is returned.
7800
 *
7801
 * @todo Remove $conditions in Drupal 8.
7802
 *
7803
 * @see hook_entity_info()
7804
 * @see DrupalEntityControllerInterface
7805
 * @see DrupalDefaultEntityController
7806
 * @see EntityFieldQuery
7807
 */
7808
function entity_load($entity_type, $ids = FALSE, $conditions = array(), $reset = FALSE) {
7809
  if ($reset) {
7810
    entity_get_controller($entity_type)->resetCache();
7811
  }
7812
  return entity_get_controller($entity_type)->load($ids, $conditions);
7813
}
7814

    
7815
/**
7816
 * Loads the unchanged, i.e. not modified, entity from the database.
7817
 *
7818
 * Unlike entity_load() this function ensures the entity is directly loaded from
7819
 * the database, thus bypassing any static cache. In particular, this function
7820
 * is useful to determine changes by comparing the entity being saved to the
7821
 * stored entity.
7822
 *
7823
 * @param $entity_type
7824
 *   The entity type to load, e.g. node or user.
7825
 * @param $id
7826
 *   The ID of the entity to load.
7827
 *
7828
 * @return
7829
 *   The unchanged entity, or FALSE if the entity cannot be loaded.
7830
 */
7831
function entity_load_unchanged($entity_type, $id) {
7832
  entity_get_controller($entity_type)->resetCache(array($id));
7833
  $result = entity_get_controller($entity_type)->load(array($id));
7834
  return reset($result);
7835
}
7836

    
7837
/**
7838
 * Gets the entity controller for an entity type.
7839
 *
7840
 * @return DrupalEntityControllerInterface
7841
 *   The entity controller object for the specified entity type.
7842
 */
7843
function entity_get_controller($entity_type) {
7844
  $controllers = &drupal_static(__FUNCTION__, array());
7845
  if (!isset($controllers[$entity_type])) {
7846
    $type_info = entity_get_info($entity_type);
7847
    $class = $type_info['controller class'];
7848
    $controllers[$entity_type] = new $class($entity_type);
7849
  }
7850
  return $controllers[$entity_type];
7851
}
7852

    
7853
/**
7854
 * Invoke hook_entity_prepare_view().
7855
 *
7856
 * If adding a new entity similar to nodes, comments or users, you should
7857
 * invoke this function during the ENTITY_build_content() or
7858
 * ENTITY_view_multiple() phases of rendering to allow other modules to alter
7859
 * the objects during this phase. This is needed for situations where
7860
 * information needs to be loaded outside of ENTITY_load() - particularly
7861
 * when loading entities into one another - i.e. a user object into a node, due
7862
 * to the potential for unwanted side-effects such as caching and infinite
7863
 * recursion. By convention, entity_prepare_view() is called after
7864
 * field_attach_prepare_view() to allow entity level hooks to act on content
7865
 * loaded by field API.
7866
 *
7867
 * @param $entity_type
7868
 *   The type of entity, i.e. 'node', 'user'.
7869
 * @param $entities
7870
 *   The entity objects which are being prepared for view, keyed by object ID.
7871
 * @param $langcode
7872
 *   (optional) A language code to be used for rendering. Defaults to the global
7873
 *   content language of the current request.
7874
 *
7875
 * @see hook_entity_prepare_view()
7876
 */
7877
function entity_prepare_view($entity_type, $entities, $langcode = NULL) {
7878
  if (!isset($langcode)) {
7879
    $langcode = $GLOBALS['language_content']->language;
7880
  }
7881

    
7882
  // To ensure hooks are only run once per entity, check for an
7883
  // entity_view_prepared flag and only process items without it.
7884
  // @todo: resolve this more generally for both entity and field level hooks.
7885
  $prepare = array();
7886
  foreach ($entities as $id => $entity) {
7887
    if (empty($entity->entity_view_prepared)) {
7888
      // Add this entity to the items to be prepared.
7889
      $prepare[$id] = $entity;
7890

    
7891
      // Mark this item as prepared.
7892
      $entity->entity_view_prepared = TRUE;
7893
    }
7894
  }
7895

    
7896
  if (!empty($prepare)) {
7897
    module_invoke_all('entity_prepare_view', $prepare, $entity_type, $langcode);
7898
  }
7899
}
7900

    
7901
/**
7902
 * Returns the URI elements of an entity.
7903
 *
7904
 * @param $entity_type
7905
 *   The entity type; e.g. 'node' or 'user'.
7906
 * @param $entity
7907
 *   The entity for which to generate a path.
7908
 * @return
7909
 *   An array containing the 'path' and 'options' keys used to build the URI of
7910
 *   the entity, and matching the signature of url(). NULL if the entity has no
7911
 *   URI of its own.
7912
 */
7913
function entity_uri($entity_type, $entity) {
7914
  $info = entity_get_info($entity_type);
7915
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
7916

    
7917
  // A bundle-specific callback takes precedence over the generic one for the
7918
  // entity type.
7919
  if (isset($info['bundles'][$bundle]['uri callback'])) {
7920
    $uri_callback = $info['bundles'][$bundle]['uri callback'];
7921
  }
7922
  elseif (isset($info['uri callback'])) {
7923
    $uri_callback = $info['uri callback'];
7924
  }
7925
  else {
7926
    return NULL;
7927
  }
7928

    
7929
  // Invoke the callback to get the URI. If there is no callback, return NULL.
7930
  if (isset($uri_callback) && function_exists($uri_callback)) {
7931
    $uri = $uri_callback($entity);
7932
    // Pass the entity data to url() so that alter functions do not need to
7933
    // lookup this entity again.
7934
    $uri['options']['entity_type'] = $entity_type;
7935
    $uri['options']['entity'] = $entity;
7936
    return $uri;
7937
  }
7938
}
7939

    
7940
/**
7941
 * Returns the label of an entity.
7942
 *
7943
 * See the 'label callback' component of the hook_entity_info() return value
7944
 * for more information.
7945
 *
7946
 * @param $entity_type
7947
 *   The entity type; e.g., 'node' or 'user'.
7948
 * @param $entity
7949
 *   The entity for which to generate the label.
7950
 *
7951
 * @return
7952
 *   The entity label, or FALSE if not found.
7953
 */
7954
function entity_label($entity_type, $entity) {
7955
  $label = FALSE;
7956
  $info = entity_get_info($entity_type);
7957
  if (isset($info['label callback']) && function_exists($info['label callback'])) {
7958
    $label = $info['label callback']($entity, $entity_type);
7959
  }
7960
  elseif (!empty($info['entity keys']['label']) && isset($entity->{$info['entity keys']['label']})) {
7961
    $label = $entity->{$info['entity keys']['label']};
7962
  }
7963

    
7964
  return $label;
7965
}
7966

    
7967
/**
7968
 * Returns the language of an entity.
7969
 *
7970
 * @param $entity_type
7971
 *   The entity type; e.g., 'node' or 'user'.
7972
 * @param $entity
7973
 *   The entity for which to get the language.
7974
 *
7975
 * @return
7976
 *   A valid language code or NULL if the entity has no language support.
7977
 */
7978
function entity_language($entity_type, $entity) {
7979
  $info = entity_get_info($entity_type);
7980

    
7981
  // Invoke the callback to get the language. If there is no callback, try to
7982
  // get it from a property of the entity, otherwise NULL.
7983
  if (isset($info['language callback']) && function_exists($info['language callback'])) {
7984
    $langcode = $info['language callback']($entity_type, $entity);
7985
  }
7986
  elseif (!empty($info['entity keys']['language']) && isset($entity->{$info['entity keys']['language']})) {
7987
    $langcode = $entity->{$info['entity keys']['language']};
7988
  }
7989
  else {
7990
    // The value returned in D8 would be LANGUAGE_NONE, we cannot use it here to
7991
    // preserve backward compatibility. In fact this function has been
7992
    // introduced very late in the D7 life cycle, mainly as the proper default
7993
    // for field_attach_form(). By returning LANGUAGE_NONE when no language
7994
    // information is available, we would introduce a potentially BC-breaking
7995
    // API change, since field_attach_form() defaults to the default language
7996
    // instead of LANGUAGE_NONE. Moreover this allows us to distinguish between
7997
    // entities that have no language specified from ones that do not have
7998
    // language support at all.
7999
    $langcode = NULL;
8000
  }
8001

    
8002
  return $langcode;
8003
}
8004

    
8005
/**
8006
 * Attaches field API validation to entity forms.
8007
 */
8008
function entity_form_field_validate($entity_type, $form, &$form_state) {
8009
  // All field attach API functions act on an entity object, but during form
8010
  // validation, we don't have one. $form_state contains the entity as it was
8011
  // prior to processing the current form submission, and we must not update it
8012
  // until we have fully validated the submitted input. Therefore, for
8013
  // validation, act on a pseudo entity created out of the form values.
8014
  $pseudo_entity = (object) $form_state['values'];
8015
  field_attach_form_validate($entity_type, $pseudo_entity, $form, $form_state);
8016
}
8017

    
8018
/**
8019
 * Copies submitted values to entity properties for simple entity forms.
8020
 *
8021
 * During the submission handling of an entity form's "Save", "Preview", and
8022
 * possibly other buttons, the form state's entity needs to be updated with the
8023
 * submitted form values. Each entity form implements its own builder function
8024
 * for doing this, appropriate for the particular entity and form, whereas
8025
 * modules may specify additional builder functions in $form['#entity_builders']
8026
 * for copying the form values of added form elements to entity properties.
8027
 * Many of the main entity builder functions can call this helper function to
8028
 * re-use its logic of copying $form_state['values'][PROPERTY] values to
8029
 * $entity->PROPERTY for all entries in $form_state['values'] that are not field
8030
 * data, and calling field_attach_submit() to copy field data. Apart from that
8031
 * this helper invokes any additional builder functions that have been specified
8032
 * in $form['#entity_builders'].
8033
 *
8034
 * For some entity forms (e.g., forms with complex non-field data and forms that
8035
 * simultaneously edit multiple entities), this behavior may be inappropriate,
8036
 * so the builder function for such forms needs to implement the required
8037
 * functionality instead of calling this function.
8038
 */
8039
function entity_form_submit_build_entity($entity_type, $entity, $form, &$form_state) {
8040
  $info = entity_get_info($entity_type);
8041
  list(, , $bundle) = entity_extract_ids($entity_type, $entity);
8042

    
8043
  // Copy top-level form values that are not for fields to entity properties,
8044
  // without changing existing entity properties that are not being edited by
8045
  // this form. Copying field values must be done using field_attach_submit().
8046
  $values_excluding_fields = $info['fieldable'] ? array_diff_key($form_state['values'], field_info_instances($entity_type, $bundle)) : $form_state['values'];
8047
  foreach ($values_excluding_fields as $key => $value) {
8048
    $entity->$key = $value;
8049
  }
8050

    
8051
  // Invoke all specified builders for copying form values to entity properties.
8052
  if (isset($form['#entity_builders'])) {
8053
    foreach ($form['#entity_builders'] as $function) {
8054
      $function($entity_type, $entity, $form, $form_state);
8055
    }
8056
  }
8057

    
8058
  // Copy field values to the entity.
8059
  if ($info['fieldable']) {
8060
    field_attach_submit($entity_type, $entity, $form, $form_state);
8061
  }
8062
}
8063

    
8064
/**
8065
 * Performs one or more XML-RPC request(s).
8066
 *
8067
 * Usage example:
8068
 * @code
8069
 * $result = xmlrpc('http://example.com/xmlrpc.php', array(
8070
 *   'service.methodName' => array($parameter, $second, $third),
8071
 * ));
8072
 * @endcode
8073
 *
8074
 * @param $url
8075
 *   An absolute URL of the XML-RPC endpoint.
8076
 * @param $args
8077
 *   An associative array whose keys are the methods to call and whose values
8078
 *   are the arguments to pass to the respective method. If multiple methods
8079
 *   are specified, a system.multicall is performed.
8080
 * @param $options
8081
 *   (optional) An array of options to pass along to drupal_http_request().
8082
 *
8083
 * @return
8084
 *   For one request:
8085
 *     Either the return value of the method on success, or FALSE.
8086
 *     If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
8087
 *   For multiple requests:
8088
 *     An array of results. Each result will either be the result
8089
 *     returned by the method called, or an xmlrpc_error object if the call
8090
 *     failed. See xmlrpc_error().
8091
 */
8092
function xmlrpc($url, $args, $options = array()) {
8093
  require_once DRUPAL_ROOT . '/includes/xmlrpc.inc';
8094
  return _xmlrpc($url, $args, $options);
8095
}
8096

    
8097
/**
8098
 * Retrieves a list of all available archivers.
8099
 *
8100
 * @see hook_archiver_info()
8101
 * @see hook_archiver_info_alter()
8102
 */
8103
function archiver_get_info() {
8104
  $archiver_info = &drupal_static(__FUNCTION__, array());
8105

    
8106
  if (empty($archiver_info)) {
8107
    $cache = cache_get('archiver_info');
8108
    if ($cache === FALSE) {
8109
      // Rebuild the cache and save it.
8110
      $archiver_info = module_invoke_all('archiver_info');
8111
      drupal_alter('archiver_info', $archiver_info);
8112
      uasort($archiver_info, 'drupal_sort_weight');
8113
      cache_set('archiver_info', $archiver_info);
8114
    }
8115
    else {
8116
      $archiver_info = $cache->data;
8117
    }
8118
  }
8119

    
8120
  return $archiver_info;
8121
}
8122

    
8123
/**
8124
 * Returns a string of supported archive extensions.
8125
 *
8126
 * @return
8127
 *   A space-separated string of extensions suitable for use by the file
8128
 *   validation system.
8129
 */
8130
function archiver_get_extensions() {
8131
  $valid_extensions = array();
8132
  foreach (archiver_get_info() as $archive) {
8133
    foreach ($archive['extensions'] as $extension) {
8134
      foreach (explode('.', $extension) as $part) {
8135
        if (!in_array($part, $valid_extensions)) {
8136
          $valid_extensions[] = $part;
8137
        }
8138
      }
8139
    }
8140
  }
8141
  return implode(' ', $valid_extensions);
8142
}
8143

    
8144
/**
8145
 * Creates the appropriate archiver for the specified file.
8146
 *
8147
 * @param $file
8148
 *   The full path of the archive file. Note that stream wrapper paths are
8149
 *   supported, but not remote ones.
8150
 *
8151
 * @return
8152
 *   A newly created instance of the archiver class appropriate
8153
 *   for the specified file, already bound to that file.
8154
 *   If no appropriate archiver class was found, will return FALSE.
8155
 */
8156
function archiver_get_archiver($file) {
8157
  // Archivers can only work on local paths
8158
  $filepath = drupal_realpath($file);
8159
  if (!is_file($filepath)) {
8160
    throw new Exception(t('Archivers can only operate on local files: %file not supported', array('%file' => $file)));
8161
  }
8162
  $archiver_info = archiver_get_info();
8163

    
8164
  foreach ($archiver_info as $implementation) {
8165
    foreach ($implementation['extensions'] as $extension) {
8166
      // Because extensions may be multi-part, such as .tar.gz,
8167
      // we cannot use simpler approaches like substr() or pathinfo().
8168
      // This method isn't quite as clean but gets the job done.
8169
      // Also note that the file may not yet exist, so we cannot rely
8170
      // on fileinfo() or other disk-level utilities.
8171
      if (strrpos($filepath, '.' . $extension) === strlen($filepath) - strlen('.' . $extension)) {
8172
        return new $implementation['class']($filepath);
8173
      }
8174
    }
8175
  }
8176
}
8177

    
8178
/**
8179
 * Assembles the Drupal Updater registry.
8180
 *
8181
 * An Updater is a class that knows how to update various parts of the Drupal
8182
 * file system, for example to update modules that have newer releases, or to
8183
 * install a new theme.
8184
 *
8185
 * @return
8186
 *   The Drupal Updater class registry.
8187
 *
8188
 * @see hook_updater_info()
8189
 * @see hook_updater_info_alter()
8190
 */
8191
function drupal_get_updaters() {
8192
  $updaters = &drupal_static(__FUNCTION__);
8193
  if (!isset($updaters)) {
8194
    $updaters = module_invoke_all('updater_info');
8195
    drupal_alter('updater_info', $updaters);
8196
    uasort($updaters, 'drupal_sort_weight');
8197
  }
8198
  return $updaters;
8199
}
8200

    
8201
/**
8202
 * Assembles the Drupal FileTransfer registry.
8203
 *
8204
 * @return
8205
 *   The Drupal FileTransfer class registry.
8206
 *
8207
 * @see FileTransfer
8208
 * @see hook_filetransfer_info()
8209
 * @see hook_filetransfer_info_alter()
8210
 */
8211
function drupal_get_filetransfer_info() {
8212
  $info = &drupal_static(__FUNCTION__);
8213
  if (!isset($info)) {
8214
    // Since we have to manually set the 'file path' default for each
8215
    // module separately, we can't use module_invoke_all().
8216
    $info = array();
8217
    foreach (module_implements('filetransfer_info') as $module) {
8218
      $function = $module . '_filetransfer_info';
8219
      if (function_exists($function)) {
8220
        $result = $function();
8221
        if (isset($result) && is_array($result)) {
8222
          foreach ($result as &$values) {
8223
            if (empty($values['file path'])) {
8224
              $values['file path'] = drupal_get_path('module', $module);
8225
            }
8226
          }
8227
          $info = array_merge_recursive($info, $result);
8228
        }
8229
      }
8230
    }
8231
    drupal_alter('filetransfer_info', $info);
8232
    uasort($info, 'drupal_sort_weight');
8233
  }
8234
  return $info;
8235
}