Projet

Général

Profil

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

root / drupal7 / includes / common.inc @ 01dfd3b5

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($delimiter, $feeds);
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
    // Double check the path derived by drupal_parse_url() is not external.
688
    if (!url_is_external($destination['path'])) {
689
      $path = $destination['path'];
690
    }
691
    $options['query'] = $destination['query'];
692
    $options['fragment'] = $destination['fragment'];
693
  }
694

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

    
702
  drupal_alter('drupal_goto', $path, $options, $http_response_code);
703

    
704
  // The 'Location' HTTP header must be absolute.
705
  $options['absolute'] = TRUE;
706

    
707
  $url = url($path, $options);
708

    
709
  header('Location: ' . $url, TRUE, $http_response_code);
710

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

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

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

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

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

    
805
  $result = new stdClass();
806

    
807
  // Parse the URL and make sure we can handle the schema.
808
  $uri = @parse_url($url);
809

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

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

    
822
  timer_start(__FUNCTION__);
823

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

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

    
839
  // stream_socket_client() requires timeout to be a float.
840
  $options['timeout'] = (float) $options['timeout'];
841

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

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

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

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

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

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

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

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

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

    
928
    return $result;
929
  }
930

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

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

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

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

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

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

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

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

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

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

    
1019
  $result->headers = array();
1020

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

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

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

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

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

    
1122
  return $result;
1123
}
1124

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

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

    
1167
/**
1168
 * @} End of "HTTP handling".
1169
 */
1170

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

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

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

    
1232
/**
1233
 * @defgroup validation Input validation
1234
 * @{
1235
 * Functions to validate user input.
1236
 */
1237

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

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

    
1292
/**
1293
 * @} End of "defgroup validation".
1294
 */
1295

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

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

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

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

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

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

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

    
1432
  return $uri;
1433
}
1434

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

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

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

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

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

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

    
1546
  if ($store) {
1547
    $allowed_html = array_flip($m);
1548
    return;
1549
  }
1550

    
1551
  $string = $m[1];
1552

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

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

    
1567
  $slash = trim($matches[1]);
1568
  $elem = &$matches[2];
1569
  $attrlist = &$matches[3];
1570
  $comment = &$matches[4];
1571

    
1572
  if ($comment) {
1573
    $elem = '!--';
1574
  }
1575

    
1576
  if (!isset($allowed_html[strtolower($elem)])) {
1577
    // Disallowed HTML element.
1578
    return '';
1579
  }
1580

    
1581
  if ($comment) {
1582
    return $comment;
1583
  }
1584

    
1585
  if ($slash != '') {
1586
    return "</$elem>";
1587
  }
1588

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

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

    
1598
  return "<$elem$attr2$xhtml_slash>";
1599
}
1600

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

    
1612
  while (strlen($attr) != 0) {
1613
    // Was the last operation successful?
1614
    $working = 0;
1615

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

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

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

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

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

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

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

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

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

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

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

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

    
1728
    $string = decode_entities($string);
1729
  }
1730
  return check_plain(drupal_strip_dangerous_protocols($string));
1731
}
1732

    
1733
/**
1734
 * @} End of "defgroup sanitization".
1735
 */
1736

    
1737
/**
1738
 * @defgroup format Formatting
1739
 * @{
1740
 * Functions to format numbers, strings, dates, etc.
1741
 */
1742

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

    
1752
  $output = "<channel>\n";
1753
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1754
  $output .= ' <link>' . check_url($link) . "</link>\n";
1755

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

    
1765
  return $output;
1766
}
1767

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

    
1781
  return $output;
1782
}
1783

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

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

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

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

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

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

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

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

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

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

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

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

    
2059
    case 'long':
2060
      $format = variable_get('date_format_long', 'l, F j, Y - H:i');
2061
      break;
2062

    
2063
    case 'custom':
2064
      // No change to format.
2065
      break;
2066

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

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

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

    
2092
  // Call date_format().
2093
  $format = date_format($date_time, $format);
2094

    
2095
  // Pass the langcode to _format_date_callback().
2096
  _format_date_callback(NULL, $langcode);
2097

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

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

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

    
2128
  if (!isset($matches)) {
2129
    $langcode = $new_langcode;
2130
    return;
2131
  }
2132

    
2133
  $code = $matches[1];
2134
  $string = $matches[2];
2135

    
2136
  if (!isset($cache[$langcode][$code][$string])) {
2137
    $options = array(
2138
      'langcode' => $langcode,
2139
    );
2140

    
2141
    if ($code == 'F') {
2142
      $options['context'] = 'Long month name';
2143
    }
2144

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

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

    
2181
/**
2182
 * @} End of "defgroup format".
2183
 */
2184

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

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

    
2267
  // Preserve the original path before altering or aliasing.
2268
  $original_path = $path;
2269

    
2270
  // Allow other modules to alter the outbound URL and options.
2271
  drupal_alter('url_outbound', $path, $options, $original_path);
2272

    
2273
  if (isset($options['fragment']) && $options['fragment'] !== '') {
2274
    $options['fragment'] = '#' . $options['fragment'];
2275
  }
2276

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

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

    
2307
  global $base_url, $base_secure_url, $base_insecure_url;
2308

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

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

    
2341
  $base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
2342
  $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
2343

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

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

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

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

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

    
2521
  // Merge in defaults.
2522
  $options += array(
2523
    'attributes' => array(),
2524
    'html' => FALSE,
2525
  );
2526

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

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

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

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

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

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

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

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

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

    
2702
        // Check for and return a fast 404 page if configured.
2703
        drupal_fast_404();
2704

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

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

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

    
2727
        drupal_set_page_content($return);
2728
        $page = element_info('page');
2729
        print drupal_render_page($page);
2730
        break;
2731

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

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

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

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

    
2759
        print drupal_render_page($return);
2760
        break;
2761

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

    
2778
  // Perform end-of-request tasks.
2779
  drupal_page_footer();
2780
}
2781

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

    
2791
  module_invoke_all('exit');
2792

    
2793
  // Commit the user session, if needed.
2794
  drupal_session_commit();
2795

    
2796
  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
2797
    drupal_serve_page_from_cache($cache);
2798
  }
2799
  else {
2800
    ob_flush();
2801
  }
2802

    
2803
  _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
2804
  drupal_cache_system_paths();
2805
  module_implements_write_cache();
2806
  drupal_file_scan_write_cache();
2807
  system_run_automated_cron();
2808
}
2809

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

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

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

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

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

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

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

    
2953
  drupal_add_html_head($element, 'drupal_add_html_head_link:' . $attributes['rel'] . ':' . $href);
2954
}
2955

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

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

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

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

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

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

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

    
3133
  return $css;
3134
}
3135

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

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

    
3175
  // Sort CSS items, so that they appear in the correct order.
3176
  uasort($css, 'drupal_sort_css_js');
3177

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

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

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

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

    
3214
  return drupal_render($styles);
3215
}
3216

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

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

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

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

    
3362
    // Add the item to the current group.
3363
    $groups[$i]['items'][] = $item;
3364
  }
3365
  return $groups;
3366
}
3367

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

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

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

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

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

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

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

    
3636
  return $elements;
3637
}
3638

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3945
  // By default, we filter using Drupal's coding standards.
3946
  $identifier = strtr($identifier, $filter);
3947

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

    
3958
  return $identifier;
3959
}
3960

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

    
3978
  if (!isset($classes[$class])) {
3979
    $classes[$class] = drupal_clean_css_identifier(drupal_strtolower($class));
3980
  }
3981
  return $classes[$class];
3982
}
3983

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

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

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

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

    
4094
  return $id;
4095
}
4096

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

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

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

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

    
4299
  // Preprocess can only be set if caching is enabled.
4300
  $options['preprocess'] = $options['cache'] ? $options['preprocess'] : FALSE;
4301

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

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

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

    
4356
      case 'inline':
4357
        $javascript[] = $options;
4358
        break;
4359

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

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

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

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

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

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

    
4453
  // Sort the JavaScript so that it appears in the correct order.
4454
  uasort($items, 'drupal_sort_css_js');
4455

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

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

    
4472
  $elements = array(
4473
    '#type' => 'scripts',
4474
    '#items' => $items,
4475
  );
4476

    
4477
  return drupal_render($elements);
4478
}
4479

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

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

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

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

    
4521
  $files = array();
4522

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

    
4526
  $settings = isset($elements['settings']) ? $elements['settings'] : array();
4527
  $settings += array('#weight' => $scripts['#weight'] + 10);
4528

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

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

    
4543
  foreach ($elements['#items'] as $item) {
4544
    $query_string =  empty($item['version']) ? $default_query_string : $js_version_string . $item['version'];
4545

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

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

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

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

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

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

    
4623
  return $element;
4624
}
4625

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

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

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

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

    
4744
  return $success;
4745
}
4746

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

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

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

    
4924
  return $added[$module][$name];
4925
}
4926

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

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

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

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

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

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

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

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

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

    
5217
  if (!isset($php530)) {
5218
    $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
5219
  }
5220

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

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

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

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

    
5255
  if (isset($var)) {
5256
    echo drupal_json_encode($var);
5257
  }
5258
}
5259

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

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

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

    
5315
function _drupal_bootstrap_full() {
5316
  static $called = FALSE;
5317

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

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

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

    
5363
  // Initialize $_GET['q'] prior to invoking hook_init().
5364
  drupal_path_initialize();
5365

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

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

    
5398
  if (drupal_page_is_cacheable()) {
5399

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

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

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

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

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

    
5451
  // Prevent session information from being saved while cron is running.
5452
  $original_session_saving = drupal_save_session();
5453
  drupal_save_session(FALSE);
5454

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

    
5460
  // Try to allocate enough time to run all the hook_cron implementations.
5461
  drupal_set_time_limit(240);
5462

    
5463
  $return = FALSE;
5464
  // Grab the defined cron queues.
5465
  $queues = module_invoke_all('cron_queue_info');
5466
  drupal_alter('cron_queue_info', $queues);
5467

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

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

    
5491
    // Record cron time.
5492
    variable_set('cron_last', REQUEST_TIME);
5493
    watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
5494

    
5495
    // Release cron lock.
5496
    lock_release('cron');
5497

    
5498
    // Return TRUE so other functions can check if it did run successfully
5499
    $return = TRUE;
5500
  }
5501

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

    
5526
  return $return;
5527
}
5528

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

    
5543
    // Release cron semaphore.
5544
    variable_del('cron_semaphore');
5545
  }
5546
}
5547

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

    
5599
  $searchdir = array($directory);
5600
  $files = array();
5601

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

    
5626
  // Always search sites/all/* as well as the global directories.
5627
  $searchdir[] = 'sites/all/' . $directory;
5628

    
5629
  if (file_exists("$config/$directory")) {
5630
    $searchdir[] = "$config/$directory";
5631
  }
5632

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

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

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

    
5665
  return $files;
5666
}
5667

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

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

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

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

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

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

    
5772
  return $elements;
5773
}
5774

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

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

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

    
5825
  $element['#markup'] = l($element['#title'], $element['#href'], $element['#options']);
5826
  return $element;
5827
}
5828

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

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

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

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

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

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

    
5982
  return drupal_render($page);
5983
}
5984

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

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

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

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

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

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

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

    
6109
  // Get the children of the element, sorted by weight.
6110
  $children = element_children($elements, TRUE);
6111

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

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

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

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

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

    
6161
  $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
6162
  $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
6163
  $output = $prefix . $elements['#children'] . $suffix;
6164

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

    
6170
  $elements['#printed'] = TRUE;
6171
  return $output;
6172
}
6173

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
6483
    if ($granularity & DRUPAL_CACHE_PER_PAGE) {
6484
      $cid_parts[] = $base_root . request_uri();
6485
    }
6486
  }
6487

    
6488
  return $cid_parts;
6489
}
6490

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

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

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

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

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

    
6561
  return isset($cache[$type]) ? $cache[$type] : array();
6562
}
6563

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

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

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

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

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

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

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

    
6655
  // Filter out properties from the element, leaving only children.
6656
  $count = count($elements);
6657
  $child_weights = array();
6658
  $i = 0;
6659
  $sortable = FALSE;
6660
  foreach ($elements as $key => $value) {
6661
    if (is_int($key) || $key === '' || $key[0] !== '#') {
6662
      if (is_array($value) && isset($value['#weight'])) {
6663
        $weight = $value['#weight'];
6664
        $sortable = TRUE;
6665
      }
6666
      else {
6667
        $weight = 0;
6668
      }
6669
      // Support weights with up to three digit precision and conserve the
6670
      // insertion order.
6671
      $child_weights[$key] = floor($weight * 1000) + $i / $count;
6672
    }
6673
    $i++;
6674
  }
6675

    
6676
  // Sort the children if necessary.
6677
  if ($sort && $sortable) {
6678
    asort($child_weights);
6679
    // Put the sorted children back into $elements in the correct order, to
6680
    // preserve sorting if the same element is passed through
6681
    // element_children() twice.
6682
    foreach ($child_weights as $key => $weight) {
6683
      $value = $elements[$key];
6684
      unset($elements[$key]);
6685
      $elements[$key] = $value;
6686
    }
6687
    $elements['#sorted'] = TRUE;
6688
  }
6689

    
6690
  return array_keys($child_weights);
6691
}
6692

    
6693
/**
6694
 * Returns the visible children of an element.
6695
 *
6696
 * @param $elements
6697
 *   The parent element.
6698
 *
6699
 * @return
6700
 *   The array keys of the element's visible children.
6701
 */
6702
function element_get_visible_children(array $elements) {
6703
  $visible_children = array();
6704

    
6705
  foreach (element_children($elements) as $key) {
6706
    $child = $elements[$key];
6707

    
6708
    // Skip un-accessible children.
6709
    if (isset($child['#access']) && !$child['#access']) {
6710
      continue;
6711
    }
6712

    
6713
    // Skip value and hidden elements, since they are not rendered.
6714
    if (isset($child['#type']) && in_array($child['#type'], array('value', 'hidden'))) {
6715
      continue;
6716
    }
6717

    
6718
    $visible_children[$key] = $child;
6719
  }
6720

    
6721
  return array_keys($visible_children);
6722
}
6723

    
6724
/**
6725
 * Sets HTML attributes based on element properties.
6726
 *
6727
 * @param $element
6728
 *   The renderable element to process.
6729
 * @param $map
6730
 *   An associative array whose keys are element property names and whose values
6731
 *   are the HTML attribute names to set for corresponding the property; e.g.,
6732
 *   array('#propertyname' => 'attributename'). If both names are identical
6733
 *   except for the leading '#', then an attribute name value is sufficient and
6734
 *   no property name needs to be specified.
6735
 */
6736
function element_set_attributes(array &$element, array $map) {
6737
  foreach ($map as $property => $attribute) {
6738
    // If the key is numeric, the attribute name needs to be taken over.
6739
    if (is_int($property)) {
6740
      $property = '#' . $attribute;
6741
    }
6742
    // Do not overwrite already existing attributes.
6743
    if (isset($element[$property]) && !isset($element['#attributes'][$attribute])) {
6744
      $element['#attributes'][$attribute] = $element[$property];
6745
    }
6746
  }
6747
}
6748

    
6749
/**
6750
 * Recursively computes the difference of arrays with additional index check.
6751
 *
6752
 * This is a version of array_diff_assoc() that supports multidimensional
6753
 * arrays.
6754
 *
6755
 * @param array $array1
6756
 *   The array to compare from.
6757
 * @param array $array2
6758
 *   The array to compare to.
6759
 *
6760
 * @return array
6761
 *   Returns an array containing all the values from array1 that are not present
6762
 *   in array2.
6763
 */
6764
function drupal_array_diff_assoc_recursive($array1, $array2) {
6765
  $difference = array();
6766

    
6767
  foreach ($array1 as $key => $value) {
6768
    if (is_array($value)) {
6769
      if (!array_key_exists($key, $array2) || !is_array($array2[$key])) {
6770
        $difference[$key] = $value;
6771
      }
6772
      else {
6773
        $new_diff = drupal_array_diff_assoc_recursive($value, $array2[$key]);
6774
        if (!empty($new_diff)) {
6775
          $difference[$key] = $new_diff;
6776
        }
6777
      }
6778
    }
6779
    elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
6780
      $difference[$key] = $value;
6781
    }
6782
  }
6783

    
6784
  return $difference;
6785
}
6786

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

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

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

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

    
7182
/**
7183
 * @addtogroup schemaapi
7184
 * @{
7185
 */
7186

    
7187
/**
7188
 * Creates all tables defined in a module's hook_schema().
7189
 *
7190
 * Note: This function does not pass the module's schema through
7191
 * hook_schema_alter(). The module's tables will be created exactly as the
7192
 * module defines them.
7193
 *
7194
 * @param $module
7195
 *   The module for which the tables will be created.
7196
 */
7197
function drupal_install_schema($module) {
7198
  $schema = drupal_get_schema_unprocessed($module);
7199
  _drupal_schema_initialize($schema, $module, FALSE);
7200

    
7201
  foreach ($schema as $name => $table) {
7202
    db_create_table($name, $table);
7203
  }
7204
}
7205

    
7206
/**
7207
 * Removes all tables defined in a module's hook_schema().
7208
 *
7209
 * Note: This function does not pass the module's schema through
7210
 * hook_schema_alter(). The module's tables will be created exactly as the
7211
 * module defines them.
7212
 *
7213
 * @param $module
7214
 *   The module for which the tables will be removed.
7215
 *
7216
 * @return
7217
 *   An array of arrays with the following key/value pairs:
7218
 *    - success: a boolean indicating whether the query succeeded.
7219
 *    - query: the SQL query(s) executed, passed through check_plain().
7220
 */
7221
function drupal_uninstall_schema($module) {
7222
  $schema = drupal_get_schema_unprocessed($module);
7223
  _drupal_schema_initialize($schema, $module, FALSE);
7224

    
7225
  foreach ($schema as $table) {
7226
    if (db_table_exists($table['name'])) {
7227
      db_drop_table($table['name']);
7228
    }
7229
  }
7230
}
7231

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

    
7262
  if (isset($table) && isset($schema[$table])) {
7263
    return $schema[$table];
7264
  }
7265
  elseif (!empty($schema)) {
7266
    return $schema;
7267
  }
7268
  return array();
7269
}
7270

    
7271
/**
7272
 * Fills in required default values for table definitions from hook_schema().
7273
 *
7274
 * @param $schema
7275
 *   The schema definition array as it was returned by the module's
7276
 *   hook_schema().
7277
 * @param $module
7278
 *   The module for which hook_schema() was invoked.
7279
 * @param $remove_descriptions
7280
 *   (optional) Whether to additionally remove 'description' keys of all tables
7281
 *   and fields to improve performance of serialize() and unserialize().
7282
 *   Defaults to TRUE.
7283
 */
7284
function _drupal_schema_initialize(&$schema, $module, $remove_descriptions = TRUE) {
7285
  // Set the name and module key for all tables.
7286
  foreach ($schema as $name => &$table) {
7287
    if (empty($table['module'])) {
7288
      $table['module'] = $module;
7289
    }
7290
    if (!isset($table['name'])) {
7291
      $table['name'] = $name;
7292
    }
7293
    if ($remove_descriptions) {
7294
      unset($table['description']);
7295
      foreach ($table['fields'] as &$field) {
7296
        unset($field['description']);
7297
      }
7298
    }
7299
  }
7300
}
7301

    
7302
/**
7303
 * Retrieves the type for every field in a table schema.
7304
 *
7305
 * @param $table
7306
 *   The name of the table from which to retrieve type information.
7307
 *
7308
 * @return
7309
 *   An array of types, keyed by field name.
7310
 */
7311
function drupal_schema_field_types($table) {
7312
  $table_schema = drupal_get_schema($table);
7313
  $field_types = array();
7314
  foreach ($table_schema['fields'] as $field_name => $field_info) {
7315
    $field_types[$field_name] = isset($field_info['type']) ? $field_info['type'] : NULL;
7316
  }
7317
  return $field_types;
7318
}
7319

    
7320
/**
7321
 * Retrieves a list of fields from a table schema.
7322
 *
7323
 * The returned list is suitable for use in an SQL query.
7324
 *
7325
 * @param $table
7326
 *   The name of the table from which to retrieve fields.
7327
 * @param
7328
 *   An optional prefix to to all fields.
7329
 *
7330
 * @return An array of fields.
7331
 */
7332
function drupal_schema_fields_sql($table, $prefix = NULL) {
7333
  $schema = drupal_get_schema($table);
7334
  $fields = array_keys($schema['fields']);
7335
  if ($prefix) {
7336
    $columns = array();
7337
    foreach ($fields as $field) {
7338
      $columns[] = "$prefix.$field";
7339
    }
7340
    return $columns;
7341
  }
7342
  else {
7343
    return $fields;
7344
  }
7345
}
7346

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

    
7380
  $schema = drupal_get_schema($table);
7381
  if (empty($schema)) {
7382
    return FALSE;
7383
  }
7384

    
7385
  $object = (object) $record;
7386
  $fields = array();
7387

    
7388
  // Go through the schema to determine fields to write.
7389
  foreach ($schema['fields'] as $field => $info) {
7390
    if ($info['type'] == 'serial') {
7391
      // Skip serial types if we are updating.
7392
      if (!empty($primary_keys)) {
7393
        continue;
7394
      }
7395
      // Track serial field so we can helpfully populate them after the query.
7396
      // NOTE: Each table should come with one serial field only.
7397
      $serial = $field;
7398
    }
7399

    
7400
    // Skip field if it is in $primary_keys as it is unnecessary to update a
7401
    // field to the value it is already set to.
7402
    if (in_array($field, $primary_keys)) {
7403
      continue;
7404
    }
7405

    
7406
    if (!property_exists($object, $field)) {
7407
      // Skip fields that are not provided, default values are already known
7408
      // by the database.
7409
      continue;
7410
    }
7411

    
7412
    // Build array of fields to update or insert.
7413
    if (empty($info['serialize'])) {
7414
      $fields[$field] = $object->$field;
7415
    }
7416
    else {
7417
      $fields[$field] = serialize($object->$field);
7418
    }
7419

    
7420
    // Type cast to proper datatype, except when the value is NULL and the
7421
    // column allows this.
7422
    //
7423
    // MySQL PDO silently casts e.g. FALSE and '' to 0 when inserting the value
7424
    // into an integer column, but PostgreSQL PDO does not. Also type cast NULL
7425
    // when the column does not allow this.
7426
    if (isset($object->$field) || !empty($info['not null'])) {
7427
      if ($info['type'] == 'int' || $info['type'] == 'serial') {
7428
        $fields[$field] = (int) $fields[$field];
7429
      }
7430
      elseif ($info['type'] == 'float') {
7431
        $fields[$field] = (float) $fields[$field];
7432
      }
7433
      else {
7434
        $fields[$field] = (string) $fields[$field];
7435
      }
7436
    }
7437
  }
7438

    
7439
  if (empty($fields)) {
7440
    return;
7441
  }
7442

    
7443
  // Build the SQL.
7444
  if (empty($primary_keys)) {
7445
    // We are doing an insert.
7446
    $options = array('return' => Database::RETURN_INSERT_ID);
7447
    if (isset($serial) && isset($fields[$serial])) {
7448
      // If the serial column has been explicitly set with an ID, then we don't
7449
      // require the database to return the last insert id.
7450
      if ($fields[$serial]) {
7451
        $options['return'] = Database::RETURN_AFFECTED;
7452
      }
7453
      // If a serial column does exist with no value (i.e. 0) then remove it as
7454
      // the database will insert the correct value for us.
7455
      else {
7456
        unset($fields[$serial]);
7457
      }
7458
    }
7459
    $query = db_insert($table, $options)->fields($fields);
7460
    $return = SAVED_NEW;
7461
  }
7462
  else {
7463
    $query = db_update($table)->fields($fields);
7464
    foreach ($primary_keys as $key) {
7465
      $query->condition($key, $object->$key);
7466
    }
7467
    $return = SAVED_UPDATED;
7468
  }
7469

    
7470
  // Execute the SQL.
7471
  if ($query_return = $query->execute()) {
7472
    if (isset($serial)) {
7473
      // If the database was not told to return the last insert id, it will be
7474
      // because we already know it.
7475
      if (isset($options) && $options['return'] != Database::RETURN_INSERT_ID) {
7476
        $object->$serial = $fields[$serial];
7477
      }
7478
      else {
7479
        $object->$serial = $query_return;
7480
      }
7481
    }
7482
  }
7483
  // If we have a single-field primary key but got no insert ID, the
7484
  // query failed. Note that we explicitly check for FALSE, because
7485
  // a valid update query which doesn't change any values will return
7486
  // zero (0) affected rows.
7487
  elseif ($query_return === FALSE && count($primary_keys) == 1) {
7488
    $return = FALSE;
7489
  }
7490

    
7491
  // If we are inserting, populate empty fields with default values.
7492
  if (empty($primary_keys)) {
7493
    foreach ($schema['fields'] as $field => $info) {
7494
      if (isset($info['default']) && !property_exists($object, $field)) {
7495
        $object->$field = $info['default'];
7496
      }
7497
    }
7498
  }
7499

    
7500
  // If we began with an array, convert back.
7501
  if (is_array($record)) {
7502
    $record = (array) $object;
7503
  }
7504

    
7505
  return $return;
7506
}
7507

    
7508
/**
7509
 * @} End of "addtogroup schemaapi".
7510
 */
7511

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

    
7559
  if (!isset($info[$filename])) {
7560
    if (!file_exists($filename)) {
7561
      $info[$filename] = array();
7562
    }
7563
    else {
7564
      $data = file_get_contents($filename);
7565
      $info[$filename] = drupal_parse_info_format($data);
7566
    }
7567
  }
7568
  return $info[$filename];
7569
}
7570

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

    
7611
  if (preg_match_all('
7612
    @^\s*                           # Start at the beginning of a line, ignoring leading whitespace
7613
    ((?:
7614
      [^=;\[\]]|                    # Key names cannot contain equal signs, semi-colons or square brackets,
7615
      \[[^\[\]]*\]                  # unless they are balanced and not nested
7616
    )+?)
7617
    \s*=\s*                         # Key/value pairs are separated by equal signs (ignoring white-space)
7618
    (?:
7619
      ("(?:[^"]|(?<=\\\\)")*")|     # Double-quoted string, which may contain slash-escaped quotes/slashes
7620
      (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
7621
      ([^\r\n]*?)                   # Non-quoted string
7622
    )\s*$                           # Stop at the next end of a line, ignoring trailing whitespace
7623
    @msx', $data, $matches, PREG_SET_ORDER)) {
7624
    foreach ($matches as $match) {
7625
      // Fetch the key and value string.
7626
      $i = 0;
7627
      foreach (array('key', 'value1', 'value2', 'value3') as $var) {
7628
        $$var = isset($match[++$i]) ? $match[$i] : '';
7629
      }
7630
      $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
7631

    
7632
      // Parse array syntax.
7633
      $keys = preg_split('/\]?\[/', rtrim($key, ']'));
7634
      $last = array_pop($keys);
7635
      $parent = &$info;
7636

    
7637
      // Create nested arrays.
7638
      foreach ($keys as $key) {
7639
        if ($key == '') {
7640
          $key = count($parent);
7641
        }
7642
        if (!isset($parent[$key]) || !is_array($parent[$key])) {
7643
          $parent[$key] = array();
7644
        }
7645
        $parent = &$parent[$key];
7646
      }
7647

    
7648
      // Handle PHP constants.
7649
      if (preg_match('/^\w+$/i', $value) && defined($value)) {
7650
        $value = constant($value);
7651
      }
7652

    
7653
      // Insert actual value.
7654
      if ($last == '') {
7655
        $last = count($parent);
7656
      }
7657
      $parent[$last] = $value;
7658
    }
7659
  }
7660

    
7661
  return $info;
7662
}
7663

    
7664
/**
7665
 * Returns a list of severity levels, as defined in RFC 3164.
7666
 *
7667
 * @return
7668
 *   Array of the possible severity levels for log messages.
7669
 *
7670
 * @see http://www.ietf.org/rfc/rfc3164.txt
7671
 * @see watchdog()
7672
 * @ingroup logging_severity_levels
7673
 */
7674
function watchdog_severity_levels() {
7675
  return array(
7676
    WATCHDOG_EMERGENCY => t('emergency'),
7677
    WATCHDOG_ALERT     => t('alert'),
7678
    WATCHDOG_CRITICAL  => t('critical'),
7679
    WATCHDOG_ERROR     => t('error'),
7680
    WATCHDOG_WARNING   => t('warning'),
7681
    WATCHDOG_NOTICE    => t('notice'),
7682
    WATCHDOG_INFO      => t('info'),
7683
    WATCHDOG_DEBUG     => t('debug'),
7684
  );
7685
}
7686

    
7687

    
7688
/**
7689
 * Explodes a string of tags into an array.
7690
 *
7691
 * @see drupal_implode_tags()
7692
 */
7693
function drupal_explode_tags($tags) {
7694
  // This regexp allows the following types of user input:
7695
  // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
7696
  $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
7697
  preg_match_all($regexp, $tags, $matches);
7698
  $typed_tags = array_unique($matches[1]);
7699

    
7700
  $tags = array();
7701
  foreach ($typed_tags as $tag) {
7702
    // If a user has escaped a term (to demonstrate that it is a group,
7703
    // or includes a comma or quote character), we remove the escape
7704
    // formatting so to save the term into the database as the user intends.
7705
    $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
7706
    if ($tag != "") {
7707
      $tags[] = $tag;
7708
    }
7709
  }
7710

    
7711
  return $tags;
7712
}
7713

    
7714
/**
7715
 * Implodes an array of tags into a string.
7716
 *
7717
 * @see drupal_explode_tags()
7718
 */
7719
function drupal_implode_tags($tags) {
7720
  $encoded_tags = array();
7721
  foreach ($tags as $tag) {
7722
    // Commas and quotes in tag names are special cases, so encode them.
7723
    if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
7724
      $tag = '"' . str_replace('"', '""', $tag) . '"';
7725
    }
7726

    
7727
    $encoded_tags[] = $tag;
7728
  }
7729
  return implode(', ', $encoded_tags);
7730
}
7731

    
7732
/**
7733
 * Flushes all cached data on the site.
7734
 *
7735
 * Empties cache tables, rebuilds the menu cache and theme registries, and
7736
 * invokes a hook so that other modules' cache data can be cleared as well.
7737
 */
7738
function drupal_flush_all_caches() {
7739
  // Change query-strings on css/js files to enforce reload for all users.
7740
  _drupal_flush_css_js();
7741

    
7742
  registry_rebuild();
7743
  drupal_clear_css_cache();
7744
  drupal_clear_js_cache();
7745

    
7746
  // Rebuild the theme data. Note that the module data is rebuilt above, as
7747
  // part of registry_rebuild().
7748
  system_rebuild_theme_data();
7749
  drupal_theme_rebuild();
7750

    
7751
  entity_info_cache_clear();
7752
  node_types_rebuild();
7753
  // node_menu() defines menu items based on node types so it needs to come
7754
  // after node types are rebuilt.
7755
  menu_rebuild();
7756

    
7757
  // Synchronize to catch any actions that were added or removed.
7758
  actions_synchronize();
7759

    
7760
  // Don't clear cache_form - in-progress form submissions may break.
7761
  // Ordered so clearing the page cache will always be the last action.
7762
  $core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
7763
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
7764
  foreach ($cache_tables as $table) {
7765
    cache_clear_all('*', $table, TRUE);
7766
  }
7767

    
7768
  // Rebuild the bootstrap module list. We do this here so that developers
7769
  // can get new hook_boot() implementations registered without having to
7770
  // write a hook_update_N() function.
7771
  _system_update_bootstrap_status();
7772
}
7773

    
7774
/**
7775
 * Changes the dummy query string added to all CSS and JavaScript files.
7776
 *
7777
 * Changing the dummy query string appended to CSS and JavaScript files forces
7778
 * all browsers to reload fresh files.
7779
 */
7780
function _drupal_flush_css_js() {
7781
  // The timestamp is converted to base 36 in order to make it more compact.
7782
  variable_set('css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
7783
}
7784

    
7785
/**
7786
 * Outputs debug information.
7787
 *
7788
 * The debug information is passed on to trigger_error() after being converted
7789
 * to a string using _drupal_debug_message().
7790
 *
7791
 * @param $data
7792
 *   Data to be output.
7793
 * @param $label
7794
 *   Label to prefix the data.
7795
 * @param $print_r
7796
 *   Flag to switch between print_r() and var_export() for data conversion to
7797
 *   string. Set $print_r to TRUE when dealing with a recursive data structure
7798
 *   as var_export() will generate an error.
7799
 */
7800
function debug($data, $label = NULL, $print_r = FALSE) {
7801
  // Print $data contents to string.
7802
  $string = check_plain($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
7803

    
7804
  // Display values with pre-formatting to increase readability.
7805
  $string = '<pre>' . $string . '</pre>';
7806

    
7807
  trigger_error(trim($label ? "$label: $string" : $string));
7808
}
7809

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

    
7878
/**
7879
 * Checks whether a version is compatible with a given dependency.
7880
 *
7881
 * @param $v
7882
 *   The parsed dependency structure from drupal_parse_dependency().
7883
 * @param $current_version
7884
 *   The version to check against (like 4.2).
7885
 *
7886
 * @return
7887
 *   NULL if compatible, otherwise the original dependency version string that
7888
 *   caused the incompatibility.
7889
 *
7890
 * @see drupal_parse_dependency()
7891
 */
7892
function drupal_check_incompatibility($v, $current_version) {
7893
  if (!empty($v['versions'])) {
7894
    foreach ($v['versions'] as $required_version) {
7895
      if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
7896
        return $v['original_version'];
7897
      }
7898
    }
7899
  }
7900
}
7901

    
7902
/**
7903
 * Get the entity info array of an entity type.
7904
 *
7905
 * @param $entity_type
7906
 *   The entity type, e.g. node, for which the info shall be returned, or NULL
7907
 *   to return an array with info about all types.
7908
 *
7909
 * @see hook_entity_info()
7910
 * @see hook_entity_info_alter()
7911
 */
7912
function entity_get_info($entity_type = NULL) {
7913
  global $language;
7914

    
7915
  // Use the advanced drupal_static() pattern, since this is called very often.
7916
  static $drupal_static_fast;
7917
  if (!isset($drupal_static_fast)) {
7918
    $drupal_static_fast['entity_info'] = &drupal_static(__FUNCTION__);
7919
  }
7920
  $entity_info = &$drupal_static_fast['entity_info'];
7921

    
7922
  // hook_entity_info() includes translated strings, so each language is cached
7923
  // separately.
7924
  $langcode = $language->language;
7925

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

    
7975
  if (empty($entity_type)) {
7976
    return $entity_info;
7977
  }
7978
  elseif (isset($entity_info[$entity_type])) {
7979
    return $entity_info[$entity_type];
7980
  }
7981
}
7982

    
7983
/**
7984
 * Resets the cached information about entity types.
7985
 */
7986
function entity_info_cache_clear() {
7987
  drupal_static_reset('entity_get_info');
7988
  // Clear all languages.
7989
  cache_clear_all('entity_info:', 'cache', TRUE);
7990
}
7991

    
7992
/**
7993
 * Helper function to extract id, vid, and bundle name from an entity.
7994
 *
7995
 * @param $entity_type
7996
 *   The entity type; e.g. 'node' or 'user'.
7997
 * @param $entity
7998
 *   The entity from which to extract values.
7999
 *
8000
 * @return
8001
 *   A numerically indexed array (not a hash table) containing these
8002
 *   elements:
8003
 *   - 0: Primary ID of the entity.
8004
 *   - 1: Revision ID of the entity, or NULL if $entity_type is not versioned.
8005
 *   - 2: Bundle name of the entity, or NULL if $entity_type has no bundles.
8006
 */
8007
function entity_extract_ids($entity_type, $entity) {
8008
  $info = entity_get_info($entity_type);
8009

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

    
8014
  if (!empty($info['entity keys']['bundle'])) {
8015
    // Explicitly fail for malformed entities missing the bundle property.
8016
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
8017
      throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
8018
    }
8019
    $bundle = $entity->{$info['entity keys']['bundle']};
8020
  }
8021
  else {
8022
    // The entity type provides no bundle key: assume a single bundle, named
8023
    // after the entity type.
8024
    $bundle = $entity_type;
8025
  }
8026

    
8027
  return array($id, $vid, $bundle);
8028
}
8029

    
8030
/**
8031
 * Helper function to assemble an object structure with initial ids.
8032
 *
8033
 * This function can be seen as reciprocal to entity_extract_ids().
8034
 *
8035
 * @param $entity_type
8036
 *   The entity type; e.g. 'node' or 'user'.
8037
 * @param $ids
8038
 *   A numerically indexed array, as returned by entity_extract_ids().
8039
 *
8040
 * @return
8041
 *   An entity structure, initialized with the ids provided.
8042
 *
8043
 * @see entity_extract_ids()
8044
 */
8045
function entity_create_stub_entity($entity_type, $ids) {
8046
  $entity = new stdClass();
8047
  $info = entity_get_info($entity_type);
8048
  $entity->{$info['entity keys']['id']} = $ids[0];
8049
  if (!empty($info['entity keys']['revision']) && isset($ids[1])) {
8050
    $entity->{$info['entity keys']['revision']} = $ids[1];
8051
  }
8052
  if (!empty($info['entity keys']['bundle']) && isset($ids[2])) {
8053
    $entity->{$info['entity keys']['bundle']} = $ids[2];
8054
  }
8055
  return $entity;
8056
}
8057

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

    
8103
/**
8104
 * Loads the unchanged, i.e. not modified, entity from the database.
8105
 *
8106
 * Unlike entity_load() this function ensures the entity is directly loaded from
8107
 * the database, thus bypassing any static cache. In particular, this function
8108
 * is useful to determine changes by comparing the entity being saved to the
8109
 * stored entity.
8110
 *
8111
 * @param $entity_type
8112
 *   The entity type to load, e.g. node or user.
8113
 * @param $id
8114
 *   The ID of the entity to load.
8115
 *
8116
 * @return
8117
 *   The unchanged entity, or FALSE if the entity cannot be loaded.
8118
 */
8119
function entity_load_unchanged($entity_type, $id) {
8120
  entity_get_controller($entity_type)->resetCache(array($id));
8121
  $result = entity_get_controller($entity_type)->load(array($id));
8122
  return reset($result);
8123
}
8124

    
8125
/**
8126
 * Gets the entity controller for an entity type.
8127
 *
8128
 * @return DrupalEntityControllerInterface
8129
 *   The entity controller object for the specified entity type.
8130
 */
8131
function entity_get_controller($entity_type) {
8132
  $controllers = &drupal_static(__FUNCTION__, array());
8133
  if (!isset($controllers[$entity_type])) {
8134
    $type_info = entity_get_info($entity_type);
8135
    $class = $type_info['controller class'];
8136
    $controllers[$entity_type] = new $class($entity_type);
8137
  }
8138
  return $controllers[$entity_type];
8139
}
8140

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

    
8170
  // To ensure hooks are only run once per entity, check for an
8171
  // entity_view_prepared flag and only process items without it.
8172
  // @todo: resolve this more generally for both entity and field level hooks.
8173
  $prepare = array();
8174
  foreach ($entities as $id => $entity) {
8175
    if (empty($entity->entity_view_prepared)) {
8176
      // Add this entity to the items to be prepared.
8177
      $prepare[$id] = $entity;
8178

    
8179
      // Mark this item as prepared.
8180
      $entity->entity_view_prepared = TRUE;
8181
    }
8182
  }
8183

    
8184
  if (!empty($prepare)) {
8185
    module_invoke_all('entity_prepare_view', $prepare, $entity_type, $langcode);
8186
  }
8187
}
8188

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

    
8217
  // To ensure hooks are never run after field_attach_prepare_view() only
8218
  // process items without the entity_view_prepared flag.
8219
  $entities_by_view_mode = array();
8220
  foreach ($entities as $id => $entity) {
8221
    $entity_view_mode = $view_mode;
8222
    if (empty($entity->entity_view_prepared)) {
8223

    
8224
      // Allow modules to change the view mode.
8225
      $context = array(
8226
        'entity_type' => $entity_type,
8227
        'entity' => $entity,
8228
        'langcode' => $langcode,
8229
      );
8230
      drupal_alter('entity_view_mode', $entity_view_mode, $context);
8231
    }
8232

    
8233
    $entities_by_view_mode[$entity_view_mode][$id] = $entity;
8234
  }
8235

    
8236
  return $entities_by_view_mode;
8237
}
8238

    
8239
/**
8240
 * Returns the URI elements of an entity.
8241
 *
8242
 * @param $entity_type
8243
 *   The entity type; e.g. 'node' or 'user'.
8244
 * @param $entity
8245
 *   The entity for which to generate a path.
8246
 * @return
8247
 *   An array containing the 'path' and 'options' keys used to build the URI of
8248
 *   the entity, and matching the signature of url(). NULL if the entity has no
8249
 *   URI of its own.
8250
 */
8251
function entity_uri($entity_type, $entity) {
8252
  $info = entity_get_info($entity_type);
8253
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
8254

    
8255
  // A bundle-specific callback takes precedence over the generic one for the
8256
  // entity type.
8257
  if (isset($info['bundles'][$bundle]['uri callback'])) {
8258
    $uri_callback = $info['bundles'][$bundle]['uri callback'];
8259
  }
8260
  elseif (isset($info['uri callback'])) {
8261
    $uri_callback = $info['uri callback'];
8262
  }
8263
  else {
8264
    return NULL;
8265
  }
8266

    
8267
  // Invoke the callback to get the URI. If there is no callback, return NULL.
8268
  if (isset($uri_callback) && function_exists($uri_callback)) {
8269
    $uri = $uri_callback($entity);
8270
    // Pass the entity data to url() so that alter functions do not need to
8271
    // lookup this entity again.
8272
    $uri['options']['entity_type'] = $entity_type;
8273
    $uri['options']['entity'] = $entity;
8274
    return $uri;
8275
  }
8276
}
8277

    
8278
/**
8279
 * Returns the label of an entity.
8280
 *
8281
 * See the 'label callback' component of the hook_entity_info() return value
8282
 * for more information.
8283
 *
8284
 * @param $entity_type
8285
 *   The entity type; e.g., 'node' or 'user'.
8286
 * @param $entity
8287
 *   The entity for which to generate the label.
8288
 *
8289
 * @return
8290
 *   The entity label, or FALSE if not found.
8291
 */
8292
function entity_label($entity_type, $entity) {
8293
  $label = FALSE;
8294
  $info = entity_get_info($entity_type);
8295
  if (isset($info['label callback']) && function_exists($info['label callback'])) {
8296
    $label = $info['label callback']($entity, $entity_type);
8297
  }
8298
  elseif (!empty($info['entity keys']['label']) && isset($entity->{$info['entity keys']['label']})) {
8299
    $label = $entity->{$info['entity keys']['label']};
8300
  }
8301

    
8302
  return $label;
8303
}
8304

    
8305
/**
8306
 * Returns the language of an entity.
8307
 *
8308
 * @param $entity_type
8309
 *   The entity type; e.g., 'node' or 'user'.
8310
 * @param $entity
8311
 *   The entity for which to get the language.
8312
 *
8313
 * @return
8314
 *   A valid language code or NULL if the entity has no language support.
8315
 */
8316
function entity_language($entity_type, $entity) {
8317
  $info = entity_get_info($entity_type);
8318

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

    
8340
  return $langcode;
8341
}
8342

    
8343
/**
8344
 * Attaches field API validation to entity forms.
8345
 */
8346
function entity_form_field_validate($entity_type, $form, &$form_state) {
8347
  // All field attach API functions act on an entity object, but during form
8348
  // validation, we don't have one. $form_state contains the entity as it was
8349
  // prior to processing the current form submission, and we must not update it
8350
  // until we have fully validated the submitted input. Therefore, for
8351
  // validation, act on a pseudo entity created out of the form values.
8352
  $pseudo_entity = (object) $form_state['values'];
8353
  field_attach_form_validate($entity_type, $pseudo_entity, $form, $form_state);
8354
}
8355

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

    
8381
  // Copy top-level form values that are not for fields to entity properties,
8382
  // without changing existing entity properties that are not being edited by
8383
  // this form. Copying field values must be done using field_attach_submit().
8384
  $values_excluding_fields = $info['fieldable'] ? array_diff_key($form_state['values'], field_info_instances($entity_type, $bundle)) : $form_state['values'];
8385
  foreach ($values_excluding_fields as $key => $value) {
8386
    $entity->$key = $value;
8387
  }
8388

    
8389
  // Invoke all specified builders for copying form values to entity properties.
8390
  if (isset($form['#entity_builders'])) {
8391
    foreach ($form['#entity_builders'] as $function) {
8392
      $function($entity_type, $entity, $form, $form_state);
8393
    }
8394
  }
8395

    
8396
  // Copy field values to the entity.
8397
  if ($info['fieldable']) {
8398
    field_attach_submit($entity_type, $entity, $form, $form_state);
8399
  }
8400
}
8401

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

    
8435
/**
8436
 * Retrieves a list of all available archivers.
8437
 *
8438
 * @see hook_archiver_info()
8439
 * @see hook_archiver_info_alter()
8440
 */
8441
function archiver_get_info() {
8442
  $archiver_info = &drupal_static(__FUNCTION__, array());
8443

    
8444
  if (empty($archiver_info)) {
8445
    $cache = cache_get('archiver_info');
8446
    if ($cache === FALSE) {
8447
      // Rebuild the cache and save it.
8448
      $archiver_info = module_invoke_all('archiver_info');
8449
      drupal_alter('archiver_info', $archiver_info);
8450
      uasort($archiver_info, 'drupal_sort_weight');
8451
      cache_set('archiver_info', $archiver_info);
8452
    }
8453
    else {
8454
      $archiver_info = $cache->data;
8455
    }
8456
  }
8457

    
8458
  return $archiver_info;
8459
}
8460

    
8461
/**
8462
 * Returns a string of supported archive extensions.
8463
 *
8464
 * @return
8465
 *   A space-separated string of extensions suitable for use by the file
8466
 *   validation system.
8467
 */
8468
function archiver_get_extensions() {
8469
  $valid_extensions = array();
8470
  foreach (archiver_get_info() as $archive) {
8471
    foreach ($archive['extensions'] as $extension) {
8472
      foreach (explode('.', $extension) as $part) {
8473
        if (!in_array($part, $valid_extensions)) {
8474
          $valid_extensions[] = $part;
8475
        }
8476
      }
8477
    }
8478
  }
8479
  return implode(' ', $valid_extensions);
8480
}
8481

    
8482
/**
8483
 * Creates the appropriate archiver for the specified file.
8484
 *
8485
 * @param $file
8486
 *   The full path of the archive file. Note that stream wrapper paths are
8487
 *   supported, but not remote ones.
8488
 *
8489
 * @return
8490
 *   A newly created instance of the archiver class appropriate
8491
 *   for the specified file, already bound to that file.
8492
 *   If no appropriate archiver class was found, will return FALSE.
8493
 */
8494
function archiver_get_archiver($file) {
8495
  // Archivers can only work on local paths
8496
  $filepath = drupal_realpath($file);
8497
  if (!is_file($filepath)) {
8498
    throw new Exception(t('Archivers can only operate on local files: %file not supported', array('%file' => $file)));
8499
  }
8500
  $archiver_info = archiver_get_info();
8501

    
8502
  foreach ($archiver_info as $implementation) {
8503
    foreach ($implementation['extensions'] as $extension) {
8504
      // Because extensions may be multi-part, such as .tar.gz,
8505
      // we cannot use simpler approaches like substr() or pathinfo().
8506
      // This method isn't quite as clean but gets the job done.
8507
      // Also note that the file may not yet exist, so we cannot rely
8508
      // on fileinfo() or other disk-level utilities.
8509
      if (strrpos($filepath, '.' . $extension) === strlen($filepath) - strlen('.' . $extension)) {
8510
        return new $implementation['class']($filepath);
8511
      }
8512
    }
8513
  }
8514
}
8515

    
8516
/**
8517
 * Assembles the Drupal Updater registry.
8518
 *
8519
 * An Updater is a class that knows how to update various parts of the Drupal
8520
 * file system, for example to update modules that have newer releases, or to
8521
 * install a new theme.
8522
 *
8523
 * @return
8524
 *   The Drupal Updater class registry.
8525
 *
8526
 * @see hook_updater_info()
8527
 * @see hook_updater_info_alter()
8528
 */
8529
function drupal_get_updaters() {
8530
  $updaters = &drupal_static(__FUNCTION__);
8531
  if (!isset($updaters)) {
8532
    $updaters = module_invoke_all('updater_info');
8533
    drupal_alter('updater_info', $updaters);
8534
    uasort($updaters, 'drupal_sort_weight');
8535
  }
8536
  return $updaters;
8537
}
8538

    
8539
/**
8540
 * Assembles the Drupal FileTransfer registry.
8541
 *
8542
 * @return
8543
 *   The Drupal FileTransfer class registry.
8544
 *
8545
 * @see FileTransfer
8546
 * @see hook_filetransfer_info()
8547
 * @see hook_filetransfer_info_alter()
8548
 */
8549
function drupal_get_filetransfer_info() {
8550
  $info = &drupal_static(__FUNCTION__);
8551
  if (!isset($info)) {
8552
    // Since we have to manually set the 'file path' default for each
8553
    // module separately, we can't use module_invoke_all().
8554
    $info = array();
8555
    foreach (module_implements('filetransfer_info') as $module) {
8556
      $function = $module . '_filetransfer_info';
8557
      if (function_exists($function)) {
8558
        $result = $function();
8559
        if (isset($result) && is_array($result)) {
8560
          foreach ($result as &$values) {
8561
            if (empty($values['file path'])) {
8562
              $values['file path'] = drupal_get_path('module', $module);
8563
            }
8564
          }
8565
          $info = array_merge_recursive($info, $result);
8566
        }
8567
      }
8568
    }
8569
    drupal_alter('filetransfer_info', $info);
8570
    uasort($info, 'drupal_sort_weight');
8571
  }
8572
  return $info;
8573
}