Projet

Général

Profil

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

root / drupal7 / includes / common.inc @ ecd39969

1
<?php
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
232
  return $profile;
233
}
234

    
235

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

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

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

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

    
262
  return $breadcrumb;
263
}
264

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
445
  return $params;
446
}
447

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

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

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

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

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

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

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

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

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

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

    
621
  return $options;
622
}
623

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

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

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

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

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

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

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

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

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

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

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

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

    
801
  $result = new stdClass();
802

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

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

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

    
818
  timer_start(__FUNCTION__);
819

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

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

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

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

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

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

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

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

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

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

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

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

    
924
    return $result;
925
  }
926

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

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

    
942
  // If the server URL has a user then attempt to use basic authentication.
943
  if (isset($uri['user'])) {
944
    $options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ':'));
945
  }
946

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

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

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

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

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

    
1004
  // Parse the response status line.
1005
  $response_status_array = _drupal_parse_response_status(trim(array_shift($response)));
1006
  $result->protocol = $response_status_array['http_version'];
1007
  $result->status_message = $response_status_array['reason_phrase'];
1008
  $code = $response_status_array['response_code'];
1009

    
1010
  $result->headers = array();
1011

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

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

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

    
1098
        // We need to unset the 'Host' header
1099
        // as we are redirecting to a new location.
1100
        unset($options['headers']['Host']);
1101

    
1102
        $result = drupal_http_request($location, $options);
1103
        $result->redirect_code = $code;
1104
      }
1105
      if (!isset($result->redirect_url)) {
1106
        $result->redirect_url = $location;
1107
      }
1108
      break;
1109
    default:
1110
      $result->error = $result->status_message;
1111
  }
1112

    
1113
  return $result;
1114
}
1115

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

    
1147
/**
1148
 * Helper function for determining hosts excluded from needing a proxy.
1149
 *
1150
 * @return
1151
 *   TRUE if a proxy should be used for this host.
1152
 */
1153
function _drupal_http_use_proxy($host) {
1154
  $proxy_exceptions = variable_get('proxy_exceptions', array('localhost', '127.0.0.1'));
1155
  return !in_array(strtolower($host), $proxy_exceptions, TRUE);
1156
}
1157

    
1158
/**
1159
 * @} End of "HTTP handling".
1160
 */
1161

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

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

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

    
1223
/**
1224
 * @defgroup validation Input validation
1225
 * @{
1226
 * Functions to validate user input.
1227
 */
1228

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

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

    
1283
/**
1284
 * @} End of "defgroup validation".
1285
 */
1286

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

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

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

    
1365
/**
1366
 * @defgroup sanitization Sanitization functions
1367
 * @{
1368
 * Functions to sanitize values.
1369
 *
1370
 * See http://drupal.org/writing-secure-code for information
1371
 * on writing secure code.
1372
 */
1373

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

    
1398
  if (!isset($allowed_protocols)) {
1399
    $allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal')));
1400
  }
1401

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

    
1423
  return $uri;
1424
}
1425

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

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

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

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

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

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

    
1537
  if ($store) {
1538
    $allowed_html = array_flip($m);
1539
    return;
1540
  }
1541

    
1542
  $string = $m[1];
1543

    
1544
  if (substr($string, 0, 1) != '<') {
1545
    // We matched a lone ">" character.
1546
    return '&gt;';
1547
  }
1548
  elseif (strlen($string) == 1) {
1549
    // We matched a lone "<" character.
1550
    return '&lt;';
1551
  }
1552

    
1553
  if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9\-]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
1554
    // Seriously malformed.
1555
    return '';
1556
  }
1557

    
1558
  $slash = trim($matches[1]);
1559
  $elem = &$matches[2];
1560
  $attrlist = &$matches[3];
1561
  $comment = &$matches[4];
1562

    
1563
  if ($comment) {
1564
    $elem = '!--';
1565
  }
1566

    
1567
  if (!isset($allowed_html[strtolower($elem)])) {
1568
    // Disallowed HTML element.
1569
    return '';
1570
  }
1571

    
1572
  if ($comment) {
1573
    return $comment;
1574
  }
1575

    
1576
  if ($slash != '') {
1577
    return "</$elem>";
1578
  }
1579

    
1580
  // Is there a closing XHTML slash at the end of the attributes?
1581
  $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
1582
  $xhtml_slash = $count ? ' /' : '';
1583

    
1584
  // Clean up attributes.
1585
  $attr2 = implode(' ', _filter_xss_attributes($attrlist));
1586
  $attr2 = preg_replace('/[<>]/', '', $attr2);
1587
  $attr2 = strlen($attr2) ? ' ' . $attr2 : '';
1588

    
1589
  return "<$elem$attr2$xhtml_slash>";
1590
}
1591

    
1592
/**
1593
 * Processes a string of HTML attributes.
1594
 *
1595
 * @return
1596
 *   Cleaned up version of the HTML attributes.
1597
 */
1598
function _filter_xss_attributes($attr) {
1599
  $attrarr = array();
1600
  $mode = 0;
1601
  $attrname = '';
1602

    
1603
  while (strlen($attr) != 0) {
1604
    // Was the last operation successful?
1605
    $working = 0;
1606

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

    
1618
      case 1:
1619
        // Equals sign or valueless ("selected").
1620
        if (preg_match('/^\s*=\s*/', $attr)) {
1621
          $working = 1; $mode = 2;
1622
          $attr = preg_replace('/^\s*=\s*/', '', $attr);
1623
          break;
1624
        }
1625

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

    
1635
      case 2:
1636
        // Attribute value, a URL after href= for instance.
1637
        if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
1638
          $thisval = filter_xss_bad_protocol($match[1]);
1639

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

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

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

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

    
1663
          if (!$skip) {
1664
            $attrarr[] = "$attrname=\"$thisval\"";
1665
          }
1666
          $working = 1; $mode = 0;
1667
          $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
1668
        }
1669
        break;
1670
    }
1671

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

    
1689
  // The attribute list ends with a valueless attribute like "selected".
1690
  if ($mode == 1 && !$skip) {
1691
    $attrarr[] = $attrname;
1692
  }
1693
  return $attrarr;
1694
}
1695

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

    
1719
    $string = decode_entities($string);
1720
  }
1721
  return check_plain(drupal_strip_dangerous_protocols($string));
1722
}
1723

    
1724
/**
1725
 * @} End of "defgroup sanitization".
1726
 */
1727

    
1728
/**
1729
 * @defgroup format Formatting
1730
 * @{
1731
 * Functions to format numbers, strings, dates, etc.
1732
 */
1733

    
1734
/**
1735
 * Formats an RSS channel.
1736
 *
1737
 * Arbitrary elements may be added using the $args associative array.
1738
 */
1739
function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
1740
  global $language_content;
1741
  $langcode = $langcode ? $langcode : $language_content->language;
1742

    
1743
  $output = "<channel>\n";
1744
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1745
  $output .= ' <link>' . check_url($link) . "</link>\n";
1746

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

    
1756
  return $output;
1757
}
1758

    
1759
/**
1760
 * Formats a single RSS item.
1761
 *
1762
 * Arbitrary elements may be added using the $args associative array.
1763
 */
1764
function format_rss_item($title, $link, $description, $args = array()) {
1765
  $output = "<item>\n";
1766
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1767
  $output .= ' <link>' . check_url($link) . "</link>\n";
1768
  $output .= ' <description>' . check_plain($description) . "</description>\n";
1769
  $output .= format_xml_elements($args);
1770
  $output .= "</item>\n";
1771

    
1772
  return $output;
1773
}
1774

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

    
1805
        if (isset($value['value']) && $value['value'] != '') {
1806
          $output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : (!empty($value['encoded']) ? $value['value'] : check_plain($value['value']))) . '</' . $value['key'] . ">\n";
1807
        }
1808
        else {
1809
          $output .= " />\n";
1810
        }
1811
      }
1812
    }
1813
    else {
1814
      $output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</$key>\n";
1815
    }
1816
  }
1817
  return $output;
1818
}
1819

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

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

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

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

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

    
1987
    if ($granularity == 0) {
1988
      break;
1989
    }
1990
  }
1991
  return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
1992
}
1993

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

    
2030
  if (!isset($timezone)) {
2031
    $timezone = date_default_timezone_get();
2032
  }
2033
  // Store DateTimeZone objects in an array rather than repeatedly
2034
  // constructing identical objects over the life of a request.
2035
  if (!isset($timezones[$timezone])) {
2036
    $timezones[$timezone] = timezone_open($timezone);
2037
  }
2038

    
2039
  // Use the default langcode if none is set.
2040
  global $language;
2041
  if (empty($langcode)) {
2042
    $langcode = isset($language->language) ? $language->language : 'en';
2043
  }
2044

    
2045
  switch ($type) {
2046
    case 'short':
2047
      $format = variable_get('date_format_short', 'm/d/Y - H:i');
2048
      break;
2049

    
2050
    case 'long':
2051
      $format = variable_get('date_format_long', 'l, F j, Y - H:i');
2052
      break;
2053

    
2054
    case 'custom':
2055
      // No change to format.
2056
      break;
2057

    
2058
    case 'medium':
2059
    default:
2060
      // Retrieve the format of the custom $type passed.
2061
      if ($type != 'medium') {
2062
        $format = variable_get('date_format_' . $type, '');
2063
      }
2064
      // Fall back to 'medium'.
2065
      if ($format === '') {
2066
        $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
2067
      }
2068
      break;
2069
  }
2070

    
2071
  // Create a DateTime object from the timestamp.
2072
  $date_time = date_create('@' . $timestamp);
2073
  // Set the time zone for the DateTime object.
2074
  date_timezone_set($date_time, $timezones[$timezone]);
2075

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

    
2083
  // Call date_format().
2084
  $format = date_format($date_time, $format);
2085

    
2086
  // Pass the langcode to _format_date_callback().
2087
  _format_date_callback(NULL, $langcode);
2088

    
2089
  // Translate the marked sequences.
2090
  return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);
2091
}
2092

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

    
2110
/**
2111
 * Translates a formatted date string.
2112
 *
2113
 * Callback for preg_replace_callback() within format_date().
2114
 */
2115
function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
2116
  // We cache translations to avoid redundant and rather costly calls to t().
2117
  static $cache, $langcode;
2118

    
2119
  if (!isset($matches)) {
2120
    $langcode = $new_langcode;
2121
    return;
2122
  }
2123

    
2124
  $code = $matches[1];
2125
  $string = $matches[2];
2126

    
2127
  if (!isset($cache[$langcode][$code][$string])) {
2128
    $options = array(
2129
      'langcode' => $langcode,
2130
    );
2131

    
2132
    if ($code == 'F') {
2133
      $options['context'] = 'Long month name';
2134
    }
2135

    
2136
    if ($code == '') {
2137
      $cache[$langcode][$code][$string] = $string;
2138
    }
2139
    else {
2140
      $cache[$langcode][$code][$string] = t($string, array(), $options);
2141
    }
2142
  }
2143
  return $cache[$langcode][$code][$string];
2144
}
2145

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

    
2172
/**
2173
 * @} End of "defgroup format".
2174
 */
2175

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

    
2251
  // Determine whether this is an external link, but ensure that the current
2252
  // path is always treated as internal by default (to prevent external link
2253
  // injection vulnerabilities).
2254
  if (!isset($options['external'])) {
2255
    $options['external'] = $path === $_GET['q'] ? FALSE : url_is_external($path);
2256
  }
2257

    
2258
  // Preserve the original path before altering or aliasing.
2259
  $original_path = $path;
2260

    
2261
  // Allow other modules to alter the outbound URL and options.
2262
  drupal_alter('url_outbound', $path, $options, $original_path);
2263

    
2264
  if (isset($options['fragment']) && $options['fragment'] !== '') {
2265
    $options['fragment'] = '#' . $options['fragment'];
2266
  }
2267

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

    
2293
  // Strip leading slashes from internal paths to prevent them becoming external
2294
  // URLs without protocol. /example.com should not be turned into
2295
  // //example.com.
2296
  $path = ltrim($path, '/');
2297

    
2298
  global $base_url, $base_secure_url, $base_insecure_url;
2299

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

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

    
2332
  $base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
2333
  $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
2334

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

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

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

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

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

    
2512
  // Merge in defaults.
2513
  $options += array(
2514
    'attributes' => array(),
2515
    'html' => FALSE,
2516
  );
2517

    
2518
  // Append active class.
2519
  if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
2520
      (empty($options['language']) || $options['language']->language == $language_url->language)) {
2521
    $options['attributes']['class'][] = 'active';
2522
  }
2523

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

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

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

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

    
2670
  // Send appropriate HTTP-Header for browsers and search engines.
2671
  global $language;
2672
  drupal_add_http_header('Content-Language', $language->language);
2673

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

    
2683
  // Menu status constants are integers; page content is a string or array.
2684
  if (is_int($page_callback_result)) {
2685
    // @todo: Break these up into separate functions?
2686
    switch ($page_callback_result) {
2687
      case MENU_NOT_FOUND:
2688
        // Print a 404 page.
2689
        drupal_add_http_header('Status', '404 Not Found');
2690

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

    
2693
        // Check for and return a fast 404 page if configured.
2694
        drupal_fast_404();
2695

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

    
2704
        $path = drupal_get_normal_path(variable_get('site_404', ''));
2705
        if ($path && $path != $_GET['q']) {
2706
          // Custom 404 handler. Set the active item in case there are tabs to
2707
          // display, or other dependencies on the path.
2708
          menu_set_active_item($path);
2709
          $return = menu_execute_active_handler($path, FALSE);
2710
        }
2711

    
2712
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2713
          // Standard 404 handler.
2714
          drupal_set_title(t('Page not found'));
2715
          $return = t('The requested page "@path" could not be found.', array('@path' => request_uri()));
2716
        }
2717

    
2718
        drupal_set_page_content($return);
2719
        $page = element_info('page');
2720
        print drupal_render_page($page);
2721
        break;
2722

    
2723
      case MENU_ACCESS_DENIED:
2724
        // Print a 403 page.
2725
        drupal_add_http_header('Status', '403 Forbidden');
2726
        watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
2727

    
2728
        // Keep old path for reference, and to allow forms to redirect to it.
2729
        if (!isset($_GET['destination'])) {
2730
          // Make sure that the current path is not interpreted as external URL.
2731
          if (!url_is_external($_GET['q'])) {
2732
            $_GET['destination'] = $_GET['q'];
2733
          }
2734
        }
2735

    
2736
        $path = drupal_get_normal_path(variable_get('site_403', ''));
2737
        if ($path && $path != $_GET['q']) {
2738
          // Custom 403 handler. Set the active item in case there are tabs to
2739
          // display or other dependencies on the path.
2740
          menu_set_active_item($path);
2741
          $return = menu_execute_active_handler($path, FALSE);
2742
        }
2743

    
2744
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2745
          // Standard 403 handler.
2746
          drupal_set_title(t('Access denied'));
2747
          $return = t('You are not authorized to access this page.');
2748
        }
2749

    
2750
        print drupal_render_page($return);
2751
        break;
2752

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

    
2769
  // Perform end-of-request tasks.
2770
  drupal_page_footer();
2771
}
2772

    
2773
/**
2774
 * Performs end-of-request tasks.
2775
 *
2776
 * This function sets the page cache if appropriate, and allows modules to
2777
 * react to the closing of the page by calling hook_exit().
2778
 */
2779
function drupal_page_footer() {
2780
  global $user;
2781

    
2782
  module_invoke_all('exit');
2783

    
2784
  // Commit the user session, if needed.
2785
  drupal_session_commit();
2786

    
2787
  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
2788
    drupal_serve_page_from_cache($cache);
2789
  }
2790
  else {
2791
    ob_flush();
2792
  }
2793

    
2794
  _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
2795
  drupal_cache_system_paths();
2796
  module_implements_write_cache();
2797
  drupal_file_scan_write_cache();
2798
  system_run_automated_cron();
2799
}
2800

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

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

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

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

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

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

    
2937
  if ($header) {
2938
    // Also add a HTTP header "Link:".
2939
    $href = '<' . check_plain($attributes['href']) . '>;';
2940
    unset($attributes['href']);
2941
    $element['#attached']['drupal_add_http_header'][] = array('Link',  $href . drupal_http_header_attributes($attributes), TRUE);
2942
  }
2943

    
2944
  drupal_add_html_head($element, 'drupal_add_html_head_link:' . $attributes['rel'] . ':' . $href);
2945
}
2946

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

    
3067
  // If the $css variable has been reset with drupal_static_reset(), there is
3068
  // no longer any CSS being tracked, so set the counter back to 0 also.
3069
  if (count($css) === 0) {
3070
    $count = 0;
3071
  }
3072

    
3073
  // Construct the options, taking the defaults into consideration.
3074
  if (isset($options)) {
3075
    if (!is_array($options)) {
3076
      $options = array('type' => $options);
3077
    }
3078
  }
3079
  else {
3080
    $options = array();
3081
  }
3082

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

    
3101
    // Files with a query string cannot be preprocessed.
3102
    if ($options['type'] === 'file' && $options['preprocess'] && strpos($options['data'], '?') !== FALSE) {
3103
      $options['preprocess'] = FALSE;
3104
    }
3105

    
3106
    // Always add a tiny value to the weight, to conserve the insertion order.
3107
    $options['weight'] += $count / 1000;
3108
    $count++;
3109

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

    
3124
  return $css;
3125
}
3126

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

    
3161
  // Allow modules and themes to alter the CSS items.
3162
  if (!$skip_alter) {
3163
    drupal_alter('css', $css);
3164
  }
3165

    
3166
  // Sort CSS items, so that they appear in the correct order.
3167
  uasort($css, 'drupal_sort_css_js');
3168

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

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

    
3195
  // Render the HTML needed to load the CSS.
3196
  $styles = array(
3197
    '#type' => 'styles',
3198
    '#items' => $css,
3199
  );
3200

    
3201
  if (!empty($setting)) {
3202
    $styles['#attached']['js'][] = array('type' => 'setting', 'data' => $setting);
3203
  }
3204

    
3205
  return drupal_render($styles);
3206
}
3207

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

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

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

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

    
3353
    // Add the item to the current group.
3354
    $groups[$i]['items'][] = $item;
3355
  }
3356
  return $groups;
3357
}
3358

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

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

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

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

    
3478
  // For inline CSS to validate as XHTML, all CSS containing XHTML needs to be
3479
  // wrapped in CDATA. To make that backwards compatible with HTML 4, we need to
3480
  // comment out the CDATA-tag.
3481
  $embed_prefix = "\n<!--/*--><![CDATA[/*><!--*/\n";
3482
  $embed_suffix = "\n/*]]>*/-->\n";
3483

    
3484
  // Defaults for LINK and STYLE elements.
3485
  $link_element_defaults = array(
3486
    '#type' => 'html_tag',
3487
    '#tag' => 'link',
3488
    '#attributes' => array(
3489
      'type' => 'text/css',
3490
      'rel' => 'stylesheet',
3491
    ),
3492
  );
3493
  $style_element_defaults = array(
3494
    '#type' => 'html_tag',
3495
    '#tag' => 'style',
3496
    '#attributes' => array(
3497
      'type' => 'text/css',
3498
    ),
3499
  );
3500

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

    
3627
  return $elements;
3628
}
3629

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

    
3669
  if (empty($uri) || !file_exists($uri)) {
3670
    // Build aggregate CSS file.
3671
    foreach ($css as $stylesheet) {
3672
      // Only 'file' stylesheets can be aggregated.
3673
      if ($stylesheet['type'] == 'file') {
3674
        $contents = drupal_load_stylesheet($stylesheet['data'], TRUE);
3675

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

    
3686
        _drupal_build_css_path(NULL, $css_base_url . '/');
3687
        // Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
3688
        $data .= preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);
3689
      }
3690
    }
3691

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

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

    
3726
/**
3727
 * Prefixes all paths within a CSS file for drupal_build_css_cache().
3728
 */
3729
function _drupal_build_css_path($matches, $base = NULL) {
3730
  $_base = &drupal_static(__FUNCTION__);
3731
  // Store base path for preg_replace_callback.
3732
  if (isset($base)) {
3733
    $_base = $base;
3734
  }
3735

    
3736
  // Prefix with base and remove '../' segments where possible.
3737
  $path = $_base . $matches[1];
3738
  $last = '';
3739
  while ($path != $last) {
3740
    $last = $path;
3741
    $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
3742
  }
3743
  return 'url(' . $path . ')';
3744
}
3745

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

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

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

    
3798
  // Restore the parent base path as the file and its childen are processed.
3799
  $basepath = $parent_base_path;
3800
  return $content;
3801
}
3802

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

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

    
3859
  // Replaces @import commands with the actual stylesheet content.
3860
  // This happens recursively but omits external files.
3861
  $contents = preg_replace_callback('/@import\s*(?:url\(\s*)?[\'"]?(?![a-z]+:)(?!\/\/)([^\'"\()]+)[\'"]?\s*\)?\s*;/', '_drupal_load_stylesheet', $contents);
3862
  return $contents;
3863
}
3864

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

    
3876
  // Determine the file's directory.
3877
  $directory = dirname($filename);
3878
  // If the file is in the current directory, make sure '.' doesn't appear in
3879
  // the url() path.
3880
  $directory = $directory == '.' ? '' : $directory .'/';
3881

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

    
3888
/**
3889
 * Deletes old cached CSS files.
3890
 */
