Projet

Général

Profil

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

root / htmltest / includes / common.inc @ a5572547

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);
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 system URL string into an associative array suitable for url().
548
 *
549
 * This function should only be used for URLs that have been generated by the
550
 * system, such as via url(). It should not be used for URLs that come from
551
 * external sources, or URLs that link to external resources.
552
 *
553
 * The returned array contains a 'path' that may be passed separately to url().
554
 * For example:
555
 * @code
556
 *   $options = drupal_parse_url($_GET['destination']);
557
 *   $my_url = url($options['path'], $options);
558
 *   $my_link = l('Example link', $options['path'], $options);
559
 * @endcode
560
 *
561
 * This is required, because url() does not support relative URLs containing a
562
 * query string or fragment in its $path argument. Instead, any query string
563
 * needs to be parsed into an associative query parameter array in
564
 * $options['query'] and the fragment into $options['fragment'].
565
 *
566
 * @param $url
567
 *   The URL string to parse, f.e. $_GET['destination'].
568
 *
569
 * @return
570
 *   An associative array containing the keys:
571
 *   - 'path': The path of the URL. If the given $url is external, this includes
572
 *     the scheme and host.
573
 *   - 'query': An array of query parameters of $url, if existent.
574
 *   - 'fragment': The fragment of $url, if existent.
575
 *
576
 * @see url()
577
 * @see drupal_goto()
578
 * @ingroup php_wrappers
579
 */
580
function drupal_parse_url($url) {
581
  $options = array(
582
    'path' => NULL,
583
    'query' => array(),
584
    'fragment' => '',
585
  );
586

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

    
625
  return $options;
626
}
627

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

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

    
696
  drupal_alter('drupal_goto', $path, $options, $http_response_code);
697

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

    
701
  $url = url($path, $options);
702

    
703
  header('Location: ' . $url, TRUE, $http_response_code);
704

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

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

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

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

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

    
795
  $result = new stdClass();
796

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

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

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

    
812
  timer_start(__FUNCTION__);
813

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

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

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

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

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

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

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

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

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

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

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

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

    
912
    return $result;
913
  }
914

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

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

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

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

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

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

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

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

    
992
  // Parse the response status line.
993
  list($protocol, $code, $status_message) = explode(' ', trim(array_shift($response)), 3);
994
  $result->protocol = $protocol;
995
  $result->status_message = $status_message;
996

    
997
  $result->headers = array();
998

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

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

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

    
1089
  return $result;
1090
}
1091

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

    
1103
/**
1104
 * @} End of "HTTP handling".
1105
 */
1106

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

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

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

    
1168
/**
1169
 * @defgroup validation Input validation
1170
 * @{
1171
 * Functions to validate user input.
1172
 */
1173

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

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

    
1228
/**
1229
 * @} End of "defgroup validation".
1230
 */
1231

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

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

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

    
1310
/**
1311
 * @defgroup sanitization Sanitization functions
1312
 * @{
1313
 * Functions to sanitize values.
1314
 *
1315
 * See http://drupal.org/writing-secure-code for information
1316
 * on writing secure code.
1317
 */
1318

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

    
1343
  if (!isset($allowed_protocols)) {
1344
    $allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal')));
1345
  }
1346

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

    
1368
  return $uri;
1369
}
1370

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

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

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

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

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

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

    
1483
  if ($store) {
1484
    $allowed_html = array_flip($m);
1485
    return;
1486
  }
1487

    
1488
  $string = $m[1];
1489

    
1490
  if (substr($string, 0, 1) != '<') {
1491
    // We matched a lone ">" character.
1492
    return '&gt;';
1493
  }
1494
  elseif (strlen($string) == 1) {
1495
    // We matched a lone "<" character.
1496
    return '&lt;';
1497
  }
1498

    
1499
  if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
1500
    // Seriously malformed.
1501
    return '';
1502
  }
1503

    
1504
  $slash = trim($matches[1]);
1505
  $elem = &$matches[2];
1506
  $attrlist = &$matches[3];
1507
  $comment = &$matches[4];
1508

    
1509
  if ($comment) {
1510
    $elem = '!--';
1511
  }
1512

    
1513
  if (!isset($allowed_html[strtolower($elem)])) {
1514
    // Disallowed HTML element.
1515
    return '';
1516
  }
1517

    
1518
  if ($comment) {
1519
    return $comment;
1520
  }
1521

    
1522
  if ($slash != '') {
1523
    return "</$elem>";
1524
  }
1525

    
1526
  // Is there a closing XHTML slash at the end of the attributes?
1527
  $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
1528
  $xhtml_slash = $count ? ' /' : '';
1529

    
1530
  // Clean up attributes.
1531
  $attr2 = implode(' ', _filter_xss_attributes($attrlist));
1532
  $attr2 = preg_replace('/[<>]/', '', $attr2);
1533
  $attr2 = strlen($attr2) ? ' ' . $attr2 : '';
1534

    
1535
  return "<$elem$attr2$xhtml_slash>";
1536
}
1537

    
1538
/**
1539
 * Processes a string of HTML attributes.
1540
 *
1541
 * @return
1542
 *   Cleaned up version of the HTML attributes.
1543
 */
1544
function _filter_xss_attributes($attr) {
1545
  $attrarr = array();
1546
  $mode = 0;
1547
  $attrname = '';
1548

    
1549
  while (strlen($attr) != 0) {
1550
    // Was the last operation successful?
1551
    $working = 0;
1552

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

    
1564
      case 1:
1565
        // Equals sign or valueless ("selected").
1566
        if (preg_match('/^\s*=\s*/', $attr)) {
1567
          $working = 1; $mode = 2;
1568
          $attr = preg_replace('/^\s*=\s*/', '', $attr);
1569
          break;
1570
        }
1571

    
1572
        if (preg_match('/^\s+/', $attr)) {
1573
          $working = 1; $mode = 0;
1574
          if (!$skip) {
1575
            $attrarr[] = $attrname;
1576
          }
1577
          $attr = preg_replace('/^\s+/', '', $attr);
1578
        }
1579
        break;
1580

    
1581
      case 2:
1582
        // Attribute value, a URL after href= for instance.
1583
        if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
1584
          $thisval = filter_xss_bad_protocol($match[1]);
1585

    
1586
          if (!$skip) {
1587
            $attrarr[] = "$attrname=\"$thisval\"";
1588
          }
1589
          $working = 1;
1590
          $mode = 0;
1591
          $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
1592
          break;
1593
        }
1594

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

    
1598
          if (!$skip) {
1599
            $attrarr[] = "$attrname='$thisval'";
1600
          }
1601
          $working = 1; $mode = 0;
1602
          $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
1603
          break;
1604
        }
1605

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

    
1609
          if (!$skip) {
1610
            $attrarr[] = "$attrname=\"$thisval\"";
1611
          }
1612
          $working = 1; $mode = 0;
1613
          $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
1614
        }
1615
        break;
1616
    }
1617

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

    
1635
  // The attribute list ends with a valueless attribute like "selected".
1636
  if ($mode == 1 && !$skip) {
1637
    $attrarr[] = $attrname;
1638
  }
1639
  return $attrarr;
1640
}
1641

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

    
1665
    $string = decode_entities($string);
1666
  }
1667
  return check_plain(drupal_strip_dangerous_protocols($string));
1668
}
1669

    
1670
/**
1671
 * @} End of "defgroup sanitization".
1672
 */
1673

    
1674
/**
1675
 * @defgroup format Formatting
1676
 * @{
1677
 * Functions to format numbers, strings, dates, etc.
1678
 */
1679

    
1680
/**
1681
 * Formats an RSS channel.
1682
 *
1683
 * Arbitrary elements may be added using the $args associative array.
1684
 */
1685
function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
1686
  global $language_content;
1687
  $langcode = $langcode ? $langcode : $language_content->language;
1688

    
1689
  $output = "<channel>\n";
1690
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1691
  $output .= ' <link>' . check_url($link) . "</link>\n";
1692

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

    
1702
  return $output;
1703
}
1704

    
1705
/**
1706
 * Formats a single RSS item.
1707
 *
1708
 * Arbitrary elements may be added using the $args associative array.
1709
 */
1710
function format_rss_item($title, $link, $description, $args = array()) {
1711
  $output = "<item>\n";
1712
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1713
  $output .= ' <link>' . check_url($link) . "</link>\n";
1714
  $output .= ' <description>' . check_plain($description) . "</description>\n";
1715
  $output .= format_xml_elements($args);
1716
  $output .= "</item>\n";
1717

    
1718
  return $output;
1719
}
1720

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

    
1745
        if (isset($value['value']) && $value['value'] != '') {
1746
          $output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) . '</' . $value['key'] . ">\n";
1747
        }
1748
        else {
1749
          $output .= " />\n";
1750
        }
1751
      }
1752
    }
1753
    else {
1754
      $output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</$key>\n";
1755
    }
1756
  }
1757
  return $output;
1758
}
1759

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

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

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

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

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

    
1927
    if ($granularity == 0) {
1928
      break;
1929
    }
1930
  }
1931
  return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
1932
}
1933

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

    
1970
  if (!isset($timezone)) {
1971
    $timezone = date_default_timezone_get();
1972
  }
1973
  // Store DateTimeZone objects in an array rather than repeatedly
1974
  // constructing identical objects over the life of a request.
1975
  if (!isset($timezones[$timezone])) {
1976
    $timezones[$timezone] = timezone_open($timezone);
1977
  }
1978

    
1979
  // Use the default langcode if none is set.
1980
  global $language;
1981
  if (empty($langcode)) {
1982
    $langcode = isset($language->language) ? $language->language : 'en';
1983
  }
1984

    
1985
  switch ($type) {
1986
    case 'short':
1987
      $format = variable_get('date_format_short', 'm/d/Y - H:i');
1988
      break;
1989

    
1990
    case 'long':
1991
      $format = variable_get('date_format_long', 'l, F j, Y - H:i');
1992
      break;
1993

    
1994
    case 'custom':
1995
      // No change to format.
1996
      break;
1997

    
1998
    case 'medium':
1999
    default:
2000
      // Retrieve the format of the custom $type passed.
2001
      if ($type != 'medium') {
2002
        $format = variable_get('date_format_' . $type, '');
2003
      }
2004
      // Fall back to 'medium'.
2005
      if ($format === '') {
2006
        $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
2007
      }
2008
      break;
2009
  }
2010

    
2011
  // Create a DateTime object from the timestamp.
2012
  $date_time = date_create('@' . $timestamp);
2013
  // Set the time zone for the DateTime object.
2014
  date_timezone_set($date_time, $timezones[$timezone]);
2015

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

    
2023
  // Call date_format().
2024
  $format = date_format($date_time, $format);
2025

    
2026
  // Pass the langcode to _format_date_callback().
2027
  _format_date_callback(NULL, $langcode);
2028

    
2029
  // Translate the marked sequences.
2030
  return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);
2031
}
2032

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

    
2050
/**
2051
 * Translates a formatted date string.
2052
 *
2053
 * Callback for preg_replace_callback() within format_date().
2054
 */
2055
function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
2056
  // We cache translations to avoid redundant and rather costly calls to t().
2057
  static $cache, $langcode;
2058

    
2059
  if (!isset($matches)) {
2060
    $langcode = $new_langcode;
2061
    return;
2062
  }
2063

    
2064
  $code = $matches[1];
2065
  $string = $matches[2];
2066

    
2067
  if (!isset($cache[$langcode][$code][$string])) {
2068
    $options = array(
2069
      'langcode' => $langcode,
2070
    );
2071

    
2072
    if ($code == 'F') {
2073
      $options['context'] = 'Long month name';
2074
    }
2075

    
2076
    if ($code == '') {
2077
      $cache[$langcode][$code][$string] = $string;
2078
    }
2079
    else {
2080
      $cache[$langcode][$code][$string] = t($string, array(), $options);
2081
    }
2082
  }
2083
  return $cache[$langcode][$code][$string];
2084
}
2085

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

    
2112
/**
2113
 * @} End of "defgroup format".
2114
 */
2115

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

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

    
2201
  // Preserve the original path before altering or aliasing.
2202
  $original_path = $path;
2203

    
2204
  // Allow other modules to alter the outbound URL and options.
2205
  drupal_alter('url_outbound', $path, $options, $original_path);
2206

    
2207
  if (isset($options['fragment']) && $options['fragment'] !== '') {
2208
    $options['fragment'] = '#' . $options['fragment'];
2209
  }
2210

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

    
2236
  global $base_url, $base_secure_url, $base_insecure_url;
2237

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

    
2255
  // The special path '<front>' links to the default front page.
2256
  if ($path == '<front>') {
2257
    $path = '';
2258
  }
2259
  elseif (!empty($path) && !$options['alias']) {
2260
    $language = isset($options['language']) && isset($options['language']->language) ? $options['language']->language : '';
2261
    $alias = drupal_get_path_alias($original_path, $language);
2262
    if ($alias != $original_path) {
2263
      $path = $alias;
2264
    }
2265
  }
2266

    
2267
  $base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
2268
  $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
2269

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

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

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

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

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

    
2436
  // Merge in defaults.
2437
  $options += array(
2438
    'attributes' => array(),
2439
    'html' => FALSE,
2440
  );
2441

    
2442
  // Append active class.
2443
  if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
2444
      (empty($options['language']) || $options['language']->language == $language_url->language)) {
2445
    $options['attributes']['class'][] = 'active';
2446
  }
2447

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

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

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

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

    
2594
  // Send appropriate HTTP-Header for browsers and search engines.
2595
  global $language;
2596
  drupal_add_http_header('Content-Language', $language->language);
2597

    
2598
  // Menu status constants are integers; page content is a string or array.
2599
  if (is_int($page_callback_result)) {
2600
    // @todo: Break these up into separate functions?
2601
    switch ($page_callback_result) {
2602
      case MENU_NOT_FOUND:
2603
        // Print a 404 page.
2604
        drupal_add_http_header('Status', '404 Not Found');
2605

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

    
2608
        // Check for and return a fast 404 page if configured.
2609
        drupal_fast_404();
2610

    
2611
        // Keep old path for reference, and to allow forms to redirect to it.
2612
        if (!isset($_GET['destination'])) {
2613
          $_GET['destination'] = $_GET['q'];
2614
        }
2615

    
2616
        $path = drupal_get_normal_path(variable_get('site_404', ''));
2617
        if ($path && $path != $_GET['q']) {
2618
          // Custom 404 handler. Set the active item in case there are tabs to
2619
          // display, or other dependencies on the path.
2620
          menu_set_active_item($path);
2621
          $return = menu_execute_active_handler($path, FALSE);
2622
        }
2623

    
2624
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2625
          // Standard 404 handler.
2626
          drupal_set_title(t('Page not found'));
2627
          $return = t('The requested page "@path" could not be found.', array('@path' => request_uri()));
2628
        }
2629

    
2630
        drupal_set_page_content($return);
2631
        $page = element_info('page');
2632
        print drupal_render_page($page);
2633
        break;
2634

    
2635
      case MENU_ACCESS_DENIED:
2636
        // Print a 403 page.
2637
        drupal_add_http_header('Status', '403 Forbidden');
2638
        watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
2639

    
2640
        // Keep old path for reference, and to allow forms to redirect to it.
2641
        if (!isset($_GET['destination'])) {
2642
          $_GET['destination'] = $_GET['q'];
2643
        }
2644

    
2645
        $path = drupal_get_normal_path(variable_get('site_403', ''));
2646
        if ($path && $path != $_GET['q']) {
2647
          // Custom 403 handler. Set the active item in case there are tabs to
2648
          // display or other dependencies on the path.
2649
          menu_set_active_item($path);
2650
          $return = menu_execute_active_handler($path, FALSE);
2651
        }
2652

    
2653
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2654
          // Standard 403 handler.
2655
          drupal_set_title(t('Access denied'));
2656
          $return = t('You are not authorized to access this page.');
2657
        }
2658

    
2659
        print drupal_render_page($return);
2660
        break;
2661

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

    
2678
  // Perform end-of-request tasks.
2679
  drupal_page_footer();
2680
}
2681

    
2682
/**
2683
 * Performs end-of-request tasks.
2684
 *
2685
 * This function sets the page cache if appropriate, and allows modules to
2686
 * react to the closing of the page by calling hook_exit().
2687
 */
2688
function drupal_page_footer() {
2689
  global $user;
2690

    
2691
  module_invoke_all('exit');
2692

    
2693
  // Commit the user session, if needed.
2694
  drupal_session_commit();
2695

    
2696
  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
2697
    drupal_serve_page_from_cache($cache);
2698
  }
2699
  else {
2700
    ob_flush();
2701
  }
2702

    
2703
  _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
2704
  drupal_cache_system_paths();
2705
  module_implements_write_cache();
2706
  system_run_automated_cron();
2707
}
2708

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

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

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

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

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

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

    
2841
  if ($header) {
2842
    // Also add a HTTP header "Link:".
2843
    $href = '<' . check_plain($attributes['href']) . '>;';
2844
    unset($attributes['href']);
2845
    $element['#attached']['drupal_add_http_header'][] = array('Link',  $href . drupal_http_header_attributes($attributes), TRUE);
2846
  }
2847

    
2848
  drupal_add_html_head($element, 'drupal_add_html_head_link:' . $attributes['rel'] . ':' . $href);
2849
}
2850

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

    
2970
  // Construct the options, taking the defaults into consideration.
2971
  if (isset($options)) {
2972
    if (!is_array($options)) {
2973
      $options = array('type' => $options);
2974
    }
2975
  }
2976
  else {
2977
    $options = array();
2978
  }
2979

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

    
2998
    // Files with a query string cannot be preprocessed.
2999
    if ($options['type'] === 'file' && $options['preprocess'] && strpos($options['data'], '?') !== FALSE) {
3000
      $options['preprocess'] = FALSE;
3001
    }
3002

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

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

    
3020
  return $css;
3021
}
3022

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

    
3057
  // Allow modules and themes to alter the CSS items.
3058
  if (!$skip_alter) {
3059
    drupal_alter('css', $css);
3060
  }
3061

    
3062
  // Sort CSS items, so that they appear in the correct order.
3063
  uasort($css, 'drupal_sort_css_js');
3064

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

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

    
3091
  // Render the HTML needed to load the CSS.
3092
  $styles = array(
3093
    '#type' => 'styles',
3094
    '#items' => $css,
3095
  );
3096

    
3097
  if (!empty($setting)) {
3098
    $styles['#attached']['js'][] = array('type' => 'setting', 'data' => $setting);
3099
  }
3100

    
3101
  return drupal_render($styles);
3102
}
3103

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

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

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

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

    
3249
    // Add the item to the current group.
3250
    $groups[$i]['items'][] = $item;
3251
  }
3252
  return $groups;
3253
}
3254

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

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

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

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

    
3374
  // For inline CSS to validate as XHTML, all CSS containing XHTML needs to be
3375
  // wrapped in CDATA. To make that backwards compatible with HTML 4, we need to
3376
  // comment out the CDATA-tag.
3377
  $embed_prefix = "\n<!--/*--><![CDATA[/*><!--*/\n";
3378
  $embed_suffix = "\n/*]]>*/-->\n";
3379

    
3380
  // Defaults for LINK and STYLE elements.
3381
  $link_element_defaults = array(
3382
    '#type' => 'html_tag',
3383
    '#tag' => 'link',
3384
    '#attributes' => array(
3385
      'type' => 'text/css',
3386
      'rel' => 'stylesheet',
3387
    ),
3388
  );
3389
  $style_element_defaults = array(
3390
    '#type' => 'html_tag',
3391
    '#tag' => 'style',
3392
    '#attributes' => array(
3393
      'type' => 'text/css',
3394
    ),
3395
  );
3396

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

    
3519
  return $elements;
3520
}
3521

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

    
3561
  if (empty($uri) || !file_exists($uri)) {
3562
    // Build aggregate CSS file.
3563
    foreach ($css as $stylesheet) {
3564
      // Only 'file' stylesheets can be aggregated.
3565
      if ($stylesheet['type'] == 'file') {
3566
        $contents = drupal_load_stylesheet($stylesheet['data'], TRUE);
3567

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

    
3578
        _drupal_build_css_path(NULL, $css_base_url . '/');
3579
        // Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
3580
        $data .= preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);
3581
      }
3582
    }
3583

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

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

    
3618
/**
3619
 * Prefixes all paths within a CSS file for drupal_build_css_cache().
3620
 */
3621
function _drupal_build_css_path($matches, $base = NULL) {
3622
  $_base = &drupal_static(__FUNCTION__);
3623
  // Store base path for preg_replace_callback.
3624
  if (isset($base)) {
3625
    $_base = $base;
3626
  }
3627

    
3628
  // Prefix with base and remove '../' segments where possible.
3629
  $path = $_base . $matches[1];
3630
  $last = '';
3631
  while ($path != $last) {
3632
    $last = $path;
3633
    $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
3634
  }
3635
  return 'url(' . $path . ')';
3636
}
3637

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

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

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

    
3690
  // Restore the parent base path as the file and its childen are processed.
3691
  $basepath = $parent_base_path;
3692
  return $content;
3693
}
3694

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

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

    
3751
  // Replaces @import commands with the actual stylesheet content.
3752
  // This happens recursively but omits external files.
3753
  $contents = preg_replace_callback('/@import\s*(?:url\(\s*)?[\'"]?(?![a-z]+:)([^\'"\()]+)[\'"]?\s*\)?\s*;/', '_drupal_load_stylesheet', $contents);
3754
  return $contents;
3755
}
3756

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

    
3768
  // Determine the file's directory.
3769
  $directory = dirname($filename);
3770
  // If the file is in the current directory, make sure '.' doesn't appear in
3771
  // the url() path.
3772
  $directory = $directory == '.' ? '' : $directory .'/';
3773

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

    
3780
/**
3781
 * Deletes old cached CSS files.
3782
 */
3783
function drupal_clear_css_cache() {
3784
  variable_del('drupal_css_cache_files');
3785
  file_scan_directory('public://css', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
3786
}
3787

    
3788
/**
3789
 * Callback to delete files modified more than a set time ago.
3790
 */
3791
function drupal_delete_file_if_stale($uri) {
3792
  // Default stale file threshold is 30 days.
3793
  if (REQUEST_TIME - filemtime($uri) > variable_get('drupal_stale_file_threshold', 2592000)) {
3794
    file_unmanaged_delete($uri);
3795
  }
3796
}
3797

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

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

    
3826
  return $identifier;
3827
}
3828

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

    
3846
  if (!isset($classes[$class])) {
3847
    $classes[$class] = drupal_clean_css_identifier(drupal_strtolower($class));
3848
  }
3849
  return $classes[$class];
3850
}
3851

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

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

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

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

    
3955
  return $id;
3956
}
3957

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

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

    
4131
  // Construct the options, taking the defaults into consideration.
4132
  if (isset($options)) {
4133
    if (!is_array($options)) {
4134
      $options = array('type' => $options);
4135
    }
4136
  }
4137
  else {
4138
    $options = array();
4139
  }
4140
  $options += drupal_js_defaults($data);
4141

    
4142
  // Preprocess can only be set if caching is enabled.
4143
  $options['preprocess'] = $options['cache'] ? $options['preprocess'] : FALSE;
4144

    
4145
  // Tweak the weight so that files of the same weight are included in the
4146
  // order of the calls to drupal_add_js().
4147
  $options['weight'] += count($javascript) / 1000;
4148

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

    
4186
    switch ($options['type']) {
4187
      case 'setting':
4188
        // All JavaScript settings are placed in the header of the page with
4189
        // the library weight so that inline scripts appear afterwards.
4190
        $javascript['settings']['data'][] = $data;
4191
        break;
4192

    
4193
      case 'inline':
4194
        $javascript[] = $options;
4195
        break;
4196

    
4197
      default: // 'file' and 'external'
4198
        // Local and external files must keep their name as the associative key
4199
        // so the same JavaScript file is not added twice.
4200
        $javascript[$options['data']] = $options;
4201
    }
4202
  }
4203
  return $javascript;
4204
}
4205

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

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

    
4271
  // Allow modules to alter the JavaScript.
4272
  if (!$skip_alter) {
4273
    drupal_alter('js', $javascript);
4274
  }
4275

    
4276
  // Filter out elements of the given scope.
4277
  $items = array();
4278
  foreach ($javascript as $key => $item) {
4279
    if ($item['scope'] == $scope) {
4280
      $items[$key] = $item;
4281
    }
4282
  }
4283

    
4284
  $output = '';
4285
  // The index counter is used to keep aggregated and non-aggregated files in
4286
  // order by weight.
4287
  $index = 1;
4288
  $processed = array();
4289
  $files = array();
4290
  $preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
4291

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

    
4300
  // For inline JavaScript to validate as XHTML, all JavaScript containing
4301
  // XHTML needs to be wrapped in CDATA. To make that backwards compatible
4302
  // with HTML 4, we need to comment out the CDATA-tag.
4303
  $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
4304
  $embed_suffix = "\n//--><!]]>\n";
4305

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

    
4310
  // Sort the JavaScript so that it appears in the correct order.
4311
  uasort($items, 'drupal_sort_css_js');
4312

    
4313
  // Provide the page with information about the individual JavaScript files
4314
  // used, information not otherwise available when aggregation is enabled.
4315
  $setting['ajaxPageState']['js'] = array_fill_keys(array_keys($items), 1);
4316
  unset($setting['ajaxPageState']['js']['settings']);
4317
  drupal_add_js($setting, 'setting');
4318

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

    
4329
  // Loop through the JavaScript to construct the rendered output.
4330
  $element = array(
4331
    '#tag' => 'script',
4332
    '#value' => '',
4333
    '#attributes' => array(
4334
      'type' => 'text/javascript',
4335
    ),
4336
  );
4337
  foreach ($items as $item) {
4338
    $query_string =  empty($item['version']) ? $default_query_string : $js_version_string . $item['version'];
4339

    
4340
    switch ($item['type']) {
4341
      case 'setting':
4342
        $js_element = $element;
4343
        $js_element['#value_prefix'] = $embed_prefix;
4344
        $js_element['#value'] = 'jQuery.extend(Drupal.settings, ' . drupal_json_encode(drupal_array_merge_deep_array($item['data'])) . ");";
4345
        $js_element['#value_suffix'] = $embed_suffix;
4346
        $output .= theme('html_tag', array('element' => $js_element));
4347
        break;
4348

    
4349
      case 'inline':
4350
        $js_element = $element;
4351
        if ($item['defer']) {
4352
          $js_element['#attributes']['defer'] = 'defer';
4353
        }
4354
        $js_element['#value_prefix'] = $embed_prefix;
4355
        $js_element['#value'] = $item['data'];
4356
        $js_element['#value_suffix'] = $embed_suffix;
4357
        $processed[$index++] = theme('html_tag', array('element' => $js_element));
4358
        break;
4359

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

    
4384
      case 'external':
4385
        $js_element = $element;
4386
        // Preprocessing for external JavaScript files is ignored.
4387
        if ($item['defer']) {
4388
          $js_element['#attributes']['defer'] = 'defer';
4389
        }
4390
        $js_element['#attributes']['src'] = $item['data'];
4391
        $processed[$index++] = theme('html_tag', array('element' => $js_element));
4392
        break;
4393
    }
4394
  }
4395

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

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

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

    
4480
  // Add the libraries first.
4481
  $success = TRUE;
4482
  foreach ($elements['#attached']['library'] as $library) {
4483
    if (drupal_add_library($library[0], $library[1], $every_page) === FALSE) {
4484
      $success = FALSE;
4485
      // Exit if the dependency is missing.
4486
      if ($dependency_check) {
4487
        return $success;
4488
      }
4489
    }
4490
  }
4491
  unset($elements['#attached']['library']);
4492

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

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

    
4534
  return $success;
4535
}
4536

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

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

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

    
4714
  return $added[$module][$name];
4715
}
4716

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

    
4751
  if (!isset($libraries[$module])) {
4752
    // Retrieve all libraries associated with the module.
4753
    $module_libraries = module_invoke($module, 'library');
4754
    if (empty($module_libraries)) {
4755
      $module_libraries = array();
4756
    }
4757
    // Allow modules to alter the module's registered libraries.
4758
    drupal_alter('library', $module_libraries, $module);
4759

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

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

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

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

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

    
4985
/**
4986
 * Deletes old cached JavaScript files and variables.
4987
 */
4988
function drupal_clear_js_cache() {
4989
  variable_del('javascript_parsed');
4990
  variable_del('drupal_js_cache_files');
4991
  file_scan_directory('public://js', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
4992
}
4993

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

    
5007
  if (!isset($php530)) {
5008
    $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
5009
  }
5010

    
5011
  if ($php530) {
5012
    // Encode <, >, ', &, and " using the json_encode() options parameter.
5013
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
5014
  }
5015

    
5016
  // json_encode() escapes <, >, ', &, and " using its options parameter, but
5017
  // does not support this parameter prior to PHP 5.3.0.  Use a helper instead.
5018
  include_once DRUPAL_ROOT . '/includes/json-encode.inc';
5019
  return drupal_json_encode_helper($var);
5020
}
5021

    
5022
/**
5023
 * Converts an HTML-safe JSON string into its PHP equivalent.
5024
 *
5025
 * @see drupal_json_encode()
5026
 * @ingroup php_wrappers
5027
 */
5028
function drupal_json_decode($var) {
5029
  return json_decode($var, TRUE);
5030
}
5031

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

    
5045
  if (isset($var)) {
5046
    echo drupal_json_encode($var);
5047
  }
5048
}
5049

    
5050
/**
5051
 * Ensures the private key variable used to generate tokens is set.
5052
 *
5053
 * @return
5054
 *   The private key.
5055
 */
5056
function drupal_get_private_key() {
5057
  if (!($key = variable_get('drupal_private_key', 0))) {
5058
    $key = drupal_random_key();
5059
    variable_set('drupal_private_key', $key);
5060
  }
5061
  return $key;
5062
}
5063

    
5064
/**
5065
 * Generates a token based on $value, the user session, and the private key.
5066
 *
5067
 * @param $value
5068
 *   An additional value to base the token on.
5069
 *
5070
 * @return string
5071
 *   A 43-character URL-safe token for validation, based on the user session ID,
5072
 *   the hash salt provided from drupal_get_hash_salt(), and the
5073
 *   'drupal_private_key' configuration variable.
5074
 *
5075
 * @see drupal_get_hash_salt()
5076
 */
5077
function drupal_get_token($value = '') {
5078
  return drupal_hmac_base64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());
5079
}
5080

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

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

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

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

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

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

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

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

    
5178
  if (drupal_page_is_cacheable()) {
5179

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5284
  foreach ($queues as $queue_name => $info) {
5285
    if (!empty($info['skip on cron'])) {
5286
      // Do not run if queue wants to skip.
5287
      continue;
5288
    }
5289
    $function = $info['worker callback'];
5290
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
5291
    $queue = DrupalQueue::get($queue_name);
5292
    while (time() < $end && ($item = $queue->claimItem())) {
5293
      $function($item->data);
5294
      $queue->deleteItem($item);
5295
    }
5296
  }
5297
  // Restore the user.
5298
  $GLOBALS['user'] = $original_user;
5299
  drupal_save_session($original_session_saving);
5300

    
5301
  return $return;
5302
}
5303

    
5304
/**
5305
 * Shutdown function: Performs cron cleanup.
5306
 *
5307
 * @see drupal_cron_run()
5308
 * @see drupal_register_shutdown_function()
5309
 */
5310
function drupal_cron_cleanup() {
5311
  // See if the semaphore is still locked.
5312
  if (variable_get('cron_semaphore', FALSE)) {
5313
    watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);
5314

    
5315
    // Release cron semaphore.
5316
    variable_del('cron_semaphore');
5317
  }
5318
}
5319

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

    
5371
  $searchdir = array($directory);
5372
  $files = array();
5373

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

    
5398
  // Always search sites/all/* as well as the global directories.
5399
  $searchdir[] = 'sites/all/' . $directory;
5400

    
5401
  if (file_exists("$config/$directory")) {
5402
    $searchdir[] = "$config/$directory";
5403
  }
5404

    
5405
  // Get current list of items.
5406
  if (!function_exists('file_scan_directory')) {
5407
    require_once DRUPAL_ROOT . '/includes/file.inc';
5408
  }
5409
  foreach ($searchdir as $dir) {
5410
    $files_to_add = file_scan_directory($dir, $mask, array('key' => $key, 'min_depth' => $min_depth));
5411

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

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

    
5437
  return $files;
5438
}
5439

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

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

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

    
5507
  // If rendering in all browsers, no need for conditional comments.
5508
  if ($browsers['IE'] === TRUE && $browsers['!IE']) {
5509
    return $elements;
5510
  }
5511

    
5512
  // Determine the conditional comment expression for Internet Explorer to
5513
  // evaluate.
5514
  if ($browsers['IE'] === TRUE) {
5515
    $expression = 'IE';
5516
  }
5517
  elseif ($browsers['IE'] === FALSE) {
5518
    $expression = '!IE';
5519
  }
5520
  else {
5521
    $expression = $browsers['IE'];
5522
  }
5523

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

    
5544
  return $elements;
5545
}
5546

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

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

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

    
5597
  $element['#markup'] = l($element['#title'], $element['#href'], $element['#options']);
5598
  return $element;
5599
}
5600

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

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

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

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

    
5738
  // Modules can add elements to $page as needed in hook_page_build().
5739
  foreach (module_implements('page_build') as $module) {
5740
    $function = $module . '_page_build';
5741
    $function($page);
5742
  }
5743
  // Modules alter the $page as needed. Blocks are populated into regions like
5744
  // 'sidebar_first', 'footer', etc.
5745
  drupal_alter('page', $page);
5746

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

    
5754
  return drupal_render($page);
5755
}
5756

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

    
5840
  // Do not print elements twice.
5841
  if (!empty($elements['#printed'])) {
5842
    return '';
5843
  }
5844

    
5845
  // Try to fetch the element's markup from cache and return.
5846
  if (isset($elements['#cache'])) {
5847
    $cached_output = drupal_render_cache_get($elements);
5848
    if ($cached_output !== FALSE) {
5849
      return $cached_output;
5850
    }
5851
  }
5852

    
5853
  // If #markup is set, ensure #type is set. This allows to specify just #markup
5854
  // on an element without setting #type.
5855
  if (isset($elements['#markup']) && !isset($elements['#type'])) {
5856
    $elements['#type'] = 'markup';
5857
  }
5858

    
5859
  // If the default values for this element have not been loaded yet, populate
5860
  // them.
5861
  if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
5862
    $elements += element_info($elements['#type']);
5863
  }
5864

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

    
5876
  // Allow #pre_render to abort rendering.
5877
  if (!empty($elements['#printed'])) {
5878
    return '';
5879
  }
5880

    
5881
  // Get the children of the element, sorted by weight.
5882
  $children = element_children($elements, TRUE);
5883

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

    
5903
  // Let the theme functions in #theme_wrappers add markup around the rendered
5904
  // children.
5905
  if (isset($elements['#theme_wrappers'])) {
5906
    foreach ($elements['#theme_wrappers'] as $theme_wrapper) {
5907
      $elements['#children'] = theme($theme_wrapper, $elements);
5908
    }
5909
  }
5910

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

    
5922
  // Add any JavaScript state information associated with the element.
5923
  if (!empty($elements['#states'])) {
5924
    drupal_process_states($elements);
5925
  }
5926

    
5927
  // Add additional libraries, CSS, JavaScript an other custom
5928
  // attached data associated with this element.
5929
  if (!empty($elements['#attached'])) {
5930
    drupal_process_attached($elements);
5931
  }
5932

    
5933
  $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
5934
  $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
5935
  $output = $prefix . $elements['#children'] . $suffix;
5936

    
5937
  // Cache the processed element if #cache is set.
5938
  if (isset($elements['#cache'])) {
5939
    drupal_render_cache_set($output, $elements);
5940
  }
5941

    
5942
  $elements['#printed'] = TRUE;
5943
  return $output;
5944
}
5945

    
5946
/**
5947
 * Renders children of an element and concatenates them.
5948
 *
5949
 * This renders all children of an element using drupal_render() and then
5950
 * joins them together into a single string.
5951
 *
5952
 * @param $element
5953
 *   The structured array whose children shall be rendered.
5954
 * @param $children_keys
5955
 *   If the keys of the element's children are already known, they can be passed
5956
 *   in to save another run of element_children().
5957
 */
5958
function drupal_render_children(&$element, $children_keys = NULL) {
5959
  if ($children_keys === NULL) {
5960
    $children_keys = element_children($element);
5961
  }
5962
  $output = '';
5963
  foreach ($children_keys as $key) {
5964
    if (!empty($element[$key])) {
5965
      $output .= drupal_render($element[$key]);
5966
    }
5967
  }
5968
  return $output;
5969
}
5970

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

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

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

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

    
6074
  if (!empty($cid) && $cache = cache_get($cid, $bin)) {
6075
    // Add additional libraries, JavaScript, CSS and other data attached
6076
    // to this element.
6077
    if (isset($cache->data['#attached'])) {
6078
      drupal_process_attached($cache->data);
6079
    }
6080
    // Return the rendered output.
6081
    return $cache->data['#markup'];
6082
  }
6083
  return FALSE;
6084
}
6085

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

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

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

    
6141
  // Collect all #attached for this element.
6142
  if (isset($elements['#attached'])) {
6143
    foreach ($elements['#attached'] as $key => $value) {
6144
      if (!isset($attached[$key])) {
6145
        $attached[$key] = array();
6146
      }
6147
      $attached[$key] = array_merge($attached[$key], $value);
6148
    }
6149
  }
6150
  if ($children = element_children($elements)) {
6151
    foreach ($children as $child) {
6152
      drupal_render_collect_attached($elements[$child]);
6153
    }
6154
  }
6155

    
6156
  // If this was the first call to the function, return all attached elements
6157
  // and reset the static cache.
6158
  if ($return) {
6159
    $return = $attached;
6160
    $attached = array();
6161
    return $return;
6162
  }
6163
}
6164

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

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

    
6225
  $cid_parts[] = $theme;
6226
  // If Locale is enabled but we have only one language we do not need it as cid
6227
  // part.
6228
  if (drupal_multilingual()) {
6229
    foreach (language_types_configurable() as $language_type) {
6230
      $cid_parts[] = $GLOBALS[$language_type]->language;
6231
    }
6232
  }
6233

    
6234
  if (!empty($granularity)) {
6235
    // 'PER_ROLE' and 'PER_USER' are mutually exclusive. 'PER_USER' can be a
6236
    // resource drag for sites with many users, so when a module is being
6237
    // equivocal, we favor the less expensive 'PER_ROLE' pattern.
6238
    if ($granularity & DRUPAL_CACHE_PER_ROLE) {
6239
      $cid_parts[] = 'r.' . implode(',', array_keys($user->roles));
6240
    }
6241
    elseif ($granularity & DRUPAL_CACHE_PER_USER) {
6242
      $cid_parts[] = "u.$user->uid";
6243
    }
6244

    
6245
    if ($granularity & DRUPAL_CACHE_PER_PAGE) {
6246
      $cid_parts[] = $base_root . request_uri();
6247
    }
6248
  }
6249

    
6250
  return $cid_parts;
6251
}
6252

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

    
6279
/**
6280
 * Function used by uasort to sort structured arrays by weight.
6281
 */
6282
function element_sort($a, $b) {
6283
  $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
6284
  $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
6285
  if ($a_weight == $b_weight) {
6286
    return 0;
6287
  }
6288
  return ($a_weight < $b_weight) ? -1 : 1;
6289
}
6290

    
6291
/**
6292
 * Array sorting callback; sorts elements by title.
6293
 */
6294
function element_sort_by_title($a, $b) {
6295
  $a_title = (is_array($a) && isset($a['#title'])) ? $a['#title'] : '';
6296
  $b_title = (is_array($b) && isset($b['#title'])) ? $b['#title'] : '';
6297
  return strnatcasecmp($a_title, $b_title);
6298
}
6299

    
6300
/**
6301
 * Retrieves the default properties for the defined element type.
6302
 *
6303
 * @param $type
6304
 *   An element type as defined by hook_element_info().
6305
 */
6306
function element_info($type) {
6307
  // Use the advanced drupal_static() pattern, since this is called very often.
6308
  static $drupal_static_fast;
6309
  if (!isset($drupal_static_fast)) {
6310
    $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__);
6311
  }
6312
  $cache = &$drupal_static_fast['cache'];
6313

    
6314
  if (!isset($cache)) {
6315
    $cache = module_invoke_all('element_info');
6316
    foreach ($cache as $element_type => $info) {
6317
      $cache[$element_type]['#type'] = $element_type;
6318
    }
6319
    // Allow modules to alter the element type defaults.
6320
    drupal_alter('element_info', $cache);
6321
  }
6322

    
6323
  return isset($cache[$type]) ? $cache[$type] : array();
6324
}
6325

    
6326
/**
6327
 * Retrieves a single property for the defined element type.
6328
 *
6329
 * @param $type
6330
 *   An element type as defined by hook_element_info().
6331
 * @param $property_name
6332
 *   The property within the element type that should be returned.
6333
 * @param $default
6334
 *   (Optional) The value to return if the element type does not specify a
6335
 *   value for the property. Defaults to NULL.
6336
 */
6337
function element_info_property($type, $property_name, $default = NULL) {
6338
  return (($info = element_info($type)) && array_key_exists($property_name, $info)) ? $info[$property_name] : $default;
6339
}
6340

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

    
6365
/**
6366
 * Array sorting callback; sorts elements by 'title' key.
6367
 */
6368
function drupal_sort_title($a, $b) {
6369
  if (!isset($b['title'])) {
6370
    return -1;
6371
  }
6372
  if (!isset($a['title'])) {
6373
    return 1;
6374
  }
6375
  return strcasecmp($a['title'], $b['title']);
6376
}
6377

    
6378
/**
6379
 * Checks if the key is a property.
6380
 */
6381
function element_property($key) {
6382
  return $key[0] == '#';
6383
}
6384

    
6385
/**
6386
 * Gets properties of a structured array element (keys beginning with '#').
6387
 */
6388
function element_properties($element) {
6389
  return array_filter(array_keys((array) $element), 'element_property');
6390
}
6391

    
6392
/**
6393
 * Checks if the key is a child.
6394
 */
6395
function element_child($key) {
6396
  return !isset($key[0]) || $key[0] != '#';
6397
}
6398

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

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

    
6441
  return array_keys($children);
6442
}
6443

    
6444
/**
6445
 * Returns the visible children of an element.
6446
 *
6447
 * @param $elements
6448
 *   The parent element.
6449
 *
6450
 * @return
6451
 *   The array keys of the element's visible children.
6452
 */
6453
function element_get_visible_children(array $elements) {
6454
  $visible_children = array();
6455

    
6456
  foreach (element_children($elements) as $key) {
6457
    $child = $elements[$key];
6458

    
6459
    // Skip un-accessible children.
6460
    if (isset($child['#access']) && !$child['#access']) {
6461
      continue;
6462
    }
6463

    
6464
    // Skip value and hidden elements, since they are not rendered.
6465
    if (isset($child['#type']) && in_array($child['#type'], array('value', 'hidden'))) {
6466
      continue;
6467
    }
6468

    
6469
    $visible_children[$key] = $child;
6470
  }
6471

    
6472
  return array_keys($visible_children);
6473
}
6474

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

    
6500
/**
6501
 * Recursively computes the difference of arrays with additional index check.
6502
 *
6503
 * This is a version of array_diff_assoc() that supports multidimensional
6504
 * arrays.
6505
 *
6506
 * @param array $array1
6507
 *   The array to compare from.
6508
 * @param array $array2
6509
 *   The array to compare to.
6510
 *
6511
 * @return array
6512
 *   Returns an array containing all the values from array1 that are not present
6513
 *   in array2.
6514
 */
6515
function drupal_array_diff_assoc_recursive($array1, $array2) {
6516
  $difference = array();
6517

    
6518
  foreach ($array1 as $key => $value) {
6519
    if (is_array($value)) {
6520
      if (!array_key_exists($key, $array2) || !is_array($array2[$key])) {
6521
        $difference[$key] = $value;
6522
      }
6523
      else {
6524
        $new_diff = drupal_array_diff_assoc_recursive($value, $array2[$key]);
6525
        if (!empty($new_diff)) {
6526
          $difference[$key] = $new_diff;
6527
        }
6528
      }
6529
    }
6530
    elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
6531
      $difference[$key] = $value;
6532
    }
6533
  }
6534

    
6535
  return $difference;
6536
}
6537

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

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

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

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

    
6924
/**
6925
 * @addtogroup schemaapi
6926
 * @{
6927
 */
6928

    
6929
/**
6930
 * Creates all tables defined in a module's hook_schema().
6931
 *
6932
 * Note: This function does not pass the module's schema through
6933
 * hook_schema_alter(). The module's tables will be created exactly as the
6934
 * module defines them.
6935
 *
6936
 * @param $module
6937
 *   The module for which the tables will be created.
6938
 */
6939
function drupal_install_schema($module) {
6940
  $schema = drupal_get_schema_unprocessed($module);
6941
  _drupal_schema_initialize($schema, $module, FALSE);
6942

    
6943
  foreach ($schema as $name => $table) {
6944
    db_create_table($name, $table);
6945
  }
6946
}
6947

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

    
6967
  foreach ($schema as $table) {
6968
    if (db_table_exists($table['name'])) {
6969
      db_drop_table($table['name']);
6970
    }
6971
  }
6972
}
6973

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

    
7003
  if (isset($table) && isset($schema[$table])) {
7004
    return $schema[$table];
7005
  }
7006
  elseif (!empty($schema)) {
7007
    return $schema;
7008
  }
7009
  return array();
7010
}
7011

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

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

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

    
7103
  $schema = drupal_get_schema($table);
7104
  if (empty($schema)) {
7105
    return FALSE;
7106
  }
7107

    
7108
  $object = (object) $record;
7109
  $fields = array();
7110

    
7111
  // Go through the schema to determine fields to write.
7112
  foreach ($schema['fields'] as $field => $info) {
7113
    if ($info['type'] == 'serial') {
7114
      // Skip serial types if we are updating.
7115
      if (!empty($primary_keys)) {
7116
        continue;
7117
      }
7118
      // Track serial field so we can helpfully populate them after the query.
7119
      // NOTE: Each table should come with one serial field only.
7120
      $serial = $field;
7121
    }
7122

    
7123
    // Skip field if it is in $primary_keys as it is unnecessary to update a
7124
    // field to the value it is already set to.
7125
    if (in_array($field, $primary_keys)) {
7126
      continue;
7127
    }
7128

    
7129
    if (!property_exists($object, $field)) {
7130
      // Skip fields that are not provided, default values are already known
7131
      // by the database.
7132
      continue;
7133
    }
7134

    
7135
    // Build array of fields to update or insert.
7136
    if (empty($info['serialize'])) {
7137
      $fields[$field] = $object->$field;
7138
    }
7139
    else {
7140
      $fields[$field] = serialize($object->$field);
7141
    }
7142

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

    
7162
  if (empty($fields)) {
7163
    return;
7164
  }
7165

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

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

    
7214
  // If we are inserting, populate empty fields with default values.
7215
  if (empty($primary_keys)) {
7216
    foreach ($schema['fields'] as $field => $info) {
7217
      if (isset($info['default']) && !property_exists($object, $field)) {
7218
        $object->$field = $info['default'];
7219
      }
7220
    }
7221
  }
7222

    
7223
  // If we began with an array, convert back.
7224
  if (is_array($record)) {
7225
    $record = (array) $object;
7226
  }
7227

    
7228
  return $return;
7229
}
7230

    
7231
/**
7232
 * @} End of "addtogroup schemaapi".
7233
 */
7234

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

    
7273
  if (!isset($info[$filename])) {
7274
    if (!file_exists($filename)) {
7275
      $info[$filename] = array();
7276
    }
7277
    else {
7278
      $data = file_get_contents($filename);
7279
      $info[$filename] = drupal_parse_info_format($data);
7280
    }
7281
  }
7282
  return $info[$filename];
7283
}
7284

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

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

    
7347
      // Parse array syntax.
7348
      $keys = preg_split('/\]?\[/', rtrim($key, ']'));
7349
      $last = array_pop($keys);
7350
      $parent = &$info;
7351

    
7352
      // Create nested arrays.
7353
      foreach ($keys as $key) {
7354
        if ($key == '') {
7355
          $key = count($parent);
7356
        }
7357
        if (!isset($parent[$key]) || !is_array($parent[$key])) {
7358
          $parent[$key] = array();
7359
        }
7360
        $parent = &$parent[$key];
7361
      }
7362

    
7363
      // Handle PHP constants.
7364
      if (isset($constants[$value])) {
7365
        $value = $constants[$value];
7366
      }
7367

    
7368
      // Insert actual value.
7369
      if ($last == '') {
7370
        $last = count($parent);
7371
      }
7372
      $parent[$last] = $value;
7373
    }
7374
  }
7375

    
7376
  return $info;
7377
}
7378

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

    
7402

    
7403
/**
7404
 * Explodes a string of tags into an array.
7405
 *
7406
 * @see drupal_implode_tags()
7407
 */
7408
function drupal_explode_tags($tags) {
7409
  // This regexp allows the following types of user input:
7410
  // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
7411
  $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
7412
  preg_match_all($regexp, $tags, $matches);
7413
  $typed_tags = array_unique($matches[1]);
7414

    
7415
  $tags = array();
7416
  foreach ($typed_tags as $tag) {
7417
    // If a user has escaped a term (to demonstrate that it is a group,
7418
    // or includes a comma or quote character), we remove the escape
7419
    // formatting so to save the term into the database as the user intends.
7420
    $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
7421
    if ($tag != "") {
7422
      $tags[] = $tag;
7423
    }
7424
  }
7425

    
7426
  return $tags;
7427
}
7428

    
7429
/**
7430
 * Implodes an array of tags into a string.
7431
 *
7432
 * @see drupal_explode_tags()
7433
 */
7434
function drupal_implode_tags($tags) {
7435
  $encoded_tags = array();
7436
  foreach ($tags as $tag) {
7437
    // Commas and quotes in tag names are special cases, so encode them.
7438
    if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
7439
      $tag = '"' . str_replace('"', '""', $tag) . '"';
7440
    }
7441

    
7442
    $encoded_tags[] = $tag;
7443
  }
7444
  return implode(', ', $encoded_tags);
7445
}
7446

    
7447
/**
7448
 * Flushes all cached data on the site.
7449
 *
7450
 * Empties cache tables, rebuilds the menu cache and theme registries, and
7451
 * invokes a hook so that other modules' cache data can be cleared as well.
7452
 */
7453
function drupal_flush_all_caches() {
7454
  // Change query-strings on css/js files to enforce reload for all users.
7455
  _drupal_flush_css_js();
7456

    
7457
  registry_rebuild();
7458
  drupal_clear_css_cache();
7459
  drupal_clear_js_cache();
7460

    
7461
  // Rebuild the theme data. Note that the module data is rebuilt above, as
7462
  // part of registry_rebuild().
7463
  system_rebuild_theme_data();
7464
  drupal_theme_rebuild();
7465

    
7466
  entity_info_cache_clear();
7467
  node_types_rebuild();
7468
  // node_menu() defines menu items based on node types so it needs to come
7469
  // after node types are rebuilt.
7470
  menu_rebuild();
7471

    
7472
  // Synchronize to catch any actions that were added or removed.
7473
  actions_synchronize();
7474

    
7475
  // Don't clear cache_form - in-progress form submissions may break.
7476
  // Ordered so clearing the page cache will always be the last action.
7477
  $core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
7478
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
7479
  foreach ($cache_tables as $table) {
7480
    cache_clear_all('*', $table, TRUE);
7481
  }
7482

    
7483
  // Rebuild the bootstrap module list. We do this here so that developers
7484
  // can get new hook_boot() implementations registered without having to
7485
  // write a hook_update_N() function.
7486
  _system_update_bootstrap_status();
7487
}
7488

    
7489
/**
7490
 * Changes the dummy query string added to all CSS and JavaScript files.
7491
 *
7492
 * Changing the dummy query string appended to CSS and JavaScript files forces
7493
 * all browsers to reload fresh files.
7494
 */
7495
function _drupal_flush_css_js() {
7496
  // The timestamp is converted to base 36 in order to make it more compact.
7497
  variable_set('css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
7498
}
7499

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

    
7519
  // Display values with pre-formatting to increase readability.
7520
  $string = '<pre>' . $string . '</pre>';
7521

    
7522
  trigger_error(trim($label ? "$label: $string" : $string));
7523
}
7524

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

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

    
7607
/**
7608
 * Get the entity info array of an entity type.
7609
 *
7610
 * @param $entity_type
7611
 *   The entity type, e.g. node, for which the info shall be returned, or NULL
7612
 *   to return an array with info about all types.
7613
 *
7614
 * @see hook_entity_info()
7615
 * @see hook_entity_info_alter()
7616
 */
7617
function entity_get_info($entity_type = NULL) {
7618
  global $language;
7619

    
7620
  // Use the advanced drupal_static() pattern, since this is called very often.
7621
  static $drupal_static_fast;
7622
  if (!isset($drupal_static_fast)) {
7623
    $drupal_static_fast['entity_info'] = &drupal_static(__FUNCTION__);
7624
  }
7625
  $entity_info = &$drupal_static_fast['entity_info'];
7626

    
7627
  // hook_entity_info() includes translated strings, so each language is cached
7628
  // separately.
7629
  $langcode = $language->language;
7630

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

    
7679
  if (empty($entity_type)) {
7680
    return $entity_info;
7681
  }
7682
  elseif (isset($entity_info[$entity_type])) {
7683
    return $entity_info[$entity_type];
7684
  }
7685
}
7686

    
7687
/**
7688
 * Resets the cached information about entity types.
7689
 */
7690
function entity_info_cache_clear() {
7691
  drupal_static_reset('entity_get_info');
7692
  // Clear all languages.
7693
  cache_clear_all('entity_info:', 'cache', TRUE);
7694
}
7695

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

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

    
7718
  if (!empty($info['entity keys']['bundle'])) {
7719
    // Explicitly fail for malformed entities missing the bundle property.
7720
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
7721
      throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
7722
    }
7723
    $bundle = $entity->{$info['entity keys']['bundle']};
7724
  }
7725
  else {
7726
    // The entity type provides no bundle key: assume a single bundle, named
7727
    // after the entity type.
7728
    $bundle = $entity_type;
7729
  }
7730

    
7731
  return array($id, $vid, $bundle);
7732
}
7733

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

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

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

    
7829
/**
7830
 * Get the entity controller class for an entity type.
7831
 */
7832
function entity_get_controller($entity_type) {
7833
  $controllers = &drupal_static(__FUNCTION__, array());
7834
  if (!isset($controllers[$entity_type])) {
7835
    $type_info = entity_get_info($entity_type);
7836
    $class = $type_info['controller class'];
7837
    $controllers[$entity_type] = new $class($entity_type);
7838
  }
7839
  return $controllers[$entity_type];
7840
}
7841

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

    
7871
  // To ensure hooks are only run once per entity, check for an
7872
  // entity_view_prepared flag and only process items without it.
7873
  // @todo: resolve this more generally for both entity and field level hooks.
7874
  $prepare = array();
7875
  foreach ($entities as $id => $entity) {
7876
    if (empty($entity->entity_view_prepared)) {
7877
      // Add this entity to the items to be prepared.
7878
      $prepare[$id] = $entity;
7879

    
7880
      // Mark this item as prepared.
7881
      $entity->entity_view_prepared = TRUE;
7882
    }
7883
  }
7884

    
7885
  if (!empty($prepare)) {
7886
    module_invoke_all('entity_prepare_view', $prepare, $entity_type, $langcode);
7887
  }
7888
}
7889

    
7890
/**
7891
 * Returns the URI elements of an entity.
7892
 *
7893
 * @param $entity_type
7894
 *   The entity type; e.g. 'node' or 'user'.
7895
 * @param $entity
7896
 *   The entity for which to generate a path.
7897
 * @return
7898
 *   An array containing the 'path' and 'options' keys used to build the URI of
7899
 *   the entity, and matching the signature of url(). NULL if the entity has no
7900
 *   URI of its own.
7901
 */
7902
function entity_uri($entity_type, $entity) {
7903
  $info = entity_get_info($entity_type);
7904
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
7905

    
7906
  // A bundle-specific callback takes precedence over the generic one for the
7907
  // entity type.
7908
  if (isset($info['bundles'][$bundle]['uri callback'])) {
7909
    $uri_callback = $info['bundles'][$bundle]['uri callback'];
7910
  }
7911
  elseif (isset($info['uri callback'])) {
7912
    $uri_callback = $info['uri callback'];
7913
  }
7914
  else {
7915
    return NULL;
7916
  }
7917

    
7918
  // Invoke the callback to get the URI. If there is no callback, return NULL.
7919
  if (isset($uri_callback) && function_exists($uri_callback)) {
7920
    $uri = $uri_callback($entity);
7921
    // Pass the entity data to url() so that alter functions do not need to
7922
    // lookup this entity again.
7923
    $uri['options']['entity_type'] = $entity_type;
7924
    $uri['options']['entity'] = $entity;
7925
    return $uri;
7926
  }
7927
}
7928

    
7929
/**
7930
 * Returns the label of an entity.
7931
 *
7932
 * See the 'label callback' component of the hook_entity_info() return value
7933
 * for more information.
7934
 *
7935
 * @param $entity_type
7936
 *   The entity type; e.g., 'node' or 'user'.
7937
 * @param $entity
7938
 *   The entity for which to generate the label.
7939
 *
7940
 * @return
7941
 *   The entity label, or FALSE if not found.
7942
 */
7943
function entity_label($entity_type, $entity) {
7944
  $label = FALSE;
7945
  $info = entity_get_info($entity_type);
7946
  if (isset($info['label callback']) && function_exists($info['label callback'])) {
7947
    $label = $info['label callback']($entity, $entity_type);
7948
  }
7949
  elseif (!empty($info['entity keys']['label']) && isset($entity->{$info['entity keys']['label']})) {
7950
    $label = $entity->{$info['entity keys']['label']};
7951
  }
7952

    
7953
  return $label;
7954
}
7955

    
7956
/**
7957
 * Returns the language of an entity.
7958
 *
7959
 * @param $entity_type
7960
 *   The entity type; e.g., 'node' or 'user'.
7961
 * @param $entity
7962
 *   The entity for which to get the language.
7963
 *
7964
 * @return
7965
 *   A valid language code or NULL if the entity has no language support.
7966
 */
7967
function entity_language($entity_type, $entity) {
7968
  $info = entity_get_info($entity_type);
7969

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

    
7991
  return $langcode;
7992
}
7993

    
7994
/**
7995
 * Attaches field API validation to entity forms.
7996
 */
7997
function entity_form_field_validate($entity_type, $form, &$form_state) {
7998
  // All field attach API functions act on an entity object, but during form
7999
  // validation, we don't have one. $form_state contains the entity as it was
8000
  // prior to processing the current form submission, and we must not update it
8001
  // until we have fully validated the submitted input. Therefore, for
8002
  // validation, act on a pseudo entity created out of the form values.
8003
  $pseudo_entity = (object) $form_state['values'];
8004
  field_attach_form_validate($entity_type, $pseudo_entity, $form, $form_state);
8005
}
8006

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

    
8032
  // Copy top-level form values that are not for fields to entity properties,
8033
  // without changing existing entity properties that are not being edited by
8034
  // this form. Copying field values must be done using field_attach_submit().
8035
  $values_excluding_fields = $info['fieldable'] ? array_diff_key($form_state['values'], field_info_instances($entity_type, $bundle)) : $form_state['values'];
8036
  foreach ($values_excluding_fields as $key => $value) {
8037
    $entity->$key = $value;
8038
  }
8039

    
8040
  // Invoke all specified builders for copying form values to entity properties.
8041
  if (isset($form['#entity_builders'])) {
8042
    foreach ($form['#entity_builders'] as $function) {
8043
      $function($entity_type, $entity, $form, $form_state);
8044
    }
8045
  }
8046

    
8047
  // Copy field values to the entity.
8048
  if ($info['fieldable']) {
8049
    field_attach_submit($entity_type, $entity, $form, $form_state);
8050
  }
8051
}
8052

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

    
8086
/**
8087
 * Retrieves a list of all available archivers.
8088
 *
8089
 * @see hook_archiver_info()
8090
 * @see hook_archiver_info_alter()
8091
 */
8092
function archiver_get_info() {
8093
  $archiver_info = &drupal_static(__FUNCTION__, array());
8094

    
8095
  if (empty($archiver_info)) {
8096
    $cache = cache_get('archiver_info');
8097
    if ($cache === FALSE) {
8098
      // Rebuild the cache and save it.
8099
      $archiver_info = module_invoke_all('archiver_info');
8100
      drupal_alter('archiver_info', $archiver_info);
8101
      uasort($archiver_info, 'drupal_sort_weight');
8102
      cache_set('archiver_info', $archiver_info);
8103
    }
8104
    else {
8105
      $archiver_info = $cache->data;
8106
    }
8107
  }
8108

    
8109
  return $archiver_info;
8110
}
8111

    
8112
/**
8113
 * Returns a string of supported archive extensions.
8114
 *
8115
 * @return
8116
 *   A space-separated string of extensions suitable for use by the file
8117
 *   validation system.
8118
 */
8119
function archiver_get_extensions() {
8120
  $valid_extensions = array();
8121
  foreach (archiver_get_info() as $archive) {
8122
    foreach ($archive['extensions'] as $extension) {
8123
      foreach (explode('.', $extension) as $part) {
8124
        if (!in_array($part, $valid_extensions)) {
8125
          $valid_extensions[] = $part;
8126
        }
8127
      }
8128
    }
8129
  }
8130
  return implode(' ', $valid_extensions);
8131
}
8132

    
8133
/**
8134
 * Creates the appropriate archiver for the specified file.
8135
 *
8136
 * @param $file
8137
 *   The full path of the archive file. Note that stream wrapper paths are
8138
 *   supported, but not remote ones.
8139
 *
8140
 * @return
8141
 *   A newly created instance of the archiver class appropriate
8142
 *   for the specified file, already bound to that file.
8143
 *   If no appropriate archiver class was found, will return FALSE.
8144
 */
8145
function archiver_get_archiver($file) {
8146
  // Archivers can only work on local paths
8147
  $filepath = drupal_realpath($file);
8148
  if (!is_file($filepath)) {
8149
    throw new Exception(t('Archivers can only operate on local files: %file not supported', array('%file' => $file)));
8150
  }
8151
  $archiver_info = archiver_get_info();
8152

    
8153
  foreach ($archiver_info as $implementation) {
8154
    foreach ($implementation['extensions'] as $extension) {
8155
      // Because extensions may be multi-part, such as .tar.gz,
8156
      // we cannot use simpler approaches like substr() or pathinfo().
8157
      // This method isn't quite as clean but gets the job done.
8158
      // Also note that the file may not yet exist, so we cannot rely
8159
      // on fileinfo() or other disk-level utilities.
8160
      if (strrpos($filepath, '.' . $extension) === strlen($filepath) - strlen('.' . $extension)) {
8161
        return new $implementation['class']($filepath);
8162
      }
8163
    }
8164
  }
8165
}
8166

    
8167
/**
8168
 * Assembles the Drupal Updater registry.
8169
 *
8170
 * An Updater is a class that knows how to update various parts of the Drupal
8171
 * file system, for example to update modules that have newer releases, or to
8172
 * install a new theme.
8173
 *
8174
 * @return
8175
 *   The Drupal Updater class registry.
8176
 *
8177
 * @see hook_updater_info()
8178
 * @see hook_updater_info_alter()
8179
 */
8180
function drupal_get_updaters() {
8181
  $updaters = &drupal_static(__FUNCTION__);
8182
  if (!isset($updaters)) {
8183
    $updaters = module_invoke_all('updater_info');
8184
    drupal_alter('updater_info', $updaters);
8185
    uasort($updaters, 'drupal_sort_weight');
8186
  }
8187
  return $updaters;
8188
}
8189

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