3891
function drupal_clear_css_cache() {
3892
  variable_del('drupal_css_cache_files');
3893
  file_scan_directory('public://css', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
3894
}
3895

    
3896
/**
3897
 * Callback to delete files modified more than a set time ago.
3898
 */
3899
function drupal_delete_file_if_stale($uri) {
3900
  // Default stale file threshold is 30 days.
3901
  if (REQUEST_TIME - filemtime($uri) > variable_get('drupal_stale_file_threshold', 2592000)) {
3902
    file_unmanaged_delete($uri);
3903
  }
3904
}
3905

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

    
3931
  // Preserve BEM-style double-underscores depending on custom setting.
3932
  if ($allow_css_double_underscores) {
3933
    $filter['__'] = '__';
3934
  }
3935

    
3936
  // By default, we filter using Drupal's coding standards.
3937
  $identifier = strtr($identifier, $filter);
3938

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

    
3949
  return $identifier;
3950
}
3951

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

    
3969
  if (!isset($classes[$class])) {
3970
    $classes[$class] = drupal_clean_css_identifier(drupal_strtolower($class));
3971
  }
3972
  return $classes[$class];
3973
}
3974

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

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

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

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

    
4085
  return $id;
4086
}
4087

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

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

    
4269
  // If the $javascript variable has been reset with drupal_static_reset(),
4270
  // jQuery and related files will have been removed from the list, so set the
4271
  // variable back to FALSE to indicate they have not yet been added.
4272
  if (empty($javascript)) {
4273
    $jquery_added = FALSE;
4274
  }
4275

    
4276
  // Construct the options, taking the defaults into consideration.
4277
  if (isset($options)) {
4278
    if (!is_array($options)) {
4279
      $options = array('type' => $options);
4280
    }
4281
  }
4282
  else {
4283
    $options = array();
4284
  }
4285
  if (isset($options['type']) && $options['type'] == 'setting') {
4286
    $options += array('requires_jquery' => FALSE);
4287
  }
4288
  $options += drupal_js_defaults($data);
4289

    
4290
  // Preprocess can only be set if caching is enabled.
4291
  $options['preprocess'] = $options['cache'] ? $options['preprocess'] : FALSE;
4292

    
4293
  // Tweak the weight so that files of the same weight are included in the
4294
  // order of the calls to drupal_add_js().
4295
  $options['weight'] += count($javascript) / 1000;
4296

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

    
4340
    switch ($options['type']) {
4341
      case 'setting':
4342
        // All JavaScript settings are placed in the header of the page with
4343
        // the library weight so that inline scripts appear afterwards.
4344
        $javascript['settings']['data'][] = $data;
4345
        break;
4346

    
4347
      case 'inline':
4348
        $javascript[] = $options;
4349
        break;
4350

    
4351
      default: // 'file' and 'external'
4352
        // Local and external files must keep their name as the associative key
4353
        // so the same JavaScript file is not added twice.
4354
        $javascript[$options['data']] = $options;
4355
    }
4356
  }
4357
  return $javascript;
4358
}
4359

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

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

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

    
4431
  // Allow modules to alter the JavaScript.
4432
  if (!$skip_alter) {
4433
    drupal_alter('js', $javascript);
4434
  }
4435

    
4436
  // Filter out elements of the given scope.
4437
  $items = array();
4438
  foreach ($javascript as $key => $item) {
4439
    if ($item['scope'] == $scope) {
4440
      $items[$key] = $item;
4441
    }
4442
  }
4443

    
4444
  $output = '';
4445
  // The index counter is used to keep aggregated and non-aggregated files in
4446
  // order by weight.
4447
  $index = 1;
4448
  $processed = array();
4449
  $files = array();
4450
  $preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
4451

    
4452
  // A dummy query-string is added to filenames, to gain control over
4453
  // browser-caching. The string changes on every update or full cache
4454
  // flush, forcing browsers to load a new copy of the files, as the
4455
  // URL changed. Files that should not be cached (see drupal_add_js())
4456
  // get REQUEST_TIME as query-string instead, to enforce reload on every
4457
  // page request.
4458
  $default_query_string = variable_get('css_js_query_string', '0');
4459

    
4460
  // For inline JavaScript to validate as XHTML, all JavaScript containing
4461
  // XHTML needs to be wrapped in CDATA. To make that backwards compatible
4462
  // with HTML 4, we need to comment out the CDATA-tag.
4463
  $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
4464
  $embed_suffix = "\n//--><!]]>\n";
4465

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

    
4470
  // Sort the JavaScript so that it appears in the correct order.
4471
  uasort($items, 'drupal_sort_css_js');
4472

    
4473
  // Provide the page with information about the individual JavaScript files
4474
  // used, information not otherwise available when aggregation is enabled.
4475
  $setting['ajaxPageState']['js'] = array_fill_keys(array_keys($items), 1);
4476
  unset($setting['ajaxPageState']['js']['settings']);
4477
  drupal_add_js($setting, 'setting');
4478

    
4479
  // If we're outputting the header scope, then this might be the final time
4480
  // that drupal_get_js() is running, so add the setting to this output as well
4481
  // as to the drupal_add_js() cache. If $items['settings'] doesn't exist, it's
4482
  // because drupal_get_js() was intentionally passed a $javascript argument
4483
  // stripped off settings, potentially in order to override how settings get
4484
  // output, so in this case, do not add the setting to this output.
4485
  if ($scope == 'header' && isset($items['settings'])) {
4486
    $items['settings']['data'][] = $setting;
4487
  }
4488

    
4489
  // Loop through the JavaScript to construct the rendered output.
4490
  $element = array(
4491
    '#tag' => 'script',
4492
    '#value' => '',
4493
    '#attributes' => array(
4494
      'type' => 'text/javascript',
4495
    ),
4496
  );
4497
  foreach ($items as $item) {
4498
    $query_string =  empty($item['version']) ? $default_query_string : $js_version_string . $item['version'];
4499

    
4500
    switch ($item['type']) {
4501
      case 'setting':
4502
        $js_element = $element;
4503
        $js_element['#value_prefix'] = $embed_prefix;
4504
        $js_element['#value'] = 'jQuery.extend(Drupal.settings, ' . drupal_json_encode(drupal_array_merge_deep_array($item['data'])) . ");";
4505
        $js_element['#value_suffix'] = $embed_suffix;
4506
        $output .= theme('html_tag', array('element' => $js_element));
4507
        break;
4508

    
4509
      case 'inline':
4510
        $js_element = $element;
4511
        if ($item['defer']) {
4512
          $js_element['#attributes']['defer'] = 'defer';
4513
        }
4514
        $js_element['#value_prefix'] = $embed_prefix;
4515
        $js_element['#value'] = $item['data'];
4516
        $js_element['#value_suffix'] = $embed_suffix;
4517
        $processed[$index++] = theme('html_tag', array('element' => $js_element));
4518
        break;
4519

    
4520
      case 'file':
4521
        $js_element = $element;
4522
        if (!$item['preprocess'] || !$preprocess_js) {
4523
          if ($item['defer']) {
4524
            $js_element['#attributes']['defer'] = 'defer';
4525
          }
4526
          $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
4527
          $js_element['#attributes']['src'] = file_create_url($item['data']) . $query_string_separator . ($item['cache'] ? $query_string : REQUEST_TIME);
4528
          $processed[$index++] = theme('html_tag', array('element' => $js_element));
4529
        }
4530
        else {
4531
          // By increasing the index for each aggregated file, we maintain
4532
          // the relative ordering of JS by weight. We also set the key such
4533
          // that groups are split by items sharing the same 'group' value and
4534
          // 'every_page' flag. While this potentially results in more aggregate
4535
          // files, it helps make each one more reusable across a site visit,
4536
          // leading to better front-end performance of a website as a whole.
4537
          // See drupal_add_js() for details.
4538
          $key = 'aggregate_' . $item['group'] . '_' . $item['every_page'] . '_' . $index;
4539
          $processed[$key] = '';
4540
          $files[$key][$item['data']] = $item;
4541
        }
4542
        break;
4543

    
4544
      case 'external':
4545
        $js_element = $element;
4546
        // Preprocessing for external JavaScript files is ignored.
4547
        if ($item['defer']) {
4548
          $js_element['#attributes']['defer'] = 'defer';
4549
        }
4550
        $js_element['#attributes']['src'] = $item['data'];
4551
        $processed[$index++] = theme('html_tag', array('element' => $js_element));
4552
        break;
4553
    }
4554
  }
4555

    
4556
  // Aggregate any remaining JS files that haven't already been output.
4557
  if ($preprocess_js && count($files) > 0) {
4558
    foreach ($files as $key => $file_set) {
4559
      $uri = drupal_build_js_cache($file_set);
4560
      // Only include the file if was written successfully. Errors are logged
4561
      // using watchdog.
4562
      if ($uri) {
4563
        $preprocess_file = file_create_url($uri);
4564
        $js_element = $element;
4565
        $js_element['#attributes']['src'] = $preprocess_file;
4566
        $processed[$key] = theme('html_tag', array('element' => $js_element));
4567
      }
4568
    }
4569
  }
4570

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

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

    
4640
  // Add the libraries first.
4641
  $success = TRUE;
4642
  foreach ($elements['#attached']['library'] as $library) {
4643
    if (drupal_add_library($library[0], $library[1], $every_page) === FALSE) {
4644
      $success = FALSE;
4645
      // Exit if the dependency is missing.
4646
      if ($dependency_check) {
4647
        return $success;
4648
      }
4649
    }
4650
  }
4651
  unset($elements['#attached']['library']);
4652

    
4653
  // Add both the JavaScript and the CSS.
4654
  // The parameters for drupal_add_js() and drupal_add_css() require special
4655
  // handling.
4656
  foreach (array('js', 'css') as $type) {
4657
    foreach ($elements['#attached'][$type] as $data => $options) {
4658
      // If the value is not an array, it's a filename and passed as first
4659
      // (and only) argument.
4660
      if (!is_array($options)) {
4661
        $data = $options;
4662
        $options = NULL;
4663
      }
4664
      // In some cases, the first parameter ($data) is an array. Arrays can't be
4665
      // passed as keys in PHP, so we have to get $data from the value array.
4666
      if (is_numeric($data)) {
4667
        $data = $options['data'];
4668
        unset($options['data']);
4669
      }
4670
      // Apply the default group if it isn't explicitly given.
4671
      if (!isset($options['group'])) {
4672
        $options['group'] = $group;
4673
      }
4674
      // Set the every_page flag if one was passed.
4675
      if (isset($every_page)) {
4676
        $options['every_page'] = $every_page;
4677
      }
4678
      call_user_func('drupal_add_' . $type, $data, $options);
4679
    }
4680
    unset($elements['#attached'][$type]);
4681
  }
4682

    
4683
  // Add additional types of attachments specified in the render() structure.
4684
  // Libraries, JavaScript and CSS have been added already, as they require
4685
  // special handling.
4686
  foreach ($elements['#attached'] as $callback => $options) {
4687
    if (function_exists($callback)) {
4688
      foreach ($elements['#attached'][$callback] as $args) {
4689
        call_user_func_array($callback, $args);
4690
      }
4691
    }
4692
  }
4693

    
4694
  return $success;
4695
}
4696

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

    
4828
/**
4829
 * Adds multiple JavaScript or CSS files at the same time.
4830
 *
4831
 * A library defines a set of JavaScript and/or CSS files, optionally using
4832
 * settings, and optionally requiring another library. For example, a library
4833
 * can be a jQuery plugin, a JavaScript framework, or a CSS framework. This
4834
 * function allows modules to load a library defined/shipped by itself or a
4835
 * depending module, without having to add all files of the library separately.
4836
 * Each library is only loaded once.
4837
 *
4838
 * @param $module
4839
 *   The name of the module that registered the library.
4840
 * @param $name
4841
 *   The name of the library to add.
4842
 * @param $every_page
4843
 *   Set to TRUE if this library is added to every page on the site. Only items
4844
 *   with the every_page flag set to TRUE can participate in aggregation.
4845
 *
4846
 * @return
4847
 *   TRUE if the library was successfully added; FALSE if the library or one of
4848
 *   its dependencies could not be added.
4849
 *
4850
 * @see drupal_get_library()
4851
 * @see hook_library()
4852
 * @see hook_library_alter()
4853
 */
4854
function drupal_add_library($module, $name, $every_page = NULL) {
4855
  $added = &drupal_static(__FUNCTION__, array());
4856

    
4857
  // Only process the library if it exists and it was not added already.
4858
  if (!isset($added[$module][$name])) {
4859
    if ($library = drupal_get_library($module, $name)) {
4860
      // Add all components within the library.
4861
      $elements['#attached'] = array(
4862
        'library' => $library['dependencies'],
4863
        'js' => $library['js'],
4864
        'css' => $library['css'],
4865
      );
4866
      $added[$module][$name] = drupal_process_attached($elements, JS_LIBRARY, TRUE, $every_page);
4867
    }
4868
    else {
4869
      // Requested library does not exist.
4870
      $added[$module][$name] = FALSE;
4871
    }
4872
  }
4873

    
4874
  return $added[$module][$name];
4875
}
4876

    
4877
/**
4878
 * Retrieves information for a JavaScript/CSS library.
4879
 *
4880
 * Library information is statically cached. Libraries are keyed by module for
4881
 * several reasons:
4882
 * - Libraries are not unique. Multiple modules might ship with the same library
4883
 *   in a different version or variant. This registry cannot (and does not
4884
 *   attempt to) prevent library conflicts.
4885
 * - Modules implementing and thereby depending on a library that is registered
4886
 *   by another module can only rely on that module's library.
4887
 * - Two (or more) modules can still register the same library and use it
4888
 *   without conflicts in case the libraries are loaded on certain pages only.
4889
 *
4890
 * @param $module
4891
 *   The name of a module that registered a library.
4892
 * @param $name
4893
 *   (optional) The name of a registered library to retrieve. By default, all
4894
 *   libraries registered by $module are returned.
4895
 *
4896
 * @return
4897
 *   The definition of the requested library, if $name was passed and it exists,
4898
 *   or FALSE if it does not exist. If no $name was passed, an associative array
4899
 *   of libraries registered by $module is returned (which may be empty).
4900
 *
4901
 * @see drupal_add_library()
4902
 * @see hook_library()
4903
 * @see hook_library_alter()
4904
 *
4905
 * @todo The purpose of drupal_get_*() is completely different to other page
4906
 *   requisite API functions; find and use a different name.
4907
 */
4908
function drupal_get_library($module, $name = NULL) {
4909
  $libraries = &drupal_static(__FUNCTION__, array());
4910

    
4911
  if (!isset($libraries[$module])) {
4912
    // Retrieve all libraries associated with the module.
4913
    $module_libraries = module_invoke($module, 'library');
4914
    if (empty($module_libraries)) {
4915
      $module_libraries = array();
4916
    }
4917
    // Allow modules to alter the module's registered libraries.
4918
    drupal_alter('library', $module_libraries, $module);
4919

    
4920
    foreach ($module_libraries as $key => $data) {
4921
      if (is_array($data)) {
4922
        // Add default elements to allow for easier processing.
4923
        $module_libraries[$key] += array('dependencies' => array(), 'js' => array(), 'css' => array());
4924
        foreach ($module_libraries[$key]['js'] as $file => $options) {
4925
          $module_libraries[$key]['js'][$file]['version'] = $module_libraries[$key]['version'];
4926
        }
4927
      }
4928
    }
4929
    $libraries[$module] = $module_libraries;
4930
  }
4931
  if (isset($name)) {
4932
    if (!isset($libraries[$module][$name])) {
4933
      $libraries[$module][$name] = FALSE;
4934
    }
4935
    return $libraries[$module][$name];
4936
  }
4937
  return $libraries[$module];
4938
}
4939

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

    
5058
  // If a subgroup or source isn't set, assume it is the same as the group.
5059
  $target = isset($subgroup) ? $subgroup : $group;
5060
  $source = isset($source) ? $source : $target;
5061
  $settings['tableDrag'][$table_id][$group][] = array(
5062
    'target' => $target,
5063
    'source' => $source,
5064
    'relationship' => $relationship,
5065
    'action' => $action,
5066
    'hidden' => $hidden,
5067
    'limit' => $limit,
5068
  );
5069
  drupal_add_js($settings, 'setting');
5070
}
5071

    
5072
/**
5073
 * Aggregates JavaScript files into a cache file in the files directory.
5074
 *
5075
 * The file name for the JavaScript cache file is generated from the hash of
5076
 * the aggregated contents of the files in $files. This forces proxies and
5077
 * browsers to download new JavaScript when the JavaScript changes.
5078
 *
5079
 * The cache file name is retrieved on a page load via a lookup variable that
5080
 * contains an associative array. The array key is the hash of the names in
5081
 * $files while the value is the cache file name. The cache file is generated
5082
 * in two cases. First, if there is no file name value for the key, which will
5083
 * happen if a new file name has been added to $files or after the lookup
5084
 * variable is emptied to force a rebuild of the cache. Second, the cache file
5085
 * is generated if it is missing on disk. Old cache files are not deleted
5086
 * immediately when the lookup variable is emptied, but are deleted after a set
5087
 * period by drupal_delete_file_if_stale(). This ensures that files referenced
5088
 * by a cached page will still be available.
5089
 *
5090
 * @param $files
5091
 *   An array of JavaScript files to aggregate and compress into one file.
5092
 *
5093
 * @return
5094
 *   The URI of the cache file, or FALSE if the file could not be saved.
5095
 */
5096
function drupal_build_js_cache($files) {
5097
  $contents = '';
5098
  $uri = '';
5099
  $map = variable_get('drupal_js_cache_files', array());
5100
  // Create a new array so that only the file names are used to create the hash.
5101
  // This prevents new aggregates from being created unnecessarily.
5102
  $js_data = array();
5103
  foreach ($files as $file) {
5104
    $js_data[] = $file['data'];
5105
  }
5106
  $key = hash('sha256', serialize($js_data));
5107
  if (isset($map[$key])) {
5108
    $uri = $map[$key];
5109
  }
5110

    
5111
  if (empty($uri) || !file_exists($uri)) {
5112
    // Build aggregate JS file.
5113
    foreach ($files as $path => $info) {
5114
      if ($info['preprocess']) {
5115
        // Append a ';' and a newline after each JS file to prevent them from running together.
5116
        $contents .= file_get_contents($path) . ";\n";
5117
      }
5118
    }
5119
    // Prefix filename to prevent blocking by firewalls which reject files
5120
    // starting with "ad*".
5121
    $filename = 'js_' . drupal_hash_base64($contents) . '.js';
5122
    // Create the js/ within the files folder.
5123
    $jspath = 'public://js';
5124
    $uri = $jspath . '/' . $filename;
5125
    // Create the JS file.
5126
    file_prepare_directory($jspath, FILE_CREATE_DIRECTORY);
5127
    if (!file_exists($uri) && !file_unmanaged_save_data($contents, $uri, FILE_EXISTS_REPLACE)) {
5128
      return FALSE;
5129
    }
5130
    // If JS gzip compression is enabled, clean URLs are enabled (which means
5131
    // that rewrite rules are working) and the zlib extension is available then
5132
    // create a gzipped version of this file. This file is served conditionally
5133
    // to browsers that accept gzip using .htaccess rules.
5134
    if (variable_get('js_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
5135
      if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($contents, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
5136
        return FALSE;
5137
      }
5138
    }
5139
    $map[$key] = $uri;
5140
    variable_set('drupal_js_cache_files', $map);
5141
  }
5142
  return $uri;
5143
}
5144

    
5145
/**
5146
 * Deletes old cached JavaScript files and variables.
5147
 */
5148
function drupal_clear_js_cache() {
5149
  variable_del('javascript_parsed');
5150
  variable_del('drupal_js_cache_files');
5151
  file_scan_directory('public://js', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
5152
}
5153

    
5154
/**
5155
 * Converts a PHP variable into its JavaScript equivalent.
5156
 *
5157
 * We use HTML-safe strings, with several characters escaped.
5158
 *
5159
 * @see drupal_json_decode()
5160
 * @see drupal_json_encode_helper()
5161
 * @ingroup php_wrappers
5162
 */
5163
function drupal_json_encode($var) {
5164
  // The PHP version cannot change within a request.
5165
  static $php530;
5166

    
5167
  if (!isset($php530)) {
5168
    $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
5169
  }
5170

    
5171
  if ($php530) {
5172
    // Encode <, >, ', &, and " using the json_encode() options parameter.
5173
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
5174
  }
5175

    
5176
  // json_encode() escapes <, >, ', &, and " using its options parameter, but
5177
  // does not support this parameter prior to PHP 5.3.0.  Use a helper instead.
5178
  include_once DRUPAL_ROOT . '/includes/json-encode.inc';
5179
  return drupal_json_encode_helper($var);
5180
}
5181

    
5182
/**
5183
 * Converts an HTML-safe JSON string into its PHP equivalent.
5184
 *
5185
 * @see drupal_json_encode()
5186
 * @ingroup php_wrappers
5187
 */
5188
function drupal_json_decode($var) {
5189
  return json_decode($var, TRUE);
5190
}
5191

    
5192
/**
5193
 * Returns data in JSON format.
5194
 *
5195
 * This function should be used for JavaScript callback functions returning
5196
 * data in JSON format. It sets the header for JavaScript output.
5197
 *
5198
 * @param $var
5199
 *   (optional) If set, the variable will be converted to JSON and output.
5200
 */
5201
function drupal_json_output($var = NULL) {
5202
  // We are returning JSON, so tell the browser.
5203
  drupal_add_http_header('Content-Type', 'application/json');
5204

    
5205
  if (isset($var)) {
5206
    echo drupal_json_encode($var);
5207
  }
5208
}
5209

    
5210
/**
5211
 * Ensures the private key variable used to generate tokens is set.
5212
 *
5213
 * @return
5214
 *   The private key.
5215
 */
5216
function drupal_get_private_key() {
5217
  if (!($key = variable_get('drupal_private_key', 0))) {
5218
    $key = drupal_random_key();
5219
    variable_set('drupal_private_key', $key);
5220
  }
5221
  return $key;
5222
}
5223

    
5224
/**
5225
 * Generates a token based on $value, the user session, and the private key.
5226
 *
5227
 * @param $value
5228
 *   An additional value to base the token on.
5229
 *
5230
 * The generated token is based on the session ID of the current user. Normally,
5231
 * anonymous users do not have a session, so the generated token will be
5232
 * different on every page request. To generate a token for users without a
5233
 * session, manually start a session prior to calling this function.
5234
 *
5235
 * @return string
5236
 *   A 43-character URL-safe token for validation, based on the user session ID,
5237
 *   the hash salt provided from drupal_get_hash_salt(), and the
5238
 *   'drupal_private_key' configuration variable.
5239
 *
5240
 * @see drupal_get_hash_salt()
5241
 */
5242
function drupal_get_token($value = '') {
5243
  return drupal_hmac_base64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());
5244
}
5245

    
5246
/**
5247
 * Validates a token based on $value, the user session, and the private key.
5248
 *
5249
 * @param $token
5250
 *   The token to be validated.
5251
 * @param $value
5252
 *   An additional value to base the token on.
5253
 * @param $skip_anonymous
5254
 *   Set to true to skip token validation for anonymous users.
5255
 *
5256
 * @return
5257
 *   True for a valid token, false for an invalid token. When $skip_anonymous
5258
 *   is true, the return value will always be true for anonymous users.
5259
 */
5260
function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
5261
  global $user;
5262
  return (($skip_anonymous && $user->uid == 0) || ($token === drupal_get_token($value)));
5263
}
5264

    
5265
function _drupal_bootstrap_full() {
5266
  static $called = FALSE;
5267

    
5268
  if ($called) {
5269
    return;
5270
  }
5271
  $called = TRUE;
5272
  require_once DRUPAL_ROOT . '/' . variable_get('path_inc', 'includes/path.inc');
5273
  require_once DRUPAL_ROOT . '/includes/theme.inc';
5274
  require_once DRUPAL_ROOT . '/includes/pager.inc';
5275
  require_once DRUPAL_ROOT . '/' . variable_get('menu_inc', 'includes/menu.inc');
5276
  require_once DRUPAL_ROOT . '/includes/tablesort.inc';
5277
  require_once DRUPAL_ROOT . '/includes/file.inc';
5278
  require_once DRUPAL_ROOT . '/includes/unicode.inc';
5279
  require_once DRUPAL_ROOT . '/includes/image.inc';
5280
  require_once DRUPAL_ROOT . '/includes/form.inc';
5281
  require_once DRUPAL_ROOT . '/includes/mail.inc';
5282
  require_once DRUPAL_ROOT . '/includes/actions.inc';
5283
  require_once DRUPAL_ROOT . '/includes/ajax.inc';
5284
  require_once DRUPAL_ROOT . '/includes/token.inc';
5285
  require_once DRUPAL_ROOT . '/includes/errors.inc';
5286

    
5287
  // Detect string handling method
5288
  unicode_check();
5289
  // Undo magic quotes
5290
  fix_gpc_magic();
5291
  // Load all enabled modules
5292
  module_load_all();
5293
  // Reset drupal_alter() and module_implements() static caches as these
5294
  // include implementations for vital modules only when called early on
5295
  // in the bootstrap.
5296
  drupal_static_reset('drupal_alter');
5297
  drupal_static_reset('module_implements');
5298
  // Make sure all stream wrappers are registered.
5299
  file_get_stream_wrappers();
5300
  // Ensure mt_rand is reseeded, to prevent random values from one page load
5301
  // being exploited to predict random values in subsequent page loads.
5302
  $seed = unpack("L", drupal_random_bytes(4));
5303
  mt_srand($seed[1]);
5304

    
5305
  $test_info = &$GLOBALS['drupal_test_info'];
5306
  if (!empty($test_info['in_child_site'])) {
5307
    // Running inside the simpletest child site, log fatal errors to test
5308
    // specific file directory.
5309
    ini_set('log_errors', 1);
5310
    ini_set('error_log', 'public://error.log');
5311
  }
5312

    
5313
  // Initialize $_GET['q'] prior to invoking hook_init().
5314
  drupal_path_initialize();
5315

    
5316
  // Let all modules take action before the menu system handles the request.
5317
  // We do not want this while running update.php.
5318
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
5319
    // Prior to invoking hook_init(), initialize the theme (potentially a custom
5320
    // one for this page), so that:
5321
    // - Modules with hook_init() implementations that call theme() or
5322
    //   theme_get_registry() don't initialize the incorrect theme.
5323
    // - The theme can have hook_*_alter() implementations affect page building
5324
    //   (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
5325
    //   ahead of when rendering starts.
5326
    menu_set_custom_theme();
5327
    drupal_theme_initialize();
5328
    module_invoke_all('init');
5329
  }
5330
}
5331

    
5332
/**
5333
 * Stores the current page in the cache.
5334
 *
5335
 * If page_compression is enabled, a gzipped version of the page is stored in
5336
 * the cache to avoid compressing the output on each request. The cache entry
5337
 * is unzipped in the relatively rare event that the page is requested by a
5338
 * client without gzip support.
5339
 *
5340
 * Page compression requires the PHP zlib extension
5341
 * (http://php.net/manual/ref.zlib.php).
5342
 *
5343
 * @see drupal_page_header()
5344
 */
5345
function drupal_page_set_cache() {
5346
  global $base_root;
5347

    
5348
  if (drupal_page_is_cacheable()) {
5349

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

    
5353
    $cache = (object) array(
5354
      'cid' => $base_root . request_uri(),
5355
      'data' => array(
5356
        'path' => $_GET['q'],
5357
        'body' => ob_get_clean(),
5358
        'title' => drupal_get_title(),
5359
        'headers' => array(),
5360
        // We need to store whether page was compressed or not,
5361
        // because by the time it is read, the configuration might change.
5362
        'page_compressed' => $page_compressed,
5363
      ),
5364
      'expire' => CACHE_TEMPORARY,
5365
      'created' => REQUEST_TIME,
5366
    );
5367

    
5368
    // Restore preferred header names based on the lower-case names returned
5369
    // by drupal_get_http_header().
5370
    $header_names = _drupal_set_preferred_header_name();
5371
    foreach (drupal_get_http_header() as $name_lower => $value) {
5372
      $cache->data['headers'][$header_names[$name_lower]] = $value;
5373
      if ($name_lower == 'expires') {
5374
        // Use the actual timestamp from an Expires header if available.
5375
        $cache->expire = strtotime($value);
5376
      }
5377
    }
5378

    
5379
    if ($cache->data['body']) {
5380
      if ($page_compressed) {
5381
        $cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
5382
      }
5383
      cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire);
5384
    }
5385
    return $cache;
5386
  }
5387
}
5388

    
5389
/**
5390
 * Executes a cron run when called.
5391
 *
5392
 * Do not call this function from a test. Use $this->cronRun() instead.
5393
 *
5394
 * @return bool
5395
 *   TRUE if cron ran successfully and FALSE if cron is already running.
5396
 */
5397
function drupal_cron_run() {
5398
  // Allow execution to continue even if the request gets canceled.
5399
  @ignore_user_abort(TRUE);
5400

    
5401
  // Prevent session information from being saved while cron is running.
5402
  $original_session_saving = drupal_save_session();
5403
  drupal_save_session(FALSE);
5404

    
5405
  // Force the current user to anonymous to ensure consistent permissions on
5406
  // cron runs.
5407
  $original_user = $GLOBALS['user'];
5408
  $GLOBALS['user'] = drupal_anonymous_user();
5409

    
5410
  // Try to allocate enough time to run all the hook_cron implementations.
5411
  drupal_set_time_limit(240);
5412

    
5413
  $return = FALSE;
5414
  // Grab the defined cron queues.
5415
  $queues = module_invoke_all('cron_queue_info');
5416
  drupal_alter('cron_queue_info', $queues);
5417

    
5418
  // Try to acquire cron lock.
5419
  if (!lock_acquire('cron', 240.0)) {
5420
    // Cron is still running normally.
5421
    watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
5422
  }
5423
  else {
5424
    // Make sure every queue exists. There is no harm in trying to recreate an
5425
    // existing queue.
5426
    foreach ($queues as $queue_name => $info) {
5427
      DrupalQueue::get($queue_name)->createQueue();
5428
    }
5429

    
5430
    // Iterate through the modules calling their cron handlers (if any):
5431
    foreach (module_implements('cron') as $module) {
5432
      // Do not let an exception thrown by one module disturb another.
5433
      try {
5434
        module_invoke($module, 'cron');
5435
      }
5436
      catch (Exception $e) {
5437
        watchdog_exception('cron', $e);
5438
      }
5439
    }
5440

    
5441
    // Record cron time.
5442
    variable_set('cron_last', REQUEST_TIME);
5443
    watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
5444

    
5445
    // Release cron lock.
5446
    lock_release('cron');
5447

    
5448
    // Return TRUE so other functions can check if it did run successfully
5449
    $return = TRUE;
5450
  }
5451

    
5452
  foreach ($queues as $queue_name => $info) {
5453
    if (!empty($info['skip on cron'])) {
5454
      // Do not run if queue wants to skip.
5455
      continue;
5456
    }
5457
    $callback = $info['worker callback'];
5458
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
5459
    $queue = DrupalQueue::get($queue_name);
5460
    while (time() < $end && ($item = $queue->claimItem())) {
5461
      try {
5462
        call_user_func($callback, $item->data);
5463
        $queue->deleteItem($item);
5464
      }
5465
      catch (Exception $e) {
5466
        // In case of exception log it and leave the item in the queue
5467
        // to be processed again later.
5468
        watchdog_exception('cron', $e);
5469
      }
5470
    }
5471
  }
5472
  // Restore the user.
5473
  $GLOBALS['user'] = $original_user;
5474
  drupal_save_session($original_session_saving);
5475

    
5476
  return $return;
5477
}
5478

    
5479
/**
5480
 * DEPRECATED: Shutdown function: Performs cron cleanup.
5481
 *
5482
 * This function is deprecated because the 'cron_semaphore' variable it
5483
 * references no longer exists. It is therefore no longer used as a shutdown
5484
 * function by Drupal core.
5485
 *
5486
 * @deprecated
5487
 */
5488
function drupal_cron_cleanup() {
5489
  // See if the semaphore is still locked.
5490
  if (variable_get('cron_semaphore', FALSE)) {
5491
    watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);
5492

    
5493
    // Release cron semaphore.
5494
    variable_del('cron_semaphore');
5495
  }
5496
}
5497

    
5498
/**
5499
 * Returns information about system object files (modules, themes, etc.).
5500
 *
5501
 * This function is used to find all or some system object files (module files,
5502
 * theme files, etc.) that exist on the site. It searches in several locations,
5503
 * depending on what type of object you are looking for. For instance, if you
5504
 * are looking for modules and call:
5505
 * @code
5506
 * drupal_system_listing("/\.module$/", "modules", 'name', 0);
5507
 * @endcode
5508
 * this function will search the site-wide modules directory (i.e., /modules/),
5509
 * your installation profile's directory (i.e.,
5510
 * /profiles/your_site_profile/modules/), the all-sites directory (i.e.,
5511
 * /sites/all/modules/), and your site-specific directory (i.e.,
5512
 * /sites/your_site_dir/modules/), in that order, and return information about
5513
 * all of the files ending in .module in those directories.
5514
 *
5515
 * The information is returned in an associative array, which can be keyed on
5516
 * the file name ($key = 'filename'), the file name without the extension ($key
5517
 * = 'name'), or the full file stream URI ($key = 'uri'). If you use a key of
5518
 * 'filename' or 'name', files found later in the search will take precedence
5519
 * over files found earlier (unless they belong to a module or theme not
5520
 * compatible with Drupal core); if you choose a key of 'uri', you will get all
5521
 * files found.
5522
 *
5523
 * @param string $mask
5524
 *   The preg_match() regular expression for the files to find.
5525
 * @param string $directory
5526
 *   The subdirectory name in which the files are found. For example,
5527
 *   'modules' will search in sub-directories of the top-level /modules
5528
 *   directory, sub-directories of /sites/all/modules/, etc.
5529
 * @param string $key
5530
 *   The key to be used for the associative array returned. Possible values are
5531
 *   'uri', for the file's URI; 'filename', for the basename of the file; and
5532
 *   'name' for the name of the file without the extension. If you choose 'name'
5533
 *   or 'filename', only the highest-precedence file will be returned.
5534
 * @param int $min_depth
5535
 *   Minimum depth of directories to return files from, relative to each
5536
 *   directory searched. For instance, a minimum depth of 2 would find modules
5537
 *   inside /modules/node/tests, but not modules directly in /modules/node.
5538
 *
5539
 * @return array
5540
 *   An associative array of file objects, keyed on the chosen key. Each element
5541
 *   in the array is an object containing file information, with properties:
5542
 *   - 'uri': Full URI of the file.
5543
 *   - 'filename': File name.
5544
 *   - 'name': Name of file without the extension.
5545
 */
5546
function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
5547
  $config = conf_path();
5548

    
5549
  $searchdir = array($directory);
5550
  $files = array();
5551

    
5552
  // The 'profiles' directory contains pristine collections of modules and
5553
  // themes as organized by a distribution. It is pristine in the same way
5554
  // that /modules is pristine for core; users should avoid changing anything
5555
  // there in favor of sites/all or sites/<domain> directories.
5556
  $profiles = array();
5557
  $profile = drupal_get_profile();
5558
  // For SimpleTest to be able to test modules packaged together with a
5559
  // distribution we need to include the profile of the parent site (in which
5560
  // test runs are triggered).
5561
  if (drupal_valid_test_ua()) {
5562
    $testing_profile = variable_get('simpletest_parent_profile', FALSE);
5563
    if ($testing_profile && $testing_profile != $profile) {
5564
      $profiles[] = $testing_profile;
5565
    }
5566
  }
5567
  // In case both profile directories contain the same extension, the actual
5568
  // profile always has precedence.
5569
  $profiles[] = $profile;
5570
  foreach ($profiles as $profile) {
5571
    if (file_exists("profiles/$profile/$directory")) {
5572
      $searchdir[] = "profiles/$profile/$directory";
5573
    }
5574
  }
5575

    
5576
  // Always search sites/all/* as well as the global directories.
5577
  $searchdir[] = 'sites/all/' . $directory;
5578

    
5579
  if (file_exists("$config/$directory")) {
5580
    $searchdir[] = "$config/$directory";
5581
  }
5582

    
5583
  // Get current list of items.
5584
  if (!function_exists('file_scan_directory')) {
5585
    require_once DRUPAL_ROOT . '/includes/file.inc';
5586
  }
5587
  foreach ($searchdir as $dir) {
5588
    $files_to_add = file_scan_directory($dir, $mask, array('key' => $key, 'min_depth' => $min_depth));
5589

    
5590
    // Duplicate files found in later search directories take precedence over
5591
    // earlier ones, so we want them to overwrite keys in our resulting
5592
    // $files array.
5593
    // The exception to this is if the later file is from a module or theme not
5594
    // compatible with Drupal core. This may occur during upgrades of Drupal
5595
    // core when new modules exist in core while older contrib modules with the
5596
    // same name exist in a directory such as sites/all/modules/.
5597
    foreach (array_intersect_key($files_to_add, $files) as $file_key => $file) {
5598
      // If it has no info file, then we just behave liberally and accept the
5599
      // new resource on the list for merging.
5600
      if (file_exists($info_file = dirname($file->uri) . '/' . $file->name . '.info')) {
5601
        // Get the .info file for the module or theme this file belongs to.
5602
        $info = drupal_parse_info_file($info_file);
5603

    
5604
        // If the module or theme is incompatible with Drupal core, remove it
5605
        // from the array for the current search directory, so it is not
5606
        // overwritten when merged with the $files array.
5607
        if (isset($info['core']) && $info['core'] != DRUPAL_CORE_COMPATIBILITY) {
5608
          unset($files_to_add[$file_key]);
5609
        }
5610
      }
5611
    }
5612
    $files = array_merge($files, $files_to_add);
5613
  }
5614

    
5615
  return $files;
5616
}
5617

    
5618
/**
5619
 * Sets the main page content value for later use.
5620
 *
5621
 * Given the nature of the Drupal page handling, this will be called once with
5622
 * a string or array. We store that and return it later as the block is being
5623
 * displayed.
5624
 *
5625
 * @param $content
5626
 *   A string or renderable array representing the body of the page.
5627
 *
5628
 * @return
5629
 *   If called without $content, a renderable array representing the body of
5630
 *   the page.
5631
 */
5632
function drupal_set_page_content($content = NULL) {
5633
  $content_block = &drupal_static(__FUNCTION__, NULL);
5634
  $main_content_display = &drupal_static('system_main_content_added', FALSE);
5635

    
5636
  if (!empty($content)) {
5637
    $content_block = (is_array($content) ? $content : array('main' => array('#markup' => $content)));
5638
  }
5639
  else {
5640
    // Indicate that the main content has been requested. We assume that
5641
    // the module requesting the content will be adding it to the page.
5642
    // A module can indicate that it does not handle the content by setting
5643
    // the static variable back to FALSE after calling this function.
5644
    $main_content_display = TRUE;
5645
    return $content_block;
5646
  }
5647
}
5648

    
5649
/**
5650
 * #pre_render callback to render #browsers into #prefix and #suffix.
5651
 *
5652
 * @param $elements
5653
 *   A render array with a '#browsers' property. The '#browsers' property can
5654
 *   contain any or all of the following keys:
5655
 *   - 'IE': If FALSE, the element is not rendered by Internet Explorer. If
5656
 *     TRUE, the element is rendered by Internet Explorer. Can also be a string
5657
 *     containing an expression for Internet Explorer to evaluate as part of a
5658
 *     conditional comment. For example, this can be set to 'lt IE 7' for the
5659
 *     element to be rendered in Internet Explorer 6, but not in Internet
5660
 *     Explorer 7 or higher. Defaults to TRUE.
5661
 *   - '!IE': If FALSE, the element is not rendered by browsers other than
5662
 *     Internet Explorer. If TRUE, the element is rendered by those browsers.
5663
 *     Defaults to TRUE.
5664
 *   Examples:
5665
 *   - To render an element in all browsers, '#browsers' can be left out or set
5666
 *     to array('IE' => TRUE, '!IE' => TRUE).
5667
 *   - To render an element in Internet Explorer only, '#browsers' can be set
5668
 *     to array('!IE' => FALSE).
5669
 *   - To render an element in Internet Explorer 6 only, '#browsers' can be set
5670
 *     to array('IE' => 'lt IE 7', '!IE' => FALSE).
5671
 *   - To render an element in Internet Explorer 8 and higher and in all other
5672
 *     browsers, '#browsers' can be set to array('IE' => 'gte IE 8').
5673
 *
5674
 * @return
5675
 *   The passed-in element with markup for conditional comments potentially
5676
 *   added to '#prefix' and '#suffix'.
5677
 */
5678
function drupal_pre_render_conditional_comments($elements) {
5679
  $browsers = isset($elements['#browsers']) ? $elements['#browsers'] : array();
5680
  $browsers += array(
5681
    'IE' => TRUE,
5682
    '!IE' => TRUE,
5683
  );
5684

    
5685
  // If rendering in all browsers, no need for conditional comments.
5686
  if ($browsers['IE'] === TRUE && $browsers['!IE']) {
5687
    return $elements;
5688
  }
5689

    
5690
  // Determine the conditional comment expression for Internet Explorer to
5691
  // evaluate.
5692
  if ($browsers['IE'] === TRUE) {
5693
    $expression = 'IE';
5694
  }
5695
  elseif ($browsers['IE'] === FALSE) {
5696
    $expression = '!IE';
5697
  }
5698
  else {
5699
    $expression = $browsers['IE'];
5700
  }
5701

    
5702
  // Wrap the element's potentially existing #prefix and #suffix properties with
5703
  // conditional comment markup. The conditional comment expression is evaluated
5704
  // by Internet Explorer only. To control the rendering by other browsers,
5705
  // either the "downlevel-hidden" or "downlevel-revealed" technique must be
5706
  // used. See http://en.wikipedia.org/wiki/Conditional_comment for details.
5707
  $elements += array(
5708
    '#prefix' => '',
5709
    '#suffix' => '',
5710
  );
5711
  if (!$browsers['!IE']) {
5712
    // "downlevel-hidden".
5713
    $elements['#prefix'] = "\n<!--[if $expression]>\n" . $elements['#prefix'];
5714
    $elements['#suffix'] .= "<![endif]-->\n";
5715
  }
5716
  else {
5717
    // "downlevel-revealed".
5718
    $elements['#prefix'] = "\n<!--[if $expression]><!-->\n" . $elements['#prefix'];
5719
    $elements['#suffix'] .= "<!--<![endif]-->\n";
5720
  }
5721

    
5722
  return $elements;
5723
}
5724

    
5725
/**
5726
 * #pre_render callback to render a link into #markup.
5727
 *
5728
 * Doing so during pre_render gives modules a chance to alter the link parts.
5729
 *
5730
 * @param $elements
5731
 *   A structured array whose keys form the arguments to l():
5732
 *   - #title: The link text to pass as argument to l().
5733
 *   - #href: The URL path component to pass as argument to l().
5734
 *   - #options: (optional) An array of options to pass to l().
5735
 *
5736
 * @return
5737
 *   The passed-in elements containing a rendered link in '#markup'.
5738
 */
5739
function drupal_pre_render_link($element) {
5740
  // By default, link options to pass to l() are normally set in #options.
5741
  $element += array('#options' => array());
5742
  // However, within the scope of renderable elements, #attributes is a valid
5743
  // way to specify attributes, too. Take them into account, but do not override
5744
  // attributes from #options.
5745
  if (isset($element['#attributes'])) {
5746
    $element['#options'] += array('attributes' => array());
5747
    $element['#options']['attributes'] += $element['#attributes'];
5748
  }
5749

    
5750
  // This #pre_render callback can be invoked from inside or outside of a Form
5751
  // API context, and depending on that, a HTML ID may be already set in
5752
  // different locations. #options should have precedence over Form API's #id.
5753
  // #attributes have been taken over into #options above already.
5754
  if (isset($element['#options']['attributes']['id'])) {
5755
    $element['#id'] = $element['#options']['attributes']['id'];
5756
  }
5757
  elseif (isset($element['#id'])) {
5758
    $element['#options']['attributes']['id'] = $element['#id'];
5759
  }
5760

    
5761
  // Conditionally invoke ajax_pre_render_element(), if #ajax is set.
5762
  if (isset($element['#ajax']) && !isset($element['#ajax_processed'])) {
5763
    // If no HTML ID was found above, automatically create one.
5764
    if (!isset($element['#id'])) {
5765
      $element['#id'] = $element['#options']['attributes']['id'] = drupal_html_id('ajax-link');
5766
    }
5767
    // If #ajax['path] was not specified, use the href as Ajax request URL.
5768
    if (!isset($element['#ajax']['path'])) {
5769
      $element['#ajax']['path'] = $element['#href'];
5770
      $element['#ajax']['options'] = $element['#options'];
5771
    }
5772
    $element = ajax_pre_render_element($element);
5773
  }
5774

    
5775
  $element['#markup'] = l($element['#title'], $element['#href'], $element['#options']);
5776
  return $element;
5777
}
5778

    
5779
/**
5780
 * #pre_render callback that collects child links into a single array.
5781
 *
5782
 * This function can be added as a pre_render callback for a renderable array,
5783
 * usually one which will be themed by theme_links(). It iterates through all
5784
 * unrendered children of the element, collects any #links properties it finds,
5785
 * merges them into the parent element's #links array, and prevents those
5786
 * children from being rendered separately.
5787
 *
5788
 * The purpose of this is to allow links to be logically grouped into related
5789
 * categories, so that each child group can be rendered as its own list of
5790
 * links if drupal_render() is called on it, but calling drupal_render() on the
5791
 * parent element will still produce a single list containing all the remaining
5792
 * links, regardless of what group they were in.
5793
 *
5794
 * A typical example comes from node links, which are stored in a renderable
5795
 * array similar to this:
5796
 * @code
5797
 * $node->content['links'] = array(
5798
 *   '#theme' => 'links__node',
5799
 *   '#pre_render' => array('drupal_pre_render_links'),
5800
 *   'comment' => array(
5801
 *     '#theme' => 'links__node__comment',
5802
 *     '#links' => array(
5803
 *       // An array of links associated with node comments, suitable for
5804
 *       // passing in to theme_links().
5805
 *     ),
5806
 *   ),
5807
 *   'statistics' => array(
5808
 *     '#theme' => 'links__node__statistics',
5809
 *     '#links' => array(
5810
 *       // An array of links associated with node statistics, suitable for
5811
 *       // passing in to theme_links().
5812
 *     ),
5813
 *   ),
5814
 *   'translation' => array(
5815
 *     '#theme' => 'links__node__translation',
5816
 *     '#links' => array(
5817
 *       // An array of links associated with node translation, suitable for
5818
 *       // passing in to theme_links().
5819
 *     ),
5820
 *   ),
5821
 * );
5822
 * @endcode
5823
 *
5824
 * In this example, the links are grouped by functionality, which can be
5825
 * helpful to themers who want to display certain kinds of links independently.
5826
 * For example, adding this code to node.tpl.php will result in the comment
5827
 * links being rendered as a single list:
5828
 * @code
5829
 * print render($content['links']['comment']);
5830
 * @endcode
5831
 *
5832
 * (where $node->content has been transformed into $content before handing
5833
 * control to the node.tpl.php template).
5834
 *
5835
 * The pre_render function defined here allows the above flexibility, but also
5836
 * allows the following code to be used to render all remaining links into a
5837
 * single list, regardless of their group:
5838
 * @code
5839
 * print render($content['links']);
5840
 * @endcode
5841
 *
5842
 * In the above example, this will result in the statistics and translation
5843
 * links being rendered together in a single list (but not the comment links,
5844
 * which were rendered previously on their own).
5845
 *
5846
 * Because of the way this function works, the individual properties of each
5847
 * group (for example, a group-specific #theme property such as
5848
 * 'links__node__comment' in the example above, or any other property such as
5849
 * #attributes or #pre_render that is attached to it) are only used when that
5850
 * group is rendered on its own. When the group is rendered together with other
5851
 * children, these child-specific properties are ignored, and only the overall
5852
 * properties of the parent are used.
5853
 */
5854
function drupal_pre_render_links($element) {
5855
  $element += array('#links' => array());
5856
  foreach (element_children($element) as $key) {
5857
    $child = &$element[$key];
5858
    // If the child has links which have not been printed yet and the user has
5859
    // access to it, merge its links in to the parent.
5860
    if (isset($child['#links']) && empty($child['#printed']) && (!isset($child['#access']) || $child['#access'])) {
5861
      $element['#links'] += $child['#links'];
5862
      // Mark the child as having been printed already (so that its links
5863
      // cannot be mistakenly rendered twice).
5864
      $child['#printed'] = TRUE;
5865
    }
5866
  }
5867
  return $element;
5868
}
5869

    
5870
/**
5871
 * #pre_render callback to append contents in #markup to #children.
5872
 *
5873
 * This needs to be a #pre_render callback, because eventually assigned
5874
 * #theme_wrappers will expect the element's rendered content in #children.
5875
 * Note that if also a #theme is defined for the element, then the result of
5876
 * the theme callback will override #children.
5877
 *
5878
 * @param $elements
5879
 *   A structured array using the #markup key.
5880
 *
5881
 * @return
5882
 *   The passed-in elements, but #markup appended to #children.
5883
 *
5884
 * @see drupal_render()
5885
 */
5886
function drupal_pre_render_markup($elements) {
5887
  $elements['#children'] = $elements['#markup'];
5888
  return $elements;
5889
}
5890

    
5891
/**
5892
 * Renders the page, including all theming.
5893
 *
5894
 * @param $page
5895
 *   A string or array representing the content of a page. The array consists of
5896
 *   the following keys:
5897
 *   - #type: Value is always 'page'. This pushes the theming through
5898
 *     page.tpl.php (required).
5899
 *   - #show_messages: Suppress drupal_get_message() items. Used by Batch
5900
 *     API (optional).
5901
 *
5902
 * @see hook_page_alter()
5903
 * @see element_info()
5904
 */
5905
function drupal_render_page($page) {
5906
  $main_content_display = &drupal_static('system_main_content_added', FALSE);
5907

    
5908
  // Allow menu callbacks to return strings or arbitrary arrays to render.
5909
  // If the array returned is not of #type page directly, we need to fill
5910
  // in the page with defaults.
5911
  if (is_string($page) || (is_array($page) && (!isset($page['#type']) || ($page['#type'] != 'page')))) {
5912
    drupal_set_page_content($page);
5913
    $page = element_info('page');
5914
  }
5915

    
5916
  // Modules can add elements to $page as needed in hook_page_build().
5917
  foreach (module_implements('page_build') as $module) {
5918
    $function = $module . '_page_build';
5919
    $function($page);
5920
  }
5921
  // Modules alter the $page as needed. Blocks are populated into regions like
5922
  // 'sidebar_first', 'footer', etc.
5923
  drupal_alter('page', $page);
5924

    
5925
  // If no module has taken care of the main content, add it to the page now.
5926
  // This allows the site to still be usable even if no modules that
5927
  // control page regions (for example, the Block module) are enabled.
5928
  if (!$main_content_display) {
5929
    $page['content']['system_main'] = drupal_set_page_content();
5930
  }
5931

    
5932
  return drupal_render($page);
5933
}
5934

    
5935
/**
5936
 * Renders HTML given a structured array tree.
5937
 *
5938
 * Recursively iterates over each of the array elements, generating HTML code.
5939
 *
5940
 * Renderable arrays have two kinds of key/value pairs: properties and
5941
 * children. Properties have keys starting with '#' and their values influence
5942
 * how the array will be rendered. Children are all elements whose keys do not
5943
 * start with a '#'. Their values should be renderable arrays themselves,
5944
 * which will be rendered during the rendering of the parent array. The markup
5945
 * provided by the children is typically inserted into the markup generated by
5946
 * the parent array.
5947
 *
5948
 * HTML generation for a renderable array, and the treatment of any children,
5949
 * is controlled by two properties containing theme functions, #theme and
5950
 * #theme_wrappers.
5951
 *
5952
 * #theme is the theme function called first. If it is set and the element has
5953
 * any children, it is the responsibility of the theme function to render
5954
 * these children. For elements that are not allowed to have any children,
5955
 * e.g. buttons or textfields, the theme function can be used to render the
5956
 * element itself. If #theme is not present and the element has children, each
5957
 * child is itself rendered by a call to drupal_render(), and the results are
5958
 * concatenated.
5959
 *
5960
 * The #theme_wrappers property contains an array of theme functions which will
5961
 * be called, in order, after #theme has run. These can be used to add further
5962
 * markup around the rendered children; e.g., fieldsets add the required markup
5963
 * for a fieldset around their rendered child elements. All wrapper theme
5964
 * functions have to include the element's #children property in their output,
5965
 * as it contains the output of the previous theme functions and the rendered
5966
 * children.
5967
 *
5968
 * For example, for the form element type, by default only the #theme_wrappers
5969
 * property is set, which adds the form markup around the rendered child
5970
 * elements of the form. This allows you to set the #theme property on a
5971
 * specific form to a custom theme function, giving you complete control over
5972
 * the placement of the form's children while not at all having to deal with
5973
 * the form markup itself.
5974
 *
5975
 * drupal_render() can optionally cache the rendered output of elements to
5976
 * improve performance. To use drupal_render() caching, set the element's #cache
5977
 * property to an associative array with one or several of the following keys:
5978
 * - 'keys': An array of one or more keys that identify the element. If 'keys'
5979
 *   is set, the cache ID is created automatically from these keys. See
5980
 *   drupal_render_cid_create().
5981
 * - 'granularity' (optional): Define the cache granularity using binary
5982
 *   combinations of the cache granularity constants, e.g.
5983
 *   DRUPAL_CACHE_PER_USER to cache for each user separately or
5984
 *   DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE to cache separately for each
5985
 *   page and role. If not specified the element is cached globally for each
5986
 *   theme and language.
5987
 * - 'cid': Specify the cache ID directly. Either 'keys' or 'cid' is required.
5988
 *   If 'cid' is set, 'keys' and 'granularity' are ignored. Use only if you
5989
 *   have special requirements.
5990
 * - 'expire': Set to one of the cache lifetime constants.
5991
 * - 'bin': Specify a cache bin to cache the element in. Defaults to 'cache'.
5992
 *
5993
 * This function is usually called from within another function, like
5994
 * drupal_get_form() or a theme function. Elements are sorted internally
5995
 * using uasort(). Since this is expensive, when passing already sorted
5996
 * elements to drupal_render(), for example from a database query, set
5997
 * $elements['#sorted'] = TRUE to avoid sorting them a second time.
5998
 *
5999
 * drupal_render() flags each element with a '#printed' status to indicate that
6000
 * the element has been rendered, which allows individual elements of a given
6001
 * array to be rendered independently and prevents them from being rendered
6002
 * more than once on subsequent calls to drupal_render() (e.g., as part of a
6003
 * larger array). If the same array or array element is passed more than once
6004
 * to drupal_render(), it simply returns an empty string.
6005
 *
6006
 * @param array $elements
6007
 *   The structured array describing the data to be rendered.
6008
 *
6009
 * @return string
6010
 *   The rendered HTML.
6011
 */
6012
function drupal_render(&$elements) {
6013
  // Early-return nothing if user does not have access.
6014
  if (empty($elements) || (isset($elements['#access']) && !$elements['#access'])) {
6015
    return '';
6016
  }
6017

    
6018
  // Do not print elements twice.
6019
  if (!empty($elements['#printed'])) {
6020
    return '';
6021
  }
6022

    
6023
  // Try to fetch the element's markup from cache and return.
6024
  if (isset($elements['#cache'])) {
6025
    $cached_output = drupal_render_cache_get($elements);
6026
    if ($cached_output !== FALSE) {
6027
      return $cached_output;
6028
    }
6029
  }
6030

    
6031
  // If #markup is set, ensure #type is set. This allows to specify just #markup
6032
  // on an element without setting #type.
6033
  if (isset($elements['#markup']) && !isset($elements['#type'])) {
6034
    $elements['#type'] = 'markup';
6035
  }
6036

    
6037
  // If the default values for this element have not been loaded yet, populate
6038
  // them.
6039
  if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
6040
    $elements += element_info($elements['#type']);
6041
  }
6042

    
6043
  // Make any final changes to the element before it is rendered. This means
6044
  // that the $element or the children can be altered or corrected before the
6045
  // element is rendered into the final text.
6046
  if (isset($elements['#pre_render'])) {
6047
    foreach ($elements['#pre_render'] as $function) {
6048
      if (function_exists($function)) {
6049
        $elements = $function($elements);
6050
      }
6051
    }
6052
  }
6053

    
6054
  // Allow #pre_render to abort rendering.
6055
  if (!empty($elements['#printed'])) {
6056
    return '';
6057
  }
6058

    
6059
  // Get the children of the element, sorted by weight.
6060
  $children = element_children($elements, TRUE);
6061

    
6062
  // Initialize this element's #children, unless a #pre_render callback already
6063
  // preset #children.
6064
  if (!isset($elements['#children'])) {
6065
    $elements['#children'] = '';
6066
  }
6067
  // Call the element's #theme function if it is set. Then any children of the
6068
  // element have to be rendered there.
6069
  if (isset($elements['#theme'])) {
6070
    $elements['#children'] = theme($elements['#theme'], $elements);
6071
  }
6072
  // If #theme was not set and the element has children, render them now.
6073
  // This is the same process as drupal_render_children() but is inlined
6074
  // for speed.
6075
  if ($elements['#children'] == '') {
6076
    foreach ($children as $key) {
6077
      $elements['#children'] .= drupal_render($elements[$key]);
6078
    }
6079
  }
6080

    
6081
  // Let the theme functions in #theme_wrappers add markup around the rendered
6082
  // children.
6083
  if (isset($elements['#theme_wrappers'])) {
6084
    foreach ($elements['#theme_wrappers'] as $theme_wrapper) {
6085
      $elements['#children'] = theme($theme_wrapper, $elements);
6086
    }
6087
  }
6088

    
6089
  // Filter the outputted content and make any last changes before the
6090
  // content is sent to the browser. The changes are made on $content
6091
  // which allows the output'ed text to be filtered.
6092
  if (isset($elements['#post_render'])) {
6093
    foreach ($elements['#post_render'] as $function) {
6094
      if (function_exists($function)) {
6095
        $elements['#children'] = $function($elements['#children'], $elements);
6096
      }
6097
    }
6098
  }
6099

    
6100
  // Add any JavaScript state information associated with the element.
6101
  if (!empty($elements['#states'])) {
6102
    drupal_process_states($elements);
6103
  }
6104

    
6105
  // Add additional libraries, CSS, JavaScript an other custom
6106
  // attached data associated with this element.
6107
  if (!empty($elements['#attached'])) {
6108
    drupal_process_attached($elements);
6109
  }
6110

    
6111
  $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
6112
  $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
6113
  $output = $prefix . $elements['#children'] . $suffix;
6114

    
6115
  // Cache the processed element if #cache is set.
6116
  if (isset($elements['#cache'])) {
6117
    drupal_render_cache_set($output, $elements);
6118
  }
6119

    
6120
  $elements['#printed'] = TRUE;
6121
  return $output;
6122
}
6123

    
6124
/**
6125
 * Renders children of an element and concatenates them.
6126
 *
6127
 * @param array $element
6128
 *   The structured array whose children shall be rendered.
6129
 * @param array $children_keys
6130
 *   (optional) If the keys of the element's children are already known, they
6131
 *   can be passed in to save another run of element_children().
6132
 *
6133
 * @return string
6134
 *   The rendered HTML of all children of the element.
6135

    
6136
 * @see drupal_render()
6137
 */
6138
function drupal_render_children(&$element, $children_keys = NULL) {
6139
  if ($children_keys === NULL) {
6140
    $children_keys = element_children($element);
6141
  }
6142
  $output = '';
6143
  foreach ($children_keys as $key) {
6144
    if (!empty($element[$key])) {
6145
      $output .= drupal_render($element[$key]);
6146
    }
6147
  }
6148
  return $output;
6149
}
6150

    
6151
/**
6152
 * Renders an element.
6153
 *
6154
 * This function renders an element using drupal_render(). The top level
6155
 * element is shown with show() before rendering, so it will always be rendered
6156
 * even if hide() had been previously used on it.
6157
 *
6158
 * @param $element
6159
 *   The element to be rendered.
6160
 *
6161
 * @return
6162
 *   The rendered element.
6163
 *
6164
 * @see drupal_render()
6165
 * @see show()
6166
 * @see hide()
6167
 */
6168
function render(&$element) {
6169
  if (is_array($element)) {
6170
    show($element);
6171
    return drupal_render($element);
6172
  }
6173
  else {
6174
    // Safe-guard for inappropriate use of render() on flat variables: return
6175
    // the variable as-is.
6176
    return $element;
6177
  }
6178
}
6179

    
6180
/**
6181
 * Hides an element from later rendering.
6182
 *
6183
 * The first time render() or drupal_render() is called on an element tree,
6184
 * as each element in the tree is rendered, it is marked with a #printed flag
6185
 * and the rendered children of the element are cached. Subsequent calls to
6186
 * render() or drupal_render() will not traverse the child tree of this element
6187
 * again: they will just use the cached children. So if you want to hide an
6188
 * element, be sure to call hide() on the element before its parent tree is
6189
 * rendered for the first time, as it will have no effect on subsequent
6190
 * renderings of the parent tree.
6191
 *
6192
 * @param $element
6193
 *   The element to be hidden.
6194
 *
6195
 * @return
6196
 *   The element.
6197
 *
6198
 * @see render()
6199
 * @see show()
6200
 */
6201
function hide(&$element) {
6202
  $element['#printed'] = TRUE;
6203
  return $element;
6204
}
6205

    
6206
/**
6207
 * Shows a hidden element for later rendering.
6208
 *
6209
 * You can also use render($element), which shows the element while rendering
6210
 * it.
6211
 *
6212
 * The first time render() or drupal_render() is called on an element tree,
6213
 * as each element in the tree is rendered, it is marked with a #printed flag
6214
 * and the rendered children of the element are cached. Subsequent calls to
6215
 * render() or drupal_render() will not traverse the child tree of this element
6216
 * again: they will just use the cached children. So if you want to show an
6217
 * element, be sure to call show() on the element before its parent tree is
6218
 * rendered for the first time, as it will have no effect on subsequent
6219
 * renderings of the parent tree.
6220
 *
6221
 * @param $element
6222
 *   The element to be shown.
6223
 *
6224
 * @return
6225
 *   The element.
6226
 *
6227
 * @see render()
6228
 * @see hide()
6229
 */
6230
function show(&$element) {
6231
  $element['#printed'] = FALSE;
6232
  return $element;
6233
}
6234

    
6235
/**
6236
 * Gets the rendered output of a renderable element from the cache.
6237
 *
6238
 * @param $elements
6239
 *   A renderable array.
6240
 *
6241
 * @return
6242
 *   A markup string containing the rendered content of the element, or FALSE
6243
 *   if no cached copy of the element is available.
6244
 *
6245
 * @see drupal_render()
6246
 * @see drupal_render_cache_set()
6247
 */
6248
function drupal_render_cache_get($elements) {
6249
  if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
6250
    return FALSE;
6251
  }
6252
  $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
6253

    
6254
  if (!empty($cid) && $cache = cache_get($cid, $bin)) {
6255
    // Add additional libraries, JavaScript, CSS and other data attached
6256
    // to this element.
6257
    if (isset($cache->data['#attached'])) {
6258
      drupal_process_attached($cache->data);
6259
    }
6260
    // Return the rendered output.
6261
    return $cache->data['#markup'];
6262
  }
6263
  return FALSE;
6264
}
6265

    
6266
/**
6267
 * Caches the rendered output of a renderable element.
6268
 *
6269
 * This is called by drupal_render() if the #cache property is set on an
6270
 * element.
6271
 *
6272
 * @param $markup
6273
 *   The rendered output string of $elements.
6274
 * @param $elements
6275
 *   A renderable array.
6276
 *
6277
 * @see drupal_render_cache_get()
6278
 */
6279
function drupal_render_cache_set(&$markup, $elements) {
6280
  // Create the cache ID for the element.
6281
  if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
6282
    return FALSE;
6283
  }
6284

    
6285
  // Cache implementations are allowed to modify the markup, to support
6286
  // replacing markup with edge-side include commands. The supporting cache
6287
  // backend will store the markup in some other key (like
6288
  // $data['#real-value']) and return an include command instead. When the
6289
  // ESI command is executed by the content accelerator, the real value can
6290
  // be retrieved and used.
6291
  $data['#markup'] = &$markup;
6292
  // Persist attached data associated with this element.
6293
  $attached = drupal_render_collect_attached($elements, TRUE);
6294
  if ($attached) {
6295
    $data['#attached'] = $attached;
6296
  }
6297
  $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
6298
  $expire = isset($elements['#cache']['expire']) ? $elements['#cache']['expire'] : CACHE_PERMANENT;
6299
  cache_set($cid, $data, $bin, $expire);
6300
}
6301

    
6302
/**
6303
 * Collects #attached for an element and its children into a single array.
6304
 *
6305
 * When caching elements, it is necessary to collect all libraries, JavaScript
6306
 * and CSS into a single array, from both the element itself and all child
6307
 * elements. This allows drupal_render() to add these back to the page when the
6308
 * element is returned from cache.
6309
 *
6310
 * @param $elements
6311
 *   The element to collect #attached from.
6312
 * @param $return
6313
 *   Whether to return the attached elements and reset the internal static.
6314
 *
6315
 * @return
6316
 *   The #attached array for this element and its descendants.
6317
 */
6318
function drupal_render_collect_attached($elements, $return = FALSE) {
6319
  $attached = &drupal_static(__FUNCTION__, array());
6320

    
6321
  // Collect all #attached for this element.
6322
  if (isset($elements['#attached'])) {
6323
    foreach ($elements['#attached'] as $key => $value) {
6324
      if (!isset($attached[$key])) {
6325
        $attached[$key] = array();
6326
      }
6327
      $attached[$key] = array_merge($attached[$key], $value);
6328
    }
6329
  }
6330
  if ($children = element_children($elements)) {
6331
    foreach ($children as $child) {
6332
      drupal_render_collect_attached($elements[$child]);
6333
    }
6334
  }
6335

    
6336
  // If this was the first call to the function, return all attached elements
6337
  // and reset the static cache.
6338
  if ($return) {
6339
    $return = $attached;
6340
    $attached = array();
6341
    return $return;
6342
  }
6343
}
6344

    
6345
/**
6346
 * Prepares an element for caching based on a query.
6347
 *
6348
 * This smart caching strategy saves Drupal from querying and rendering to HTML
6349
 * when the underlying query is unchanged.
6350
 *
6351
 * Expensive queries should use the query builder to create the query and then
6352
 * call this function. Executing the query and formatting results should happen
6353
 * in a #pre_render callback.
6354
 *
6355
 * @param $query
6356
 *   A select query object as returned by db_select().
6357
 * @param $function
6358
 *   The name of the function doing this caching. A _pre_render suffix will be
6359
 *   added to this string and is also part of the cache key in
6360
 *   drupal_render_cache_set() and drupal_render_cache_get().
6361
 * @param $expire
6362
 *   The cache expire time, passed eventually to cache_set().
6363
 * @param $granularity
6364
 *   One or more granularity constants passed to drupal_render_cid_parts().
6365
 *
6366
 * @return
6367
 *   A renderable array with the following keys and values:
6368
 *   - #query: The passed-in $query.
6369
 *   - #pre_render: $function with a _pre_render suffix.
6370
 *   - #cache: An associative array prepared for drupal_render_cache_set().
6371
 */
6372
function drupal_render_cache_by_query($query, $function, $expire = CACHE_TEMPORARY, $granularity = NULL) {
6373
  $cache_keys = array_merge(array($function), drupal_render_cid_parts($granularity));
6374
  $query->preExecute();
6375
  $cache_keys[] = hash('sha256', serialize(array((string) $query, $query->getArguments())));
6376
  return array(
6377
    '#query' => $query,
6378
    '#pre_render' => array($function . '_pre_render'),
6379
    '#cache' => array(
6380
      'keys' => $cache_keys,
6381
      'expire' => $expire,
6382
    ),
6383
  );
6384
}
6385

    
6386
/**
6387
 * Returns cache ID parts for building a cache ID.
6388
 *
6389
 * @param $granularity
6390
 *   One or more cache granularity constants. For example, to cache separately
6391
 *   for each user, use DRUPAL_CACHE_PER_USER. To cache separately for each
6392
 *   page and role, use the expression:
6393
 *   @code
6394
 *   DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE
6395
 *   @endcode
6396
 *
6397
 * @return
6398
 *   An array of cache ID parts, always containing the active theme. If the
6399
 *   locale module is enabled it also contains the active language. If
6400
 *   $granularity was passed in, more parts are added.
6401
 */
6402
function drupal_render_cid_parts($granularity = NULL) {
6403
  global $theme, $base_root, $user;
6404

    
6405
  $cid_parts[] = $theme;
6406
  // If Locale is enabled but we have only one language we do not need it as cid
6407
  // part.
6408
  if (drupal_multilingual()) {
6409
    foreach (language_types_configurable() as $language_type) {
6410
      $cid_parts[] = $GLOBALS[$language_type]->language;
6411
    }
6412
  }
6413

    
6414
  if (!empty($granularity)) {
6415
    $cache_per_role = $granularity & DRUPAL_CACHE_PER_ROLE;
6416
    $cache_per_user = $granularity & DRUPAL_CACHE_PER_USER;
6417
    // User 1 has special permissions outside of the role system, so when
6418
    // caching per role is requested, it should cache per user instead.
6419
    if ($user->uid == 1 && $cache_per_role) {
6420
      $cache_per_user = TRUE;
6421
      $cache_per_role = FALSE;
6422
    }
6423
    // 'PER_ROLE' and 'PER_USER' are mutually exclusive. 'PER_USER' can be a
6424
    // resource drag for sites with many users, so when a module is being
6425
    // equivocal, we favor the less expensive 'PER_ROLE' pattern.
6426
    if ($cache_per_role) {
6427
      $cid_parts[] = 'r.' . implode(',', array_keys($user->roles));
6428
    }
6429
    elseif ($cache_per_user) {
6430
      $cid_parts[] = "u.$user->uid";
6431
    }
6432

    
6433
    if ($granularity & DRUPAL_CACHE_PER_PAGE) {
6434
      $cid_parts[] = $base_root . request_uri();
6435
    }
6436
  }
6437

    
6438
  return $cid_parts;
6439
}
6440

    
6441
/**
6442
 * Creates the cache ID for a renderable element.
6443
 *
6444
 * This creates the cache ID string, either by returning the #cache['cid']
6445
 * property if present or by building the cache ID out of the #cache['keys']
6446
 * and, optionally, the #cache['granularity'] properties.
6447
 *
6448
 * @param $elements
6449
 *   A renderable array.
6450
 *
6451
 * @return
6452
 *   The cache ID string, or FALSE if the element may not be cached.
6453
 */
6454
function drupal_render_cid_create($elements) {
6455
  if (isset($elements['#cache']['cid'])) {
6456
    return $elements['#cache']['cid'];
6457
  }
6458
  elseif (isset($elements['#cache']['keys'])) {
6459
    $granularity = isset($elements['#cache']['granularity']) ? $elements['#cache']['granularity'] : NULL;
6460
    // Merge in additional cache ID parts based provided by drupal_render_cid_parts().
6461
    $cid_parts = array_merge($elements['#cache']['keys'], drupal_render_cid_parts($granularity));
6462
    return implode(':', $cid_parts);
6463
  }
6464
  return FALSE;
6465
}
6466

    
6467
/**
6468
 * Function used by uasort to sort structured arrays by weight.
6469
 */
6470
function element_sort($a, $b) {
6471
  $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
6472
  $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
6473
  if ($a_weight == $b_weight) {
6474
    return 0;
6475
  }
6476
  return ($a_weight < $b_weight) ? -1 : 1;
6477
}
6478

    
6479
/**
6480
 * Array sorting callback; sorts elements by title.
6481
 */
6482
function element_sort_by_title($a, $b) {
6483
  $a_title = (is_array($a) && isset($a['#title'])) ? $a['#title'] : '';
6484
  $b_title = (is_array($b) && isset($b['#title'])) ? $b['#title'] : '';
6485
  return strnatcasecmp($a_title, $b_title);
6486
}
6487

    
6488
/**
6489
 * Retrieves the default properties for the defined element type.
6490
 *
6491
 * @param $type
6492
 *   An element type as defined by hook_element_info().
6493
 */
6494
function element_info($type) {
6495
  // Use the advanced drupal_static() pattern, since this is called very often.
6496
  static $drupal_static_fast;
6497
  if (!isset($drupal_static_fast)) {
6498
    $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__);
6499
  }
6500
  $cache = &$drupal_static_fast['cache'];
6501

    
6502
  if (!isset($cache)) {
6503
    $cache = module_invoke_all('element_info');
6504
    foreach ($cache as $element_type => $info) {
6505
      $cache[$element_type]['#type'] = $element_type;
6506
    }
6507
    // Allow modules to alter the element type defaults.
6508
    drupal_alter('element_info', $cache);
6509
  }
6510

    
6511
  return isset($cache[$type]) ? $cache[$type] : array();
6512
}
6513

    
6514
/**
6515
 * Retrieves a single property for the defined element type.
6516
 *
6517
 * @param $type
6518
 *   An element type as defined by hook_element_info().
6519
 * @param $property_name
6520
 *   The property within the element type that should be returned.
6521
 * @param $default
6522
 *   (Optional) The value to return if the element type does not specify a
6523
 *   value for the property. Defaults to NULL.
6524
 */
6525
function element_info_property($type, $property_name, $default = NULL) {
6526
  return (($info = element_info($type)) && array_key_exists($property_name, $info)) ? $info[$property_name] : $default;
6527
}
6528

    
6529
/**
6530
 * Sorts a structured array by the 'weight' element.
6531
 *
6532
 * Note that the sorting is by the 'weight' array element, not by the render
6533
 * element property '#weight'.
6534
 *
6535
 * Callback for uasort() used in various functions.
6536
 *
6537
 * @param $a
6538
 *   First item for comparison. The compared items should be associative arrays
6539
 *   that optionally include a 'weight' element. For items without a 'weight'
6540
 *   element, a default value of 0 will be used.
6541
 * @param $b
6542
 *   Second item for comparison.
6543
 */
6544
function drupal_sort_weight($a, $b) {
6545
  $a_weight = (is_array($a) && isset($a['weight'])) ? $a['weight'] : 0;
6546
  $b_weight = (is_array($b) && isset($b['weight'])) ? $b['weight'] : 0;
6547
  if ($a_weight == $b_weight) {
6548
    return 0;
6549
  }
6550
  return ($a_weight < $b_weight) ? -1 : 1;
6551
}
6552

    
6553
/**
6554
 * Array sorting callback; sorts elements by 'title' key.
6555
 */
6556
function drupal_sort_title($a, $b) {
6557
  if (!isset($b['title'])) {
6558
    return -1;
6559
  }
6560
  if (!isset($a['title'])) {
6561
    return 1;
6562
  }
6563
  return strcasecmp($a['title'], $b['title']);
6564
}
6565

    
6566
/**
6567
 * Checks if the key is a property.
6568
 */
6569
function element_property($key) {
6570
  return $key[0] == '#';
6571
}
6572

    
6573
/**
6574
 * Gets properties of a structured array element (keys beginning with '#').
6575
 */
6576
function element_properties($element) {
6577
  return array_filter(array_keys((array) $element), 'element_property');
6578
}
6579

    
6580
/**
6581
 * Checks if the key is a child.
6582
 */
6583
function element_child($key) {
6584
  return !isset($key[0]) || $key[0] != '#';
6585
}
6586

    
6587
/**
6588
 * Identifies the children of an element array, optionally sorted by weight.
6589
 *
6590
 * The children of a element array are those key/value pairs whose key does
6591
 * not start with a '#'. See drupal_render() for details.
6592
 *
6593
 * @param $elements
6594
 *   The element array whose children are to be identified.
6595
 * @param $sort
6596
 *   Boolean to indicate whether the children should be sorted by weight.
6597
 *
6598
 * @return
6599
 *   The array keys of the element's children.
6600
 */
6601
function element_children(&$elements, $sort = FALSE) {
6602
  // Do not attempt to sort elements which have already been sorted.
6603
  $sort = isset($elements['#sorted']) ? !$elements['#sorted'] : $sort;
6604

    
6605
  // Filter out properties from the element, leaving only children.
6606
  $children = array();
6607
  $sortable = FALSE;
6608
  foreach ($elements as $key => $value) {
6609
    if ($key === '' || $key[0] !== '#') {
6610
      $children[$key] = $value;
6611
      if (is_array($value) && isset($value['#weight'])) {
6612
        $sortable = TRUE;
6613
      }
6614
    }
6615
  }
6616
  // Sort the children if necessary.
6617
  if ($sort && $sortable) {
6618
    uasort($children, 'element_sort');
6619
    // Put the sorted children back into $elements in the correct order, to
6620
    // preserve sorting if the same element is passed through
6621
    // element_children() twice.
6622
    foreach ($children as $key => $child) {
6623
      unset($elements[$key]);
6624
      $elements[$key] = $child;
6625
    }
6626
    $elements['#sorted'] = TRUE;
6627
  }
6628

    
6629
  return array_keys($children);
6630
}
6631

    
6632
/**
6633
 * Returns the visible children of an element.
6634
 *
6635
 * @param $elements
6636
 *   The parent element.
6637
 *
6638
 * @return
6639
 *   The array keys of the element's visible children.
6640
 */
6641
function element_get_visible_children(array $elements) {
6642
  $visible_children = array();
6643

    
6644
  foreach (element_children($elements) as $key) {
6645
    $child = $elements[$key];
6646

    
6647
    // Skip un-accessible children.
6648
    if (isset($child['#access']) && !$child['#access']) {
6649
      continue;
6650
    }
6651

    
6652
    // Skip value and hidden elements, since they are not rendered.
6653
    if (isset($child['#type']) && in_array($child['#type'], array('value', 'hidden'))) {
6654
      continue;
6655
    }
6656

    
6657
    $visible_children[$key] = $child;
6658
  }
6659

    
6660
  return array_keys($visible_children);
6661
}
6662

    
6663
/**
6664
 * Sets HTML attributes based on element properties.
6665
 *
6666
 * @param $element
6667
 *   The renderable element to process.
6668
 * @param $map
6669
 *   An associative array whose keys are element property names and whose values
6670
 *   are the HTML attribute names to set for corresponding the property; e.g.,
6671
 *   array('#propertyname' => 'attributename'). If both names are identical
6672
 *   except for the leading '#', then an attribute name value is sufficient and
6673
 *   no property name needs to be specified.
6674
 */
6675
function element_set_attributes(array &$element, array $map) {
6676
  foreach ($map as $property => $attribute) {
6677
    // If the key is numeric, the attribute name needs to be taken over.
6678
    if (is_int($property)) {
6679
      $property = '#' . $attribute;
6680
    }
6681
    // Do not overwrite already existing attributes.
6682
    if (isset($element[$property]) && !isset($element['#attributes'][$attribute])) {
6683
      $element['#attributes'][$attribute] = $element[$property];
6684
    }
6685
  }
6686
}
6687

    
6688
/**
6689
 * Recursively computes the difference of arrays with additional index check.
6690
 *
6691
 * This is a version of array_diff_assoc() that supports multidimensional
6692
 * arrays.
6693
 *
6694
 * @param array $array1
6695
 *   The array to compare from.
6696
 * @param array $array2
6697
 *   The array to compare to.
6698
 *
6699
 * @return array
6700
 *   Returns an array containing all the values from array1 that are not present
6701
 *   in array2.
6702
 */
6703
function drupal_array_diff_assoc_recursive($array1, $array2) {
6704
  $difference = array();
6705

    
6706
  foreach ($array1 as $key => $value) {
6707
    if (is_array($value)) {
6708
      if (!array_key_exists($key, $array2) || !is_array($array2[$key])) {
6709
        $difference[$key] = $value;
6710
      }
6711
      else {
6712
        $new_diff = drupal_array_diff_assoc_recursive($value, $array2[$key]);
6713
        if (!empty($new_diff)) {
6714
          $difference[$key] = $new_diff;
6715
        }
6716
      }
6717
    }
6718
    elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
6719
      $difference[$key] = $value;
6720
    }
6721
  }
6722

    
6723
  return $difference;
6724
}
6725

    
6726
/**
6727
 * Sets a value in a nested array with variable depth.
6728
 *
6729
 * This helper function should be used when the depth of the array element you
6730
 * are changing may vary (that is, the number of parent keys is variable). It
6731
 * is primarily used for form structures and renderable arrays.
6732
 *
6733
 * Example:
6734
 * @code
6735
 * // Assume you have a 'signature' element somewhere in a form. It might be:
6736
 * $form['signature_settings']['signature'] = array(
6737
 *   '#type' => 'text_format',
6738
 *   '#title' => t('Signature'),
6739
 * );
6740
 * // Or, it might be further nested:
6741
 * $form['signature_settings']['user']['signature'] = array(
6742
 *   '#type' => 'text_format',
6743
 *   '#title' => t('Signature'),
6744
 * );
6745
 * @endcode
6746
 *
6747
 * To deal with the situation, the code needs to figure out the route to the
6748
 * element, given an array of parents that is either
6749
 * @code array('signature_settings', 'signature') @endcode in the first case or
6750
 * @code array('signature_settings', 'user', 'signature') @endcode in the second
6751
 * case.
6752
 *
6753
 * Without this helper function the only way to set the signature element in one
6754
 * line would be using eval(), which should be avoided:
6755
 * @code
6756
 * // Do not do this! Avoid eval().
6757
 * eval('$form[\'' . implode("']['", $parents) . '\'] = $element;');
6758
 * @endcode
6759
 *
6760
 * Instead, use this helper function:
6761
 * @code
6762
 * drupal_array_set_nested_value($form, $parents, $element);
6763
 * @endcode
6764
 *
6765
 * However if the number of array parent keys is static, the value should always
6766
 * be set directly rather than calling this function. For instance, for the
6767
 * first example we could just do:
6768
 * @code
6769
 * $form['signature_settings']['signature'] = $element;
6770
 * @endcode
6771
 *
6772
 * @param $array
6773
 *   A reference to the array to modify.
6774
 * @param $parents
6775
 *   An array of parent keys, starting with the outermost key.
6776
 * @param $value
6777
 *   The value to set.
6778
 * @param $force
6779
 *   (Optional) If TRUE, the value is forced into the structure even if it
6780
 *   requires the deletion of an already existing non-array parent value. If
6781
 *   FALSE, PHP throws an error if trying to add into a value that is not an
6782
 *   array. Defaults to FALSE.
6783
 *
6784
 * @see drupal_array_get_nested_value()
6785
 */
6786
function drupal_array_set_nested_value(array &$array, array $parents, $value, $force = FALSE) {
6787
  $ref = &$array;
6788
  foreach ($parents as $parent) {
6789
    // PHP auto-creates container arrays and NULL entries without error if $ref
6790
    // is NULL, but throws an error if $ref is set, but not an array.
6791
    if ($force && isset($ref) && !is_array($ref)) {
6792
      $ref = array();
6793
    }
6794
    $ref = &$ref[$parent];
6795
  }
6796
  $ref = $value;
6797
}
6798

    
6799
/**
6800
 * Retrieves a value from a nested array with variable depth.
6801
 *
6802
 * This helper function should be used when the depth of the array element being
6803
 * retrieved may vary (that is, the number of parent keys is variable). It is
6804
 * primarily used for form structures and renderable arrays.
6805
 *
6806
 * Without this helper function the only way to get a nested array value with
6807
 * variable depth in one line would be using eval(), which should be avoided:
6808
 * @code
6809
 * // Do not do this! Avoid eval().
6810
 * // May also throw a PHP notice, if the variable array keys do not exist.
6811
 * eval('$value = $array[\'' . implode("']['", $parents) . "'];");
6812
 * @endcode
6813
 *
6814
 * Instead, use this helper function:
6815
 * @code
6816
 * $value = drupal_array_get_nested_value($form, $parents);
6817
 * @endcode
6818
 *
6819
 * A return value of NULL is ambiguous, and can mean either that the requested
6820
 * key does not exist, or that the actual value is NULL. If it is required to
6821
 * know whether the nested array key actually exists, pass a third argument that
6822
 * is altered by reference:
6823
 * @code
6824
 * $key_exists = NULL;
6825
 * $value = drupal_array_get_nested_value($form, $parents, $key_exists);
6826
 * if ($key_exists) {
6827
 *   // ... do something with $value ...
6828
 * }
6829
 * @endcode
6830
 *
6831
 * However if the number of array parent keys is static, the value should always
6832
 * be retrieved directly rather than calling this function. For instance:
6833
 * @code
6834
 * $value = $form['signature_settings']['signature'];
6835
 * @endcode
6836
 *
6837
 * @param $array
6838
 *   The array from which to get the value.
6839
 * @param $parents
6840
 *   An array of parent keys of the value, starting with the outermost key.
6841
 * @param $key_exists
6842
 *   (optional) If given, an already defined variable that is altered by
6843
 *   reference.
6844
 *
6845
 * @return
6846
 *   The requested nested value. Possibly NULL if the value is NULL or not all
6847
 *   nested parent keys exist. $key_exists is altered by reference and is a
6848
 *   Boolean that indicates whether all nested parent keys exist (TRUE) or not
6849
 *   (FALSE). This allows to distinguish between the two possibilities when NULL
6850
 *   is returned.
6851
 *
6852
 * @see drupal_array_set_nested_value()
6853
 */
6854
function &drupal_array_get_nested_value(array &$array, array $parents, &$key_exists = NULL) {
6855
  $ref = &$array;
6856
  foreach ($parents as $parent) {
6857
    if (is_array($ref) && array_key_exists($parent, $ref)) {
6858
      $ref = &$ref[$parent];
6859
    }
6860
    else {
6861
      $key_exists = FALSE;
6862
      $null = NULL;
6863
      return $null;
6864
    }
6865
  }
6866
  $key_exists = TRUE;
6867
  return $ref;
6868
}
6869

    
6870
/**
6871
 * Determines whether a nested array contains the requested keys.
6872
 *
6873
 * This helper function should be used when the depth of the array element to be
6874
 * checked may vary (that is, the number of parent keys is variable). See
6875
 * drupal_array_set_nested_value() for details. It is primarily used for form
6876
 * structures and renderable arrays.
6877
 *
6878
 * If it is required to also get the value of the checked nested key, use
6879
 * drupal_array_get_nested_value() instead.
6880
 *
6881
 * If the number of array parent keys is static, this helper function is
6882
 * unnecessary and the following code can be used instead:
6883
 * @code
6884
 * $value_exists = isset($form['signature_settings']['signature']);
6885
 * $key_exists = array_key_exists('signature', $form['signature_settings']);
6886
 * @endcode
6887
 *
6888
 * @param $array
6889
 *   The array with the value to check for.
6890
 * @param $parents
6891
 *   An array of parent keys of the value, starting with the outermost key.
6892
 *
6893
 * @return
6894
 *   TRUE if all the parent keys exist, FALSE otherwise.
6895
 *
6896
 * @see drupal_array_get_nested_value()
6897
 */
6898
function drupal_array_nested_key_exists(array $array, array $parents) {
6899
  // Although this function is similar to PHP's array_key_exists(), its
6900
  // arguments should be consistent with drupal_array_get_nested_value().
6901
  $key_exists = NULL;
6902
  drupal_array_get_nested_value($array, $parents, $key_exists);
6903
  return $key_exists;
6904
}
6905

    
6906
/**
6907
 * Provides theme registration for themes across .inc files.
6908
 */
6909
function drupal_common_theme() {
6910
  return array(
6911
    // From theme.inc.
6912
    'html' => array(
6913
      'render element' => 'page',
6914
      'template' => 'html',
6915
    ),
6916
    'page' => array(
6917
      'render element' => 'page',
6918
      'template' => 'page',
6919
    ),
6920
    'region' => array(
6921
      'render element' => 'elements',
6922
      'template' => 'region',
6923
    ),
6924
    'status_messages' => array(
6925
      'variables' => array('display' => NULL),
6926
    ),
6927
    'link' => array(
6928
      'variables' => array('text' => NULL, 'path' => NULL, 'options' => array()),
6929
    ),
6930
    'links' => array(
6931
      'variables' => array('links' => NULL, 'attributes' => array('class' => array('links')), 'heading' => array()),
6932
    ),
6933
    'image' => array(
6934
      // HTML 4 and XHTML 1.0 always require an alt attribute. The HTML 5 draft
6935
      // allows the alt attribute to be omitted in some cases. Therefore,
6936
      // default the alt attribute to an empty string, but allow code calling
6937
      // theme('image') to pass explicit NULL for it to be omitted. Usually,
6938
      // neither omission nor an empty string satisfies accessibility
6939
      // requirements, so it is strongly encouraged for code calling
6940
      // theme('image') to pass a meaningful value for the alt variable.
6941
      // - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
6942
      // - http://www.w3.org/TR/xhtml1/dtds.html
6943
      // - http://dev.w3.org/html5/spec/Overview.html#alt
6944
      // The title attribute is optional in all cases, so it is omitted by
6945
      // default.
6946
      'variables' => array('path' => NULL, 'width' => NULL, 'height' => NULL, 'alt' => '', 'title' => NULL, 'attributes' => array()),
6947
    ),
6948
    'breadcrumb' => array(
6949
      'variables' => array('breadcrumb' => NULL),
6950
    ),
6951
    'help' => array(
6952
      'variables' => array(),
6953
    ),
6954
    'table' => array(
6955
      'variables' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL, 'colgroups' => array(), 'sticky' => TRUE, 'empty' => ''),
6956
    ),
6957
    'tablesort_indicator' => array(
6958
      'variables' => array('style' => NULL),
6959
    ),
6960
    'mark' => array(
6961
      'variables' => array('type' => MARK_NEW),
6962
    ),
6963
    'item_list' => array(
6964
      'variables' => array('items' => array(), 'title' => NULL, 'type' => 'ul', 'attributes' => array()),
6965
    ),
6966
    'more_help_link' => array(
6967
      'variables' => array('url' => NULL),
6968
    ),
6969
    'feed_icon' => array(
6970
      'variables' => array('url' => NULL, 'title' => NULL),
6971
    ),
6972
    'more_link' => array(
6973
      'variables' => array('url' => NULL, 'title' => NULL)
6974
    ),
6975
    'username' => array(
6976
      'variables' => array('account' => NULL),
6977
    ),
6978
    'progress_bar' => array(
6979
      'variables' => array('percent' => NULL, 'message' => NULL),
6980
    ),
6981
    'indentation' => array(
6982
      'variables' => array('size' => 1),
6983
    ),
6984
    'html_tag' => array(
6985
      'render element' => 'element',
6986
    ),
6987
    // From theme.maintenance.inc.
6988
    'maintenance_page' => array(
6989
      'variables' => array('content' => NULL, 'show_messages' => TRUE),
6990
      'template' => 'maintenance-page',
6991
    ),
6992
    'update_page' => array(
6993
      'variables' => array('content' => NULL, 'show_messages' => TRUE),
6994
    ),
6995
    'install_page' => array(
6996
      'variables' => array('content' => NULL),
6997
    ),
6998
    'task_list' => array(
6999
      'variables' => array('items' => NULL, 'active' => NULL),
7000
    ),
7001
    'authorize_message' => array(
7002
      'variables' => array('message' => NULL, 'success' => TRUE),
7003
    ),
7004
    'authorize_report' => array(
7005
      'variables' => array('messages' => array()),
7006
    ),
7007
    // From pager.inc.
7008
    'pager' => array(
7009
      'variables' => array('tags' => array(), 'element' => 0, 'parameters' => array(), 'quantity' => 9),
7010
    ),
7011
    'pager_first' => array(
7012
      'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
7013
    ),
7014
    'pager_previous' => array(
7015
      'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
7016
    ),
7017
    'pager_next' => array(
7018
      'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
7019
    ),
7020
    'pager_last' => array(
7021
      'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
7022
    ),
7023
    'pager_link' => array(
7024
      'variables' => array('text' => NULL, 'page_new' => NULL, 'element' => NULL, 'parameters' => array(), 'attributes' => array()),
7025
    ),
7026
    // From menu.inc.
7027
    'menu_link' => array(
7028
      'render element' => 'element',
7029
    ),
7030
    'menu_tree' => array(
7031
      'render element' => 'tree',
7032
    ),
7033
    'menu_local_task' => array(
7034
      'render element' => 'element',
7035
    ),
7036
    'menu_local_action' => array(
7037
      'render element' => 'element',
7038
    ),
7039
    'menu_local_tasks' => array(
7040
      'variables' => array('primary' => array(), 'secondary' => array()),
7041
    ),
7042
    // From form.inc.
7043
    'select' => array(
7044
      'render element' => 'element',
7045
    ),
7046
    'fieldset' => array(
7047
      'render element' => 'element',
7048
    ),
7049
    'radio' => array(
7050
      'render element' => 'element',
7051
    ),
7052
    'radios' => array(
7053
      'render element' => 'element',
7054
    ),
7055
    'date' => array(
7056
      'render element' => 'element',
7057
    ),
7058
    'exposed_filters' => array(
7059
      'render element' => 'form',
7060
    ),
7061
    'checkbox' => array(
7062
      'render element' => 'element',
7063
    ),
7064
    'checkboxes' => array(
7065
      'render element' => 'element',
7066
    ),
7067
    'button' => array(
7068
      'render element' => 'element',
7069
    ),
7070
    'image_button' => array(
7071
      'render element' => 'element',
7072
    ),
7073
    'hidden' => array(
7074
      'render element' => 'element',
7075
    ),
7076
    'textfield' => array(
7077
      'render element' => 'element',
7078
    ),
7079
    'form' => array(
7080
      'render element' => 'element',
7081
    ),
7082
    'textarea' => array(
7083
      'render element' => 'element',
7084
    ),
7085
    'password' => array(
7086
      'render element' => 'element',
7087
    ),
7088
    'file' => array(
7089
      'render element' => 'element',
7090
    ),
7091
    'tableselect' => array(
7092
      'render element' => 'element',
7093
    ),
7094
    'form_element' => array(
7095
      'render element' => 'element',
7096
    ),
7097
    'form_required_marker' => array(
7098
      'render element' => 'element',
7099
    ),
7100
    'form_element_label' => array(
7101
      'render element' => 'element',
7102
    ),
7103
    'vertical_tabs' => array(
7104
      'render element' => 'element',
7105
    ),
7106
    'container' => array(
7107
      'render element' => 'element',
7108
    ),
7109
  );
7110
}
7111

    
7112
/**
7113
 * @addtogroup schemaapi
7114
 * @{
7115
 */
7116

    
7117
/**
7118
 * Creates all tables defined in a module's hook_schema().
7119
 *
7120
 * Note: This function does not pass the module's schema through
7121
 * hook_schema_alter(). The module's tables will be created exactly as the
7122
 * module defines them.
7123
 *
7124
 * @param $module
7125
 *   The module for which the tables will be created.
7126
 */
7127
function drupal_install_schema($module) {
7128
  $schema = drupal_get_schema_unprocessed($module);
7129
  _drupal_schema_initialize($schema, $module, FALSE);
7130

    
7131
  foreach ($schema as $name => $table) {
7132
    db_create_table($name, $table);
7133
  }
7134
}
7135

    
7136
/**
7137
 * Removes all tables defined in a module's hook_schema().
7138
 *
7139
 * Note: This function does not pass the module's schema through
7140
 * hook_schema_alter(). The module's tables will be created exactly as the
7141
 * module defines them.
7142
 *
7143
 * @param $module
7144
 *   The module for which the tables will be removed.
7145
 *
7146
 * @return
7147
 *   An array of arrays with the following key/value pairs:
7148
 *    - success: a boolean indicating whether the query succeeded.
7149
 *    - query: the SQL query(s) executed, passed through check_plain().
7150
 */
7151
function drupal_uninstall_schema($module) {
7152
  $schema = drupal_get_schema_unprocessed($module);
7153
  _drupal_schema_initialize($schema, $module, FALSE);
7154

    
7155
  foreach ($schema as $table) {
7156
    if (db_table_exists($table['name'])) {
7157
      db_drop_table($table['name']);
7158
    }
7159
  }
7160
}
7161

    
7162
/**
7163
 * Returns the unprocessed and unaltered version of a module's schema.
7164
 *
7165
 * Use this function only if you explicitly need the original
7166
 * specification of a schema, as it was defined in a module's
7167
 * hook_schema(). No additional default values will be set,
7168
 * hook_schema_alter() is not invoked and these unprocessed
7169
 * definitions won't be cached. To retrieve the schema after
7170
 * hook_schema_alter() has been invoked use drupal_get_schema().
7171
 *
7172
 * This function can be used to retrieve a schema specification in
7173
 * hook_schema(), so it allows you to derive your tables from existing
7174
 * specifications.
7175
 *
7176
 * It is also used by drupal_install_schema() and
7177
 * drupal_uninstall_schema() to ensure that a module's tables are
7178
 * created exactly as specified without any changes introduced by a
7179
 * module that implements hook_schema_alter().
7180
 *
7181
 * @param $module
7182
 *   The module to which the table belongs.
7183
 * @param $table
7184
 *   The name of the table. If not given, the module's complete schema
7185
 *   is returned.
7186
 */
7187
function drupal_get_schema_unprocessed($module, $table = NULL) {
7188
  // Load the .install file to get hook_schema.
7189
  module_load_install($module);
7190
  $schema = module_invoke($module, 'schema');
7191

    
7192
  if (isset($table) && isset($schema[$table])) {
7193
    return $schema[$table];
7194
  }
7195
  elseif (!empty($schema)) {
7196
    return $schema;
7197
  }
7198
  return array();
7199
}
7200

    
7201
/**
7202
 * Fills in required default values for table definitions from hook_schema().
7203
 *
7204
 * @param $schema
7205
 *   The schema definition array as it was returned by the module's
7206
 *   hook_schema().
7207
 * @param $module
7208
 *   The module for which hook_schema() was invoked.
7209
 * @param $remove_descriptions
7210
 *   (optional) Whether to additionally remove 'description' keys of all tables
7211
 *   and fields to improve performance of serialize() and unserialize().
7212
 *   Defaults to TRUE.
7213
 */
7214
function _drupal_schema_initialize(&$schema, $module, $remove_descriptions = TRUE) {
7215
  // Set the name and module key for all tables.
7216
  foreach ($schema as $name => &$table) {
7217
    if (empty($table['module'])) {
7218
      $table['module'] = $module;
7219
    }
7220
    if (!isset($table['name'])) {
7221
      $table['name'] = $name;
7222
    }
7223
    if ($remove_descriptions) {
7224
      unset($table['description']);
7225
      foreach ($table['fields'] as &$field) {
7226
        unset($field['description']);
7227
      }
7228
    }
7229
  }
7230
}
7231

    
7232
/**
7233
 * Retrieves the type for every field in a table schema.
7234
 *
7235
 * @param $table
7236
 *   The name of the table from which to retrieve type information.
7237
 *
7238
 * @return
7239
 *   An array of types, keyed by field name.
7240
 */
7241
function drupal_schema_field_types($table) {
7242
  $table_schema = drupal_get_schema($table);
7243
  $field_types = array();
7244
  foreach ($table_schema['fields'] as $field_name => $field_info) {
7245
    $field_types[$field_name] = isset($field_info['type']) ? $field_info['type'] : NULL;
7246
  }
7247
  return $field_types;
7248
}
7249

    
7250
/**
7251
 * Retrieves a list of fields from a table schema.
7252
 *
7253
 * The returned list is suitable for use in an SQL query.
7254
 *
7255
 * @param $table
7256
 *   The name of the table from which to retrieve fields.
7257
 * @param
7258
 *   An optional prefix to to all fields.
7259
 *
7260
 * @return An array of fields.
7261
 */
7262
function drupal_schema_fields_sql($table, $prefix = NULL) {
7263
  $schema = drupal_get_schema($table);
7264
  $fields = array_keys($schema['fields']);
7265
  if ($prefix) {
7266
    $columns = array();
7267
    foreach ($fields as $field) {
7268
      $columns[] = "$prefix.$field";
7269
    }
7270
    return $columns;
7271
  }
7272
  else {
7273
    return $fields;
7274
  }
7275
}
7276

    
7277
/**
7278
 * Saves (inserts or updates) a record to the database based upon the schema.
7279
 *
7280
 * Do not use drupal_write_record() within hook_update_N() functions, since the
7281
 * database schema cannot be relied upon when a user is running a series of
7282
 * updates. Instead, use db_insert() or db_update() to save the record.
7283
 *
7284
 * @param $table
7285
 *   The name of the table; this must be defined by a hook_schema()
7286
 *   implementation.
7287
 * @param $record
7288
 *   An object or array representing the record to write, passed in by
7289
 *   reference. If inserting a new record, values not provided in $record will
7290
 *   be populated in $record and in the database with the default values from
7291
 *   the schema, as well as a single serial (auto-increment) field (if present).
7292
 *   If updating an existing record, only provided values are updated in the
7293
 *   database, and $record is not modified.
7294
 * @param $primary_keys
7295
 *   To indicate that this is a new record to be inserted, omit this argument.
7296
 *   If this is an update, this argument specifies the primary keys' field
7297
 *   names. If there is only 1 field in the key, you may pass in a string; if
7298
 *   there are multiple fields in the key, pass in an array.
7299
 *
7300
 * @return
7301
 *   If the record insert or update failed, returns FALSE. If it succeeded,
7302
 *   returns SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
7303
 */
7304
function drupal_write_record($table, &$record, $primary_keys = array()) {
7305
  // Standardize $primary_keys to an array.
7306
  if (is_string($primary_keys)) {
7307
    $primary_keys = array($primary_keys);
7308
  }
7309

    
7310
  $schema = drupal_get_schema($table);
7311
  if (empty($schema)) {
7312
    return FALSE;
7313
  }
7314

    
7315
  $object = (object) $record;
7316
  $fields = array();
7317

    
7318
  // Go through the schema to determine fields to write.
7319
  foreach ($schema['fields'] as $field => $info) {
7320
    if ($info['type'] == 'serial') {
7321
      // Skip serial types if we are updating.
7322
      if (!empty($primary_keys)) {
7323
        continue;
7324
      }
7325
      // Track serial field so we can helpfully populate them after the query.
7326
      // NOTE: Each table should come with one serial field only.
7327
      $serial = $field;
7328
    }
7329

    
7330
    // Skip field if it is in $primary_keys as it is unnecessary to update a
7331
    // field to the value it is already set to.
7332
    if (in_array($field, $primary_keys)) {
7333
      continue;
7334
    }
7335

    
7336
    if (!property_exists($object, $field)) {
7337
      // Skip fields that are not provided, default values are already known
7338
      // by the database.
7339
      continue;
7340
    }
7341

    
7342
    // Build array of fields to update or insert.
7343
    if (empty($info['serialize'])) {
7344
      $fields[$field] = $object->$field;
7345
    }
7346
    else {
7347
      $fields[$field] = serialize($object->$field);
7348
    }
7349

    
7350
    // Type cast to proper datatype, except when the value is NULL and the
7351
    // column allows this.
7352
    //
7353
    // MySQL PDO silently casts e.g. FALSE and '' to 0 when inserting the value
7354
    // into an integer column, but PostgreSQL PDO does not. Also type cast NULL
7355
    // when the column does not allow this.
7356
    if (isset($object->$field) || !empty($info['not null'])) {
7357
      if ($info['type'] == 'int' || $info['type'] == 'serial') {
7358
        $fields[$field] = (int) $fields[$field];
7359
      }
7360
      elseif ($info['type'] == 'float') {
7361
        $fields[$field] = (float) $fields[$field];
7362
      }
7363
      else {
7364
        $fields[$field] = (string) $fields[$field];
7365
      }
7366
    }
7367
  }
7368

    
7369
  if (empty($fields)) {
7370
    return;
7371
  }
7372

    
7373
  // Build the SQL.
7374
  if (empty($primary_keys)) {
7375
    // We are doing an insert.
7376
    $options = array('return' => Database::RETURN_INSERT_ID);
7377
    if (isset($serial) && isset($fields[$serial])) {
7378
      // If the serial column has been explicitly set with an ID, then we don't
7379
      // require the database to return the last insert id.
7380
      if ($fields[$serial]) {
7381
        $options['return'] = Database::RETURN_AFFECTED;
7382
      }
7383
      // If a serial column does exist with no value (i.e. 0) then remove it as
7384
      // the database will insert the correct value for us.
7385
      else {
7386
        unset($fields[$serial]);
7387
      }
7388
    }
7389
    $query = db_insert($table, $options)->fields($fields);
7390
    $return = SAVED_NEW;
7391
  }
7392
  else {
7393
    $query = db_update($table)->fields($fields);
7394
    foreach ($primary_keys as $key) {
7395
      $query->condition($key, $object->$key);
7396
    }
7397
    $return = SAVED_UPDATED;
7398
  }
7399

    
7400
  // Execute the SQL.
7401
  if ($query_return = $query->execute()) {
7402
    if (isset($serial)) {
7403
      // If the database was not told to return the last insert id, it will be
7404
      // because we already know it.
7405
      if (isset($options) && $options['return'] != Database::RETURN_INSERT_ID) {
7406
        $object->$serial = $fields[$serial];
7407
      }
7408
      else {
7409
        $object->$serial = $query_return;
7410
      }
7411
    }
7412
  }
7413
  // If we have a single-field primary key but got no insert ID, the
7414
  // query failed. Note that we explicitly check for FALSE, because
7415
  // a valid update query which doesn't change any values will return
7416
  // zero (0) affected rows.
7417
  elseif ($query_return === FALSE && count($primary_keys) == 1) {
7418
    $return = FALSE;
7419
  }
7420

    
7421
  // If we are inserting, populate empty fields with default values.
7422
  if (empty($primary_keys)) {
7423
    foreach ($schema['fields'] as $field => $info) {
7424
      if (isset($info['default']) && !property_exists($object, $field)) {
7425
        $object->$field = $info['default'];
7426
      }
7427
    }
7428
  }
7429

    
7430
  // If we began with an array, convert back.
7431
  if (is_array($record)) {
7432
    $record = (array) $object;
7433
  }
7434

    
7435
  return $return;
7436
}
7437

    
7438
/**
7439
 * @} End of "addtogroup schemaapi".
7440
 */
7441

    
7442
/**
7443
 * Parses Drupal module and theme .info files.
7444
 *
7445
 * Info files are NOT for placing arbitrary theme and module-specific settings.
7446
 * Use variable_get() and variable_set() for that.
7447
 *
7448
 * Information stored in a module .info file:
7449
 * - name: The real name of the module for display purposes.
7450
 * - description: A brief description of the module.
7451
 * - dependencies: An array of dependency strings. Each is in the form
7452
 *   'project:module (versions)'; with the following meanings:
7453
 *   - project: (optional) Project shortname, recommended to ensure uniqueness,
7454
 *     if the module is part of a project hosted on drupal.org. If omitted,
7455
 *     also omit the : that follows. The project name is currently ignored by
7456
 *     Drupal core but is used for automated testing.
7457
 *   - module: (required) Module shortname within the project.
7458
 *   - (versions): Optional version information, consisting of one or more
7459
 *     comma-separated operator/value pairs or simply version numbers, which
7460
 *     can contain "x" as a wildcard. Examples: (>=7.22, <7.28), (7.x-3.x).
7461
 * - package: The name of the package of modules this module belongs to.
7462
 *
7463
 * See forum.info for an example of a module .info file.
7464
 *
7465
 * Information stored in a theme .info file:
7466
 * - name: The real name of the theme for display purposes.
7467
 * - description: Brief description.
7468
 * - screenshot: Path to screenshot relative to the theme's .info file.
7469
 * - engine: Theme engine; typically phptemplate.
7470
 * - base: Name of a base theme, if applicable; e.g., base = zen.
7471
 * - regions: Listed regions; e.g., region[left] = Left sidebar.
7472
 * - features: Features available; e.g., features[] = logo.
7473
 * - stylesheets: Theme stylesheets; e.g., stylesheets[all][] = my-style.css.
7474
 * - scripts: Theme scripts; e.g., scripts[] = my-script.js.
7475
 *
7476
 * See bartik.info for an example of a theme .info file.
7477
 *
7478
 * @param $filename
7479
 *   The file we are parsing. Accepts file with relative or absolute path.
7480
 *
7481
 * @return
7482
 *   The info array.
7483
 *
7484
 * @see drupal_parse_info_format()
7485
 */
7486
function drupal_parse_info_file($filename) {
7487
  $info = &drupal_static(__FUNCTION__, array());
7488

    
7489
  if (!isset($info[$filename])) {
7490
    if (!file_exists($filename)) {
7491
      $info[$filename] = array();
7492
    }
7493
    else {
7494
      $data = file_get_contents($filename);
7495
      $info[$filename] = drupal_parse_info_format($data);
7496
    }
7497
  }
7498
  return $info[$filename];
7499
}
7500

    
7501
/**
7502
 * Parses data in Drupal's .info format.
7503
 *
7504
 * Data should be in an .ini-like format to specify values. White-space
7505
 * generally doesn't matter, except inside values:
7506
 * @code
7507
 *   key = value
7508
 *   key = "value"
7509
 *   key = 'value'
7510
 *   key = "multi-line
7511
 *   value"
7512
 *   key = 'multi-line
7513
 *   value'
7514
 *   key
7515
 *   =
7516
 *   'value'
7517
 * @endcode
7518
 *
7519
 * Arrays are created using a HTTP GET alike syntax:
7520
 * @code
7521
 *   key[] = "numeric array"
7522
 *   key[index] = "associative array"
7523
 *   key[index][] = "nested numeric array"
7524
 *   key[index][index] = "nested associative array"
7525
 * @endcode
7526
 *
7527
 * PHP constants are substituted in, but only when used as the entire value.
7528
 * Comments should start with a semi-colon at the beginning of a line.
7529
 *
7530
 * @param $data
7531
 *   A string to parse.
7532
 *
7533
 * @return
7534
 *   The info array.
7535
 *
7536
 * @see drupal_parse_info_file()
7537
 */
7538
function drupal_parse_info_format($data) {
7539
  $info = array();
7540

    
7541
  if (preg_match_all('
7542
    @^\s*                           # Start at the beginning of a line, ignoring leading whitespace
7543
    ((?:
7544
      [^=;\[\]]|                    # Key names cannot contain equal signs, semi-colons or square brackets,
7545
      \[[^\[\]]*\]                  # unless they are balanced and not nested
7546
    )+?)
7547
    \s*=\s*                         # Key/value pairs are separated by equal signs (ignoring white-space)
7548
    (?:
7549
      ("(?:[^"]|(?<=\\\\)")*")|     # Double-quoted string, which may contain slash-escaped quotes/slashes
7550
      (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
7551
      ([^\r\n]*?)                   # Non-quoted string
7552
    )\s*$                           # Stop at the next end of a line, ignoring trailing whitespace
7553
    @msx', $data, $matches, PREG_SET_ORDER)) {
7554
    foreach ($matches as $match) {
7555
      // Fetch the key and value string.
7556
      $i = 0;
7557
      foreach (array('key', 'value1', 'value2', 'value3') as $var) {
7558
        $$var = isset($match[++$i]) ? $match[$i] : '';
7559
      }
7560
      $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
7561

    
7562
      // Parse array syntax.
7563
      $keys = preg_split('/\]?\[/', rtrim($key, ']'));
7564
      $last = array_pop($keys);
7565
      $parent = &$info;
7566

    
7567
      // Create nested arrays.
7568
      foreach ($keys as $key) {
7569
        if ($key == '') {
7570
          $key = count($parent);
7571
        }
7572
        if (!isset($parent[$key]) || !is_array($parent[$key])) {
7573
          $parent[$key] = array();
7574
        }
7575
        $parent = &$parent[$key];
7576
      }
7577

    
7578
      // Handle PHP constants.
7579
      if (preg_match('/^\w+$/i', $value) && defined($value)) {
7580
        $value = constant($value);
7581
      }
7582

    
7583
      // Insert actual value.
7584
      if ($last == '') {
7585
        $last = count($parent);
7586
      }
7587
      $parent[$last] = $value;
7588
    }
7589
  }
7590

    
7591
  return $info;
7592
}
7593

    
7594
/**
7595
 * Returns a list of severity levels, as defined in RFC 3164.
7596
 *
7597
 * @return
7598
 *   Array of the possible severity levels for log messages.
7599
 *
7600
 * @see http://www.ietf.org/rfc/rfc3164.txt
7601
 * @see watchdog()
7602
 * @ingroup logging_severity_levels
7603
 */
7604
function watchdog_severity_levels() {
7605
  return array(
7606
    WATCHDOG_EMERGENCY => t('emergency'),
7607
    WATCHDOG_ALERT     => t('alert'),
7608
    WATCHDOG_CRITICAL  => t('critical'),
7609
    WATCHDOG_ERROR     => t('error'),
7610
    WATCHDOG_WARNING   => t('warning'),
7611
    WATCHDOG_NOTICE    => t('notice'),
7612
    WATCHDOG_INFO      => t('info'),
7613
    WATCHDOG_DEBUG     => t('debug'),
7614
  );
7615
}
7616

    
7617

    
7618
/**
7619
 * Explodes a string of tags into an array.
7620
 *
7621
 * @see drupal_implode_tags()
7622
 */
7623
function drupal_explode_tags($tags) {
7624
  // This regexp allows the following types of user input:
7625
  // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
7626
  $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
7627
  preg_match_all($regexp, $tags, $matches);
7628
  $typed_tags = array_unique($matches[1]);
7629

    
7630
  $tags = array();
7631
  foreach ($typed_tags as $tag) {
7632
    // If a user has escaped a term (to demonstrate that it is a group,
7633
    // or includes a comma or quote character), we remove the escape
7634
    // formatting so to save the term into the database as the user intends.
7635
    $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
7636
    if ($tag != "") {
7637
      $tags[] = $tag;
7638
    }
7639
  }
7640

    
7641
  return $tags;
7642
}
7643

    
7644
/**
7645
 * Implodes an array of tags into a string.
7646
 *
7647
 * @see drupal_explode_tags()
7648
 */
7649
function drupal_implode_tags($tags) {
7650
  $encoded_tags = array();
7651
  foreach ($tags as $tag) {
7652
    // Commas and quotes in tag names are special cases, so encode them.
7653
    if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
7654
      $tag = '"' . str_replace('"', '""', $tag) . '"';
7655
    }
7656

    
7657
    $encoded_tags[] = $tag;
7658
  }
7659
  return implode(', ', $encoded_tags);
7660
}
7661

    
7662
/**
7663
 * Flushes all cached data on the site.
7664
 *
7665
 * Empties cache tables, rebuilds the menu cache and theme registries, and
7666
 * invokes a hook so that other modules' cache data can be cleared as well.
7667
 */
7668
function drupal_flush_all_caches() {
7669
  // Change query-strings on css/js files to enforce reload for all users.
7670
  _drupal_flush_css_js();
7671

    
7672
  registry_rebuild();
7673
  drupal_clear_css_cache();
7674
  drupal_clear_js_cache();
7675

    
7676
  // Rebuild the theme data. Note that the module data is rebuilt above, as
7677
  // part of registry_rebuild().
7678
  system_rebuild_theme_data();
7679
  drupal_theme_rebuild();
7680

    
7681
  entity_info_cache_clear();
7682
  node_types_rebuild();
7683
  // node_menu() defines menu items based on node types so it needs to come
7684
  // after node types are rebuilt.
7685
  menu_rebuild();
7686

    
7687
  // Synchronize to catch any actions that were added or removed.
7688
  actions_synchronize();
7689

    
7690
  // Don't clear cache_form - in-progress form submissions may break.
7691
  // Ordered so clearing the page cache will always be the last action.
7692
  $core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
7693
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
7694
  foreach ($cache_tables as $table) {
7695
    cache_clear_all('*', $table, TRUE);
7696
  }
7697

    
7698
  // Rebuild the bootstrap module list. We do this here so that developers
7699
  // can get new hook_boot() implementations registered without having to
7700
  // write a hook_update_N() function.
7701
  _system_update_bootstrap_status();
7702
}
7703

    
7704
/**
7705
 * Changes the dummy query string added to all CSS and JavaScript files.
7706
 *
7707
 * Changing the dummy query string appended to CSS and JavaScript files forces
7708
 * all browsers to reload fresh files.
7709
 */
7710
function _drupal_flush_css_js() {
7711
  // The timestamp is converted to base 36 in order to make it more compact.
7712
  variable_set('css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
7713
}
7714

    
7715
/**
7716
 * Outputs debug information.
7717
 *
7718
 * The debug information is passed on to trigger_error() after being converted
7719
 * to a string using _drupal_debug_message().
7720
 *
7721
 * @param $data
7722
 *   Data to be output.
7723
 * @param $label
7724
 *   Label to prefix the data.
7725
 * @param $print_r
7726
 *   Flag to switch between print_r() and var_export() for data conversion to
7727
 *   string. Set $print_r to TRUE when dealing with a recursive data structure
7728
 *   as var_export() will generate an error.
7729
 */
7730
function debug($data, $label = NULL, $print_r = FALSE) {
7731
  // Print $data contents to string.
7732
  $string = check_plain($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
7733

    
7734
  // Display values with pre-formatting to increase readability.
7735
  $string = '<pre>' . $string . '</pre>';
7736

    
7737
  trigger_error(trim($label ? "$label: $string" : $string));
7738
}
7739

    
7740
/**
7741
 * Parses a dependency for comparison by drupal_check_incompatibility().
7742
 *
7743
 * @param $dependency
7744
 *   A dependency string, which specifies a module dependency, and optionally
7745
 *   the project it comes from and versions that are supported. Supported
7746
 *   formats include:
7747
 *   - 'module'
7748
 *   - 'project:module'
7749
 *   - 'project:module (>=version, version)'
7750
 *
7751
 * @return
7752
 *   An associative array with three keys:
7753
 *   - 'name' includes the name of the thing to depend on (e.g. 'foo').
7754
 *   - 'original_version' contains the original version string (which can be
7755
 *     used in the UI for reporting incompatibilities).
7756
 *   - 'versions' is a list of associative arrays, each containing the keys
7757
 *     'op' and 'version'. 'op' can be one of: '=', '==', '!=', '<>', '<',
7758
 *     '<=', '>', or '>='. 'version' is one piece like '4.5-beta3'.
7759
 *   Callers should pass this structure to drupal_check_incompatibility().
7760
 *
7761
 * @see drupal_check_incompatibility()
7762
 */
7763
function drupal_parse_dependency($dependency) {
7764
  $value = array();
7765
  // Split out the optional project name.
7766
  if (strpos($dependency, ':')) {
7767
    list($project_name, $dependency) = explode(':', $dependency);
7768
    $value['project'] = $project_name;
7769
  }
7770
  // We use named subpatterns and support every op that version_compare
7771
  // supports. Also, op is optional and defaults to equals.
7772
  $p_op = '(?P<operation>!=|==|=|<|<=|>|>=|<>)?';
7773
  // Core version is always optional: 7.x-2.x and 2.x is treated the same.
7774
  $p_core = '(?:' . preg_quote(DRUPAL_CORE_COMPATIBILITY) . '-)?';
7775
  $p_major = '(?P<major>\d+)';
7776
  // By setting the minor version to x, branches can be matched.
7777
  $p_minor = '(?P<minor>(?:\d+|x)(?:-[A-Za-z]+\d+)?)';
7778
  $parts = explode('(', $dependency, 2);
7779
  $value['name'] = trim($parts[0]);
7780
  if (isset($parts[1])) {
7781
    $value['original_version'] = ' (' . $parts[1];
7782
    foreach (explode(',', $parts[1]) as $version) {
7783
      if (preg_match("/^\s*$p_op\s*$p_core$p_major\.$p_minor/", $version, $matches)) {
7784
        $op = !empty($matches['operation']) ? $matches['operation'] : '=';
7785
        if ($matches['minor'] == 'x') {
7786
          // Drupal considers "2.x" to mean any version that begins with
7787
          // "2" (e.g. 2.0, 2.9 are all "2.x"). PHP's version_compare(),
7788
          // on the other hand, treats "x" as a string; so to
7789
          // version_compare(), "2.x" is considered less than 2.0. This
7790
          // means that >=2.x and <2.x are handled by version_compare()
7791
          // as we need, but > and <= are not.
7792
          if ($op == '>' || $op == '<=') {
7793
            $matches['major']++;
7794
          }
7795
          // Equivalence can be checked by adding two restrictions.
7796
          if ($op == '=' || $op == '==') {
7797
            $value['versions'][] = array('op' => '<', 'version' => ($matches['major'] + 1) . '.x');
7798
            $op = '>=';
7799
          }
7800
        }
7801
        $value['versions'][] = array('op' => $op, 'version' => $matches['major'] . '.' . $matches['minor']);
7802
      }
7803
    }
7804
  }
7805
  return $value;
7806
}
7807

    
7808
/**
7809
 * Checks whether a version is compatible with a given dependency.
7810
 *
7811
 * @param $v
7812
 *   The parsed dependency structure from drupal_parse_dependency().
7813
 * @param $current_version
7814
 *   The version to check against (like 4.2).
7815
 *
7816
 * @return
7817
 *   NULL if compatible, otherwise the original dependency version string that
7818
 *   caused the incompatibility.
7819
 *
7820
 * @see drupal_parse_dependency()
7821
 */
7822
function drupal_check_incompatibility($v, $current_version) {
7823
  if (!empty($v['versions'])) {
7824
    foreach ($v['versions'] as $required_version) {
7825
      if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
7826
        return $v['original_version'];
7827
      }
7828
    }
7829
  }
7830
}
7831

    
7832
/**
7833
 * Get the entity info array of an entity type.
7834
 *
7835
 * @param $entity_type
7836
 *   The entity type, e.g. node, for which the info shall be returned, or NULL
7837
 *   to return an array with info about all types.
7838
 *
7839
 * @see hook_entity_info()
7840
 * @see hook_entity_info_alter()
7841
 */
7842
function entity_get_info($entity_type = NULL) {
7843
  global $language;
7844

    
7845
  // Use the advanced drupal_static() pattern, since this is called very often.
7846
  static $drupal_static_fast;
7847
  if (!isset($drupal_static_fast)) {
7848
    $drupal_static_fast['entity_info'] = &drupal_static(__FUNCTION__);
7849
  }
7850
  $entity_info = &$drupal_static_fast['entity_info'];
7851

    
7852
  // hook_entity_info() includes translated strings, so each language is cached
7853
  // separately.
7854
  $langcode = $language->language;
7855

    
7856
  if (empty($entity_info)) {
7857
    if ($cache = cache_get("entity_info:$langcode")) {
7858
      $entity_info = $cache->data;
7859
    }
7860
    else {
7861
      $entity_info = module_invoke_all('entity_info');
7862
      // Merge in default values.
7863
      foreach ($entity_info as $name => $data) {
7864
        $entity_info[$name] += array(
7865
          'fieldable' => FALSE,
7866
          'controller class' => 'DrupalDefaultEntityController',
7867
          'static cache' => TRUE,
7868
          'field cache' => TRUE,
7869
          'load hook' => $name . '_load',
7870
          'bundles' => array(),
7871
          'view modes' => array(),
7872
          'entity keys' => array(),
7873
          'translation' => array(),
7874
        );
7875
        $entity_info[$name]['entity keys'] += array(
7876
          'revision' => '',
7877
          'bundle' => '',
7878
        );
7879
        foreach ($entity_info[$name]['view modes'] as $view_mode => $view_mode_info) {
7880
          $entity_info[$name]['view modes'][$view_mode] += array(
7881
            'custom settings' => FALSE,
7882
          );
7883
        }
7884
        // If no bundle key is provided, assume a single bundle, named after
7885
        // the entity type.
7886
        if (empty($entity_info[$name]['entity keys']['bundle']) && empty($entity_info[$name]['bundles'])) {
7887
          $entity_info[$name]['bundles'] = array($name => array('label' => $entity_info[$name]['label']));
7888
        }
7889
        // Prepare entity schema fields SQL info for
7890
        // DrupalEntityControllerInterface::buildQuery().
7891
        if (isset($entity_info[$name]['base table'])) {
7892
          $entity_info[$name]['base table field types'] = drupal_schema_field_types($entity_info[$name]['base table']);
7893
          $entity_info[$name]['schema_fields_sql']['base table'] = drupal_schema_fields_sql($entity_info[$name]['base table']);
7894
          if (isset($entity_info[$name]['revision table'])) {
7895
            $entity_info[$name]['schema_fields_sql']['revision table'] = drupal_schema_fields_sql($entity_info[$name]['revision table']);
7896
          }
7897
        }
7898
      }
7899
      // Let other modules alter the entity info.
7900
      drupal_alter('entity_info', $entity_info);
7901
      cache_set("entity_info:$langcode", $entity_info);
7902
    }
7903
  }
7904

    
7905
  if (empty($entity_type)) {
7906
    return $entity_info;
7907
  }
7908
  elseif (isset($entity_info[$entity_type])) {
7909
    return $entity_info[$entity_type];
7910
  }
7911
}
7912

    
7913
/**
7914
 * Resets the cached information about entity types.
7915
 */
7916
function entity_info_cache_clear() {
7917
  drupal_static_reset('entity_get_info');
7918
  // Clear all languages.
7919
  cache_clear_all('entity_info:', 'cache', TRUE);
7920
}
7921

    
7922
/**
7923
 * Helper function to extract id, vid, and bundle name from an entity.
7924
 *
7925
 * @param $entity_type
7926
 *   The entity type; e.g. 'node' or 'user'.
7927
 * @param $entity
7928
 *   The entity from which to extract values.
7929
 *
7930
 * @return
7931
 *   A numerically indexed array (not a hash table) containing these
7932
 *   elements:
7933
 *   - 0: Primary ID of the entity.
7934
 *   - 1: Revision ID of the entity, or NULL if $entity_type is not versioned.
7935
 *   - 2: Bundle name of the entity, or NULL if $entity_type has no bundles.
7936
 */
7937
function entity_extract_ids($entity_type, $entity) {
7938
  $info = entity_get_info($entity_type);
7939

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

    
7944
  if (!empty($info['entity keys']['bundle'])) {
7945
    // Explicitly fail for malformed entities missing the bundle property.
7946
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
7947
      throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
7948
    }
7949
    $bundle = $entity->{$info['entity keys']['bundle']};
7950
  }
7951
  else {
7952
    // The entity type provides no bundle key: assume a single bundle, named
7953
    // after the entity type.
7954
    $bundle = $entity_type;
7955
  }
7956

    
7957
  return array($id, $vid, $bundle);
7958
}
7959

    
7960
/**
7961
 * Helper function to assemble an object structure with initial ids.
7962
 *
7963
 * This function can be seen as reciprocal to entity_extract_ids().
7964
 *
7965
 * @param $entity_type
7966
 *   The entity type; e.g. 'node' or 'user'.
7967
 * @param $ids
7968
 *   A numerically indexed array, as returned by entity_extract_ids().
7969
 *
7970
 * @return
7971
 *   An entity structure, initialized with the ids provided.
7972
 *
7973
 * @see entity_extract_ids()
7974
 */
7975
function entity_create_stub_entity($entity_type, $ids) {
7976
  $entity = new stdClass();
7977
  $info = entity_get_info($entity_type);
7978
  $entity->{$info['entity keys']['id']} = $ids[0];
7979
  if (!empty($info['entity keys']['revision']) && isset($ids[1])) {
7980
    $entity->{$info['entity keys']['revision']} = $ids[1];
7981
  }
7982
  if (!empty($info['entity keys']['bundle']) && isset($ids[2])) {
7983
    $entity->{$info['entity keys']['bundle']} = $ids[2];
7984
  }
7985
  return $entity;
7986
}
7987

    
7988
/**
7989
 * Load entities from the database.
7990
 *
7991
 * The entities are stored in a static memory cache, and will not require
7992
 * database access if loaded again during the same page request.
7993
 *
7994
 * The actual loading is done through a class that has to implement the
7995
 * DrupalEntityControllerInterface interface. By default,
7996
 * DrupalDefaultEntityController is used. Entity types can specify that a
7997
 * different class should be used by setting the 'controller class' key in
7998
 * hook_entity_info(). These classes can either implement the
7999
 * DrupalEntityControllerInterface interface, or, most commonly, extend the
8000
 * DrupalDefaultEntityController class. See node_entity_info() and the
8001
 * NodeController in node.module as an example.
8002
 *
8003
 * @param $entity_type
8004
 *   The entity type to load, e.g. node or user.
8005
 * @param $ids
8006
 *   An array of entity IDs, or FALSE to load all entities.
8007
 * @param $conditions
8008
 *   (deprecated) An associative array of conditions on the base table, where
8009
 *   the keys are the database fields and the values are the values those
8010
 *   fields must have. Instead, it is preferable to use EntityFieldQuery to
8011
 *   retrieve a list of entity IDs loadable by this function.
8012
 * @param $reset
8013
 *   Whether to reset the internal cache for the requested entity type.
8014
 *
8015
 * @return
8016
 *   An array of entity objects indexed by their ids. When no results are
8017
 *   found, an empty array is returned.
8018
 *
8019
 * @todo Remove $conditions in Drupal 8.
8020
 *
8021
 * @see hook_entity_info()
8022
 * @see DrupalEntityControllerInterface
8023
 * @see DrupalDefaultEntityController
8024
 * @see EntityFieldQuery
8025
 */
8026
function entity_load($entity_type, $ids = FALSE, $conditions = array(), $reset = FALSE) {
8027
  if ($reset) {
8028
    entity_get_controller($entity_type)->resetCache();
8029
  }
8030
  return entity_get_controller($entity_type)->load($ids, $conditions);
8031
}
8032

    
8033
/**
8034
 * Loads the unchanged, i.e. not modified, entity from the database.
8035
 *
8036
 * Unlike entity_load() this function ensures the entity is directly loaded from
8037
 * the database, thus bypassing any static cache. In particular, this function
8038
 * is useful to determine changes by comparing the entity being saved to the
8039
 * stored entity.
8040
 *
8041
 * @param $entity_type
8042
 *   The entity type to load, e.g. node or user.
8043
 * @param $id
8044
 *   The ID of the entity to load.
8045
 *
8046
 * @return
8047
 *   The unchanged entity, or FALSE if the entity cannot be loaded.
8048
 */
8049
function entity_load_unchanged($entity_type, $id) {
8050
  entity_get_controller($entity_type)->resetCache(array($id));
8051
  $result = entity_get_controller($entity_type)->load(array($id));
8052
  return reset($result);
8053
}
8054

    
8055
/**
8056
 * Gets the entity controller for an entity type.
8057
 *
8058
 * @return DrupalEntityControllerInterface
8059
 *   The entity controller object for the specified entity type.
8060
 */
8061
function entity_get_controller($entity_type) {
8062
  $controllers = &drupal_static(__FUNCTION__, array());
8063
  if (!isset($controllers[$entity_type])) {
8064
    $type_info = entity_get_info($entity_type);
8065
    $class = $type_info['controller class'];
8066
    $controllers[$entity_type] = new $class($entity_type);
8067
  }
8068
  return $controllers[$entity_type];
8069
}
8070

    
8071
/**
8072
 * Invoke hook_entity_prepare_view().
8073
 *
8074
 * If adding a new entity similar to nodes, comments or users, you should
8075
 * invoke this function during the ENTITY_build_content() or
8076
 * ENTITY_view_multiple() phases of rendering to allow other modules to alter
8077
 * the objects during this phase. This is needed for situations where
8078
 * information needs to be loaded outside of ENTITY_load() - particularly
8079
 * when loading entities into one another - i.e. a user object into a node, due
8080
 * to the potential for unwanted side-effects such as caching and infinite
8081
 * recursion. By convention, entity_prepare_view() is called after
8082
 * field_attach_prepare_view() to allow entity level hooks to act on content
8083
 * loaded by field API.
8084
 *
8085
 * @param $entity_type
8086
 *   The type of entity, i.e. 'node', 'user'.
8087
 * @param $entities
8088
 *   The entity objects which are being prepared for view, keyed by object ID.
8089
 * @param $langcode
8090
 *   (optional) A language code to be used for rendering. Defaults to the global
8091
 *   content language of the current request.
8092
 *
8093
 * @see hook_entity_prepare_view()
8094
 */
8095
function entity_prepare_view($entity_type, $entities, $langcode = NULL) {
8096
  if (!isset($langcode)) {
8097
    $langcode = $GLOBALS['language_content']->language;
8098
  }
8099

    
8100
  // To ensure hooks are only run once per entity, check for an
8101
  // entity_view_prepared flag and only process items without it.
8102
  // @todo: resolve this more generally for both entity and field level hooks.
8103
  $prepare = array();
8104
  foreach ($entities as $id => $entity) {
8105
    if (empty($entity->entity_view_prepared)) {
8106
      // Add this entity to the items to be prepared.
8107
      $prepare[$id] = $entity;
8108

    
8109
      // Mark this item as prepared.
8110
      $entity->entity_view_prepared = TRUE;
8111
    }
8112
  }
8113

    
8114
  if (!empty($prepare)) {
8115
    module_invoke_all('entity_prepare_view', $prepare, $entity_type, $langcode);
8116
  }
8117
}
8118

    
8119
/**
8120
 * Invoke hook_entity_view_mode_alter().
8121
 *
8122
 * If adding a new entity similar to nodes, comments or users, you should invoke
8123
 * this function during the ENTITY_build_content() or ENTITY_view_multiple()
8124
 * phases of rendering to allow other modules to alter the view mode during this
8125
 * phase. This function needs to be called before field_attach_prepare_view() to
8126
 * ensure that the correct content is loaded by field API.
8127
 *
8128
 * @param $entity_type
8129
 *   The type of entity, i.e. 'node', 'user'.
8130
 * @param $entities
8131
 *   The entity objects which are being prepared for view, keyed by object ID.
8132
 * @param $view_mode
8133
 *   The original view mode e.g. 'full', 'teaser'...
8134
 * @param $langcode
8135
 *   (optional) A language code to be used for rendering. Defaults to the global
8136
 *   content language of the current request.
8137
 * @return
8138
 *   An associative array with arrays of entities keyed by view mode.
8139
 *
8140
 * @see hook_entity_view_mode_alter()
8141
 */
8142
function entity_view_mode_prepare($entity_type, $entities, $view_mode, $langcode = NULL) {
8143
  if (!isset($langcode)) {
8144
    $langcode = $GLOBALS['language_content']->language;
8145
  }
8146

    
8147
  // To ensure hooks are never run after field_attach_prepare_view() only
8148
  // process items without the entity_view_prepared flag.
8149
  $entities_by_view_mode = array();
8150
  foreach ($entities as $id => $entity) {
8151
    $entity_view_mode = $view_mode;
8152
    if (empty($entity->entity_view_prepared)) {
8153

    
8154
      // Allow modules to change the view mode.
8155
      $context = array(
8156
        'entity_type' => $entity_type,
8157
        'entity' => $entity,
8158
        'langcode' => $langcode,
8159
      );
8160
      drupal_alter('entity_view_mode', $entity_view_mode, $context);
8161
    }
8162

    
8163
    $entities_by_view_mode[$entity_view_mode][$id] = $entity;
8164
  }
8165

    
8166
  return $entities_by_view_mode;
8167
}
8168

    
8169
/**
8170
 * Returns the URI elements of an entity.
8171
 *
8172
 * @param $entity_type
8173
 *   The entity type; e.g. 'node' or 'user'.
8174
 * @param $entity
8175
 *   The entity for which to generate a path.
8176
 * @return
8177
 *   An array containing the 'path' and 'options' keys used to build the URI of
8178
 *   the entity, and matching the signature of url(). NULL if the entity has no
8179
 *   URI of its own.
8180
 */
8181
function entity_uri($entity_type, $entity) {
8182
  $info = entity_get_info($entity_type);
8183
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
8184

    
8185
  // A bundle-specific callback takes precedence over the generic one for the
8186
  // entity type.
8187
  if (isset($info['bundles'][$bundle]['uri callback'])) {
8188
    $uri_callback = $info['bundles'][$bundle]['uri callback'];
8189
  }
8190
  elseif (isset($info['uri callback'])) {
8191
    $uri_callback = $info['uri callback'];
8192
  }
8193
  else {
8194
    return NULL;
8195
  }
8196

    
8197
  // Invoke the callback to get the URI. If there is no callback, return NULL.
8198
  if (isset($uri_callback) && function_exists($uri_callback)) {
8199
    $uri = $uri_callback($entity);
8200
    // Pass the entity data to url() so that alter functions do not need to
8201
    // lookup this entity again.
8202
    $uri['options']['entity_type'] = $entity_type;
8203
    $uri['options']['entity'] = $entity;
8204
    return $uri;
8205
  }
8206
}
8207

    
8208
/**
8209
 * Returns the label of an entity.
8210
 *
8211
 * See the 'label callback' component of the hook_entity_info() return value
8212
 * for more information.
8213
 *
8214
 * @param $entity_type
8215
 *   The entity type; e.g., 'node' or 'user'.
8216
 * @param $entity
8217
 *   The entity for which to generate the label.
8218
 *
8219
 * @return
8220
 *   The entity label, or FALSE if not found.
8221
 */
8222
function entity_label($entity_type, $entity) {
8223
  $label = FALSE;
8224
  $info = entity_get_info($entity_type);
8225
  if (isset($info['label callback']) && function_exists($info['label callback'])) {
8226
    $label = $info['label callback']($entity, $entity_type);
8227
  }
8228
  elseif (!empty($info['entity keys']['label']) && isset($entity->{$info['entity keys']['label']})) {
8229
    $label = $entity->{$info['entity keys']['label']};
8230
  }
8231

    
8232
  return $label;
8233
}
8234

    
8235
/**
8236
 * Returns the language of an entity.
8237
 *
8238
 * @param $entity_type
8239
 *   The entity type; e.g., 'node' or 'user'.
8240
 * @param $entity
8241
 *   The entity for which to get the language.
8242
 *
8243
 * @return
8244
 *   A valid language code or NULL if the entity has no language support.
8245
 */
8246
function entity_language($entity_type, $entity) {
8247
  $info = entity_get_info($entity_type);
8248

    
8249
  // Invoke the callback to get the language. If there is no callback, try to
8250
  // get it from a property of the entity, otherwise NULL.
8251
  if (isset($info['language callback']) && function_exists($info['language callback'])) {
8252
    $langcode = $info['language callback']($entity_type, $entity);
8253
  }
8254
  elseif (!empty($info['entity keys']['language']) && isset($entity->{$info['entity keys']['language']})) {
8255
    $langcode = $entity->{$info['entity keys']['language']};
8256
  }
8257
  else {
8258
    // The value returned in D8 would be LANGUAGE_NONE, we cannot use it here to
8259
    // preserve backward compatibility. In fact this function has been
8260
    // introduced very late in the D7 life cycle, mainly as the proper default
8261
    // for field_attach_form(). By returning LANGUAGE_NONE when no language
8262
    // information is available, we would introduce a potentially BC-breaking
8263
    // API change, since field_attach_form() defaults to the default language
8264
    // instead of LANGUAGE_NONE. Moreover this allows us to distinguish between
8265
    // entities that have no language specified from ones that do not have
8266
    // language support at all.
8267
    $langcode = NULL;
8268
  }
8269

    
8270
  return $langcode;
8271
}
8272

    
8273
/**
8274
 * Attaches field API validation to entity forms.
8275
 */
8276
function entity_form_field_validate($entity_type, $form, &$form_state) {
8277
  // All field attach API functions act on an entity object, but during form
8278
  // validation, we don't have one. $form_state contains the entity as it was
8279
  // prior to processing the current form submission, and we must not update it
8280
  // until we have fully validated the submitted input. Therefore, for
8281
  // validation, act on a pseudo entity created out of the form values.
8282
  $pseudo_entity = (object) $form_state['values'];
8283
  field_attach_form_validate($entity_type, $pseudo_entity, $form, $form_state);
8284
}
8285

    
8286
/**
8287
 * Copies submitted values to entity properties for simple entity forms.
8288
 *
8289
 * During the submission handling of an entity form's "Save", "Preview", and
8290
 * possibly other buttons, the form state's entity needs to be updated with the
8291
 * submitted form values. Each entity form implements its own builder function
8292
 * for doing this, appropriate for the particular entity and form, whereas
8293
 * modules may specify additional builder functions in $form['#entity_builders']
8294
 * for copying the form values of added form elements to entity properties.
8295
 * Many of the main entity builder functions can call this helper function to
8296
 * re-use its logic of copying $form_state['values'][PROPERTY] values to
8297
 * $entity->PROPERTY for all entries in $form_state['values'] that are not field
8298
 * data, and calling field_attach_submit() to copy field data. Apart from that
8299
 * this helper invokes any additional builder functions that have been specified
8300
 * in $form['#entity_builders'].
8301
 *
8302
 * For some entity forms (e.g., forms with complex non-field data and forms that
8303
 * simultaneously edit multiple entities), this behavior may be inappropriate,
8304
 * so the builder function for such forms needs to implement the required
8305
 * functionality instead of calling this function.
8306
 */
8307
function entity_form_submit_build_entity($entity_type, $entity, $form, &$form_state) {
8308
  $info = entity_get_info($entity_type);
8309
  list(, , $bundle) = entity_extract_ids($entity_type, $entity);
8310

    
8311
  // Copy top-level form values that are not for fields to entity properties,
8312
  // without changing existing entity properties that are not being edited by
8313
  // this form. Copying field values must be done using field_attach_submit().
8314
  $values_excluding_fields = $info['fieldable'] ? array_diff_key($form_state['values'], field_info_instances($entity_type, $bundle)) : $form_state['values'];
8315
  foreach ($values_excluding_fields as $key => $value) {
8316
    $entity->$key = $value;
8317
  }
8318

    
8319
  // Invoke all specified builders for copying form values to entity properties.
8320
  if (isset($form['#entity_builders'])) {
8321
    foreach ($form['#entity_builders'] as $function) {
8322
      $function($entity_type, $entity, $form, $form_state);
8323
    }
8324
  }
8325

    
8326
  // Copy field values to the entity.
8327
  if ($info['fieldable']) {
8328
    field_attach_submit($entity_type, $entity, $form, $form_state);
8329
  }
8330
}
8331

    
8332
/**
8333
 * Performs one or more XML-RPC request(s).
8334
 *
8335
 * Usage example:
8336
 * @code
8337
 * $result = xmlrpc('http://example.com/xmlrpc.php', array(
8338
 *   'service.methodName' => array($parameter, $second, $third),
8339
 * ));
8340
 * @endcode
8341
 *
8342
 * @param $url
8343
 *   An absolute URL of the XML-RPC endpoint.
8344
 * @param $args
8345
 *   An associative array whose keys are the methods to call and whose values
8346
 *   are the arguments to pass to the respective method. If multiple methods
8347
 *   are specified, a system.multicall is performed.
8348
 * @param $options
8349
 *   (optional) An array of options to pass along to drupal_http_request().
8350
 *
8351
 * @return
8352
 *   For one request:
8353
 *     Either the return value of the method on success, or FALSE.
8354
 *     If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
8355
 *   For multiple requests:
8356
 *     An array of results. Each result will either be the result
8357
 *     returned by the method called, or an xmlrpc_error object if the call
8358
 *     failed. See xmlrpc_error().
8359
 */
8360
function xmlrpc($url, $args, $options = array()) {
8361
  require_once DRUPAL_ROOT . '/includes/xmlrpc.inc';
8362
  return _xmlrpc($url, $args, $options);
8363
}
8364

    
8365
/**
8366
 * Retrieves a list of all available archivers.
8367
 *
8368
 * @see hook_archiver_info()
8369
 * @see hook_archiver_info_alter()
8370
 */
8371
function archiver_get_info() {
8372
  $archiver_info = &drupal_static(__FUNCTION__, array());
8373

    
8374
  if (empty($archiver_info)) {
8375
    $cache = cache_get('archiver_info');
8376
    if ($cache === FALSE) {
8377
      // Rebuild the cache and save it.
8378
      $archiver_info = module_invoke_all('archiver_info');
8379
      drupal_alter('archiver_info', $archiver_info);
8380
      uasort($archiver_info, 'drupal_sort_weight');
8381
      cache_set('archiver_info', $archiver_info);
8382
    }
8383
    else {
8384
      $archiver_info = $cache->data;
8385
    }
8386
  }
8387

    
8388
  return $archiver_info;
8389
}
8390

    
8391
/**
8392
 * Returns a string of supported archive extensions.
8393
 *
8394
 * @return
8395
 *   A space-separated string of extensions suitable for use by the file
8396
 *   validation system.
8397
 */
8398
function archiver_get_extensions() {
8399
  $valid_extensions = array();
8400
  foreach (archiver_get_info() as $archive) {
8401
    foreach ($archive['extensions'] as $extension) {
8402
      foreach (explode('.', $extension) as $part) {
8403
        if (!in_array($part, $valid_extensions)) {
8404
          $valid_extensions[] = $part;
8405
        }
8406
      }
8407
    }
8408
  }
8409
  return implode(' ', $valid_extensions);
8410
}
8411

    
8412
/**
8413
 * Creates the appropriate archiver for the specified file.
8414
 *
8415
 * @param $file
8416
 *   The full path of the archive file. Note that stream wrapper paths are
8417
 *   supported, but not remote ones.
8418
 *
8419
 * @return
8420
 *   A newly created instance of the archiver class appropriate
8421
 *   for the specified file, already bound to that file.
8422
 *   If no appropriate archiver class was found, will return FALSE.
8423
 */
8424
function archiver_get_archiver($file) {
8425
  // Archivers can only work on local paths
8426
  $filepath = drupal_realpath($file);
8427
  if (!is_file($filepath)) {
8428
    throw new Exception(t('Archivers can only operate on local files: %file not supported', array('%file' => $file)));
8429
  }
8430
  $archiver_info = archiver_get_info();
8431

    
8432
  foreach ($archiver_info as $implementation) {
8433
    foreach ($implementation['extensions'] as $extension) {
8434
      // Because extensions may be multi-part, such as .tar.gz,
8435
      // we cannot use simpler approaches like substr() or pathinfo().
8436
      // This method isn't quite as clean but gets the job done.
8437
      // Also note that the file may not yet exist, so we cannot rely
8438
      // on fileinfo() or other disk-level utilities.
8439
      if (strrpos($filepath, '.' . $extension) === strlen($filepath) - strlen('.' . $extension)) {
8440
        return new $implementation['class']($filepath);
8441
      }
8442
    }
8443
  }
8444
}
8445

    
8446
/**
8447
 * Assembles the Drupal Updater registry.
8448
 *
8449
 * An Updater is a class that knows how to update various parts of the Drupal
8450
 * file system, for example to update modules that have newer releases, or to
8451
 * install a new theme.
8452
 *
8453
 * @return
8454
 *   The Drupal Updater class registry.
8455
 *
8456
 * @see hook_updater_info()
8457
 * @see hook_updater_info_alter()
8458
 */
8459
function drupal_get_updaters() {
8460
  $updaters = &drupal_static(__FUNCTION__);
8461
  if (!isset($updaters)) {
8462
    $updaters = module_invoke_all('updater_info');
8463
    drupal_alter('updater_info', $updaters);
8464
    uasort($updaters, 'drupal_sort_weight');
8465
  }
8466
  return $updaters;
8467
}
8468

    
8469
/**
8470
 * Assembles the Drupal FileTransfer registry.
8471
 *
8472
 * @return
8473
 *   The Drupal FileTransfer class registry.
8474
 *
8475
 * @see FileTransfer
8476
 * @see hook_filetransfer_info()
8477
 * @see hook_filetransfer_info_alter()
8478
 */
8479
function drupal_get_filetransfer_info() {
8480
  $info = &drupal_static(__FUNCTION__);
8481
  if (!isset($info)) {
8482
    // Since we have to manually set the 'file path' default for each
8483
    // module separately, we can't use module_invoke_all().
8484
    $info = array();
8485
    foreach (module_implements('filetransfer_info') as $module) {
8486
      $function = $module . '_filetransfer_info';
8487
      if (function_exists($function)) {
8488
        $result = $function();
8489
        if (isset($result) && is_array($result)) {
8490
          foreach ($result as &$values) {
8491
            if (empty($values['file path'])) {
8492
              $values['file path'] = drupal_get_path('module', $module);
8493
            }
8494
          }
8495
          $info = array_merge_recursive($info, $result);
8496
        }
8497
      }
8498
    }
8499
    drupal_alter('filetransfer_info', $info);
8500
    uasort($info, 'drupal_sort_weight');
8501
  }
8502
  return $info;
8503
}