Projet

Général

Profil

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

root / drupal7 / includes / common.inc @ cf490feb

1
<?php
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
232
  return $profile;
233
}
234

    
235

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

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

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

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

    
262
  return $breadcrumb;
263
}
264

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
445
  return $params;
446
}
447

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

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

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

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

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

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

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

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

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

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

    
620
  return $options;
621
}
622

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

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

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

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

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

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

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

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

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

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

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

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

    
800
  $result = new stdClass();
801

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

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

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

    
817
  timer_start(__FUNCTION__);
818

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

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

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

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

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

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

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

    
883
    case 'https':
884
      // Note: Only works when PHP is compiled with OpenSSL support.
885
      $port = isset($uri['port']) ? $uri['port'] : 443;
886
      $socket = 'ssl://' . $uri['host'] . ':' . $port;
887
      $options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
888
      break;
889

    
890
    default:
891
      $result->error = 'invalid schema ' . $uri['scheme'];
892
      $result->code = -1003;
893
      return $result;
894
  }
895

    
896
  if (empty($options['context'])) {
897
    $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout']);
898
  }
899
  else {
900
    // Create a stream with context. Allows verification of a SSL certificate.
901
    $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
902
  }
903

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

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

    
917
    return $result;
918
  }
919

    
920
  // Construct the path to act on.
921
  $path = isset($uri['path']) ? $uri['path'] : '/';
922
  if (isset($uri['query'])) {
923
    $path .= '?' . $uri['query'];
924
  }
925

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

    
935
  // If the server URL has a user then attempt to use basic authentication.
936
  if (isset($uri['user'])) {
937
    $options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ':'));
938
  }
939

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

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

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

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

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

    
997
  // Parse the response status line.
998
  $response_status_array = _drupal_parse_response_status(trim(array_shift($response)));
999
  $result->protocol = $response_status_array['http_version'];
1000
  $result->status_message = $response_status_array['reason_phrase'];
1001
  $code = $response_status_array['response_code'];
1002

    
1003
  $result->headers = array();
1004

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

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

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

    
1101
  return $result;
1102
}
1103

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

    
1135
/**
1136
 * Helper function for determining hosts excluded from needing a proxy.
1137
 *
1138
 * @return
1139
 *   TRUE if a proxy should be used for this host.
1140
 */
1141
function _drupal_http_use_proxy($host) {
1142
  $proxy_exceptions = variable_get('proxy_exceptions', array('localhost', '127.0.0.1'));
1143
  return !in_array(strtolower($host), $proxy_exceptions, TRUE);
1144
}
1145

    
1146
/**
1147
 * @} End of "HTTP handling".
1148
 */
1149

    
1150
/**
1151
 * Strips slashes from a string or array of strings.
1152
 *
1153
 * Callback for array_walk() within fix_gpx_magic().
1154
 *
1155
 * @param $item
1156
 *   An individual string or array of strings from superglobals.
1157
 */
1158
function _fix_gpc_magic(&$item) {
1159
  if (is_array($item)) {
1160
    array_walk($item, '_fix_gpc_magic');
1161
  }
1162
  else {
1163
    $item = stripslashes($item);
1164
  }
1165
}
1166

    
1167
/**
1168
 * Strips slashes from $_FILES items.
1169
 *
1170
 * Callback for array_walk() within fix_gpc_magic().
1171
 *
1172
 * The tmp_name key is skipped keys since PHP generates single backslashes for
1173
 * file paths on Windows systems.
1174
 *
1175
 * @param $item
1176
 *   An item from $_FILES.
1177
 * @param $key
1178
 *   The key for the item within $_FILES.
1179
 *
1180
 * @see http://php.net/manual/features.file-upload.php#42280
1181
 */
1182
function _fix_gpc_magic_files(&$item, $key) {
1183
  if ($key != 'tmp_name') {
1184
    if (is_array($item)) {
1185
      array_walk($item, '_fix_gpc_magic_files');
1186
    }
1187
    else {
1188
      $item = stripslashes($item);
1189
    }
1190
  }
1191
}
1192

    
1193
/**
1194
 * Fixes double-escaping caused by "magic quotes" in some PHP installations.
1195
 *
1196
 * @see _fix_gpc_magic()
1197
 * @see _fix_gpc_magic_files()
1198
 */
1199
function fix_gpc_magic() {
1200
  static $fixed = FALSE;
1201
  if (!$fixed && ini_get('magic_quotes_gpc')) {
1202
    array_walk($_GET, '_fix_gpc_magic');
1203
    array_walk($_POST, '_fix_gpc_magic');
1204
    array_walk($_COOKIE, '_fix_gpc_magic');
1205
    array_walk($_REQUEST, '_fix_gpc_magic');
1206
    array_walk($_FILES, '_fix_gpc_magic_files');
1207
  }
1208
  $fixed = TRUE;
1209
}
1210

    
1211
/**
1212
 * @defgroup validation Input validation
1213
 * @{
1214
 * Functions to validate user input.
1215
 */
1216

    
1217
/**
1218
 * Verifies the syntax of the given e-mail address.
1219
 *
1220
 * This uses the
1221
 * @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
1222
 *
1223
 * @param $mail
1224
 *   A string containing an e-mail address.
1225
 *
1226
 * @return
1227
 *   TRUE if the address is in a valid format.
1228
 */
1229
function valid_email_address($mail) {
1230
  return (bool)filter_var($mail, FILTER_VALIDATE_EMAIL);
1231
}
1232

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

    
1271
/**
1272
 * @} End of "defgroup validation".
1273
 */
1274

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

    
1302
/**
1303
 * Makes the flood control mechanism forget an event for the current visitor.
1304
 *
1305
 * @param $name
1306
 *   The name of an event.
1307
 * @param $identifier
1308
 *   Optional identifier (defaults to the current user's IP address).
1309
 */
1310
function flood_clear_event($name, $identifier = NULL) {
1311
  if (!isset($identifier)) {
1312
    $identifier = ip_address();
1313
  }
1314
  db_delete('flood')
1315
    ->condition('event', $name)
1316
    ->condition('identifier', $identifier)
1317
    ->execute();
1318
}
1319

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

    
1353
/**
1354
 * @defgroup sanitization Sanitization functions
1355
 * @{
1356
 * Functions to sanitize values.
1357
 *
1358
 * See http://drupal.org/writing-secure-code for information
1359
 * on writing secure code.
1360
 */
1361

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

    
1386
  if (!isset($allowed_protocols)) {
1387
    $allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal')));
1388
  }
1389

    
1390
  // Iteratively remove any invalid protocol found.
1391
  do {
1392
    $before = $uri;
1393
    $colonpos = strpos($uri, ':');
1394
    if ($colonpos > 0) {
1395
      // We found a colon, possibly a protocol. Verify.
1396
      $protocol = substr($uri, 0, $colonpos);
1397
      // If a colon is preceded by a slash, question mark or hash, it cannot
1398
      // possibly be part of the URL scheme. This must be a relative URL, which
1399
      // inherits the (safe) protocol of the base document.
1400
      if (preg_match('![/?#]!', $protocol)) {
1401
        break;
1402
      }
1403
      // Check if this is a disallowed protocol. Per RFC2616, section 3.2.3
1404
      // (URI Comparison) scheme comparison must be case-insensitive.
1405
      if (!isset($allowed_protocols[strtolower($protocol)])) {
1406
        $uri = substr($uri, $colonpos + 1);
1407
      }
1408
    }
1409
  } while ($before != $uri);
1410

    
1411
  return $uri;
1412
}
1413

    
1414
/**
1415
 * Strips dangerous protocols from a URI and encodes it for output to HTML.
1416
 *
1417
 * @param $uri
1418
 *   A plain-text URI that might contain dangerous protocols.
1419
 *
1420
 * @return
1421
 *   A URI stripped of dangerous protocols and encoded for output to an HTML
1422
 *   attribute value. Because it is already encoded, it should not be set as a
1423
 *   value within a $attributes array passed to drupal_attributes(), because
1424
 *   drupal_attributes() expects those values to be plain-text strings. To pass
1425
 *   a filtered URI to drupal_attributes(), call
1426
 *   drupal_strip_dangerous_protocols() instead.
1427
 *
1428
 * @see drupal_strip_dangerous_protocols()
1429
 */
1430
function check_url($uri) {
1431
  return check_plain(drupal_strip_dangerous_protocols($uri));
1432
}
1433

    
1434
/**
1435
 * Applies a very permissive XSS/HTML filter for admin-only use.
1436
 *
1437
 * Use only for fields where it is impractical to use the
1438
 * whole filter system, but where some (mainly inline) mark-up
1439
 * is desired (so check_plain() is not acceptable).
1440
 *
1441
 * Allows all tags that can be used inside an HTML body, save
1442
 * for scripts and styles.
1443
 */
1444
function filter_xss_admin($string) {
1445
  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'));
1446
}
1447

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

    
1486
  // Defuse all HTML entities.
1487
  $string = str_replace('&', '&amp;', $string);
1488
  // Change back only well-formed entities in our whitelist:
1489
  // Decimal numeric entities.
1490
  $string = preg_replace('/&amp;#([0-9]+;)/', '&#\1', $string);
1491
  // Hexadecimal numeric entities.
1492
  $string = preg_replace('/&amp;#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\1', $string);
1493
  // Named entities.
1494
  $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string);
1495

    
1496
  return preg_replace_callback('%
1497
    (
1498
    <(?=[^a-zA-Z!/])  # a lone <
1499
    |                 # or
1500
    <!--.*?-->        # a comment
1501
    |                 # or
1502
    <[^>]*(>|$)       # a string that starts with a <, up until the > or the end of the string
1503
    |                 # or
1504
    >                 # just a >
1505
    )%x', '_filter_xss_split', $string);
1506
}
1507

    
1508
/**
1509
 * Processes an HTML tag.
1510
 *
1511
 * @param $m
1512
 *   An array with various meaning depending on the value of $store.
1513
 *   If $store is TRUE then the array contains the allowed tags.
1514
 *   If $store is FALSE then the array has one element, the HTML tag to process.
1515
 * @param $store
1516
 *   Whether to store $m.
1517
 *
1518
 * @return
1519
 *   If the element isn't allowed, an empty string. Otherwise, the cleaned up
1520
 *   version of the HTML element.
1521
 */
1522
function _filter_xss_split($m, $store = FALSE) {
1523
  static $allowed_html;
1524

    
1525
  if ($store) {
1526
    $allowed_html = array_flip($m);
1527
    return;
1528
  }
1529

    
1530
  $string = $m[1];
1531

    
1532
  if (substr($string, 0, 1) != '<') {
1533
    // We matched a lone ">" character.
1534
    return '&gt;';
1535
  }
1536
  elseif (strlen($string) == 1) {
1537
    // We matched a lone "<" character.
1538
    return '&lt;';
1539
  }
1540

    
1541
  if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9\-]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
1542
    // Seriously malformed.
1543
    return '';
1544
  }
1545

    
1546
  $slash = trim($matches[1]);
1547
  $elem = &$matches[2];
1548
  $attrlist = &$matches[3];
1549
  $comment = &$matches[4];
1550

    
1551
  if ($comment) {
1552
    $elem = '!--';
1553
  }
1554

    
1555
  if (!isset($allowed_html[strtolower($elem)])) {
1556
    // Disallowed HTML element.
1557
    return '';
1558
  }
1559

    
1560
  if ($comment) {
1561
    return $comment;
1562
  }
1563

    
1564
  if ($slash != '') {
1565
    return "</$elem>";
1566
  }
1567

    
1568
  // Is there a closing XHTML slash at the end of the attributes?
1569
  $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
1570
  $xhtml_slash = $count ? ' /' : '';
1571

    
1572
  // Clean up attributes.
1573
  $attr2 = implode(' ', _filter_xss_attributes($attrlist));
1574
  $attr2 = preg_replace('/[<>]/', '', $attr2);
1575
  $attr2 = strlen($attr2) ? ' ' . $attr2 : '';
1576

    
1577
  return "<$elem$attr2$xhtml_slash>";
1578
}
1579

    
1580
/**
1581
 * Processes a string of HTML attributes.
1582
 *
1583
 * @return
1584
 *   Cleaned up version of the HTML attributes.
1585
 */
1586
function _filter_xss_attributes($attr) {
1587
  $attrarr = array();
1588
  $mode = 0;
1589
  $attrname = '';
1590

    
1591
  while (strlen($attr) != 0) {
1592
    // Was the last operation successful?
1593
    $working = 0;
1594

    
1595
    switch ($mode) {
1596
      case 0:
1597
        // Attribute name, href for instance.
1598
        if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
1599
          $attrname = strtolower($match[1]);
1600
          $skip = ($attrname == 'style' || substr($attrname, 0, 2) == 'on');
1601
          $working = $mode = 1;
1602
          $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
1603
        }
1604
        break;
1605

    
1606
      case 1:
1607
        // Equals sign or valueless ("selected").
1608
        if (preg_match('/^\s*=\s*/', $attr)) {
1609
          $working = 1; $mode = 2;
1610
          $attr = preg_replace('/^\s*=\s*/', '', $attr);
1611
          break;
1612
        }
1613

    
1614
        if (preg_match('/^\s+/', $attr)) {
1615
          $working = 1; $mode = 0;
1616
          if (!$skip) {
1617
            $attrarr[] = $attrname;
1618
          }
1619
          $attr = preg_replace('/^\s+/', '', $attr);
1620
        }
1621
        break;
1622

    
1623
      case 2:
1624
        // Attribute value, a URL after href= for instance.
1625
        if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
1626
          $thisval = filter_xss_bad_protocol($match[1]);
1627

    
1628
          if (!$skip) {
1629
            $attrarr[] = "$attrname=\"$thisval\"";
1630
          }
1631
          $working = 1;
1632
          $mode = 0;
1633
          $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
1634
          break;
1635
        }
1636

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

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

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

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

    
1660
    if ($working == 0) {
1661
      // Not well formed; remove and try again.
1662
      $attr = preg_replace('/
1663
        ^
1664
        (
1665
        "[^"]*("|$)     # - a string that starts with a double quote, up until the next double quote or the end of the string
1666
        |               # or
1667
        \'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
1668
        |               # or
1669
        \S              # - a non-whitespace character
1670
        )*              # any number of the above three
1671
        \s*             # any number of whitespaces
1672
        /x', '', $attr);
1673
      $mode = 0;
1674
    }
1675
  }
1676

    
1677
  // The attribute list ends with a valueless attribute like "selected".
1678
  if ($mode == 1 && !$skip) {
1679
    $attrarr[] = $attrname;
1680
  }
1681
  return $attrarr;
1682
}
1683

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

    
1707
    $string = decode_entities($string);
1708
  }
1709
  return check_plain(drupal_strip_dangerous_protocols($string));
1710
}
1711

    
1712
/**
1713
 * @} End of "defgroup sanitization".
1714
 */
1715

    
1716
/**
1717
 * @defgroup format Formatting
1718
 * @{
1719
 * Functions to format numbers, strings, dates, etc.
1720
 */
1721

    
1722
/**
1723
 * Formats an RSS channel.
1724
 *
1725
 * Arbitrary elements may be added using the $args associative array.
1726
 */
1727
function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
1728
  global $language_content;
1729
  $langcode = $langcode ? $langcode : $language_content->language;
1730

    
1731
  $output = "<channel>\n";
1732
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1733
  $output .= ' <link>' . check_url($link) . "</link>\n";
1734

    
1735
  // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
1736
  // We strip all HTML tags, but need to prevent double encoding from properly
1737
  // escaped source data (such as &amp becoming &amp;amp;).
1738
  $output .= ' <description>' . check_plain(decode_entities(strip_tags($description))) . "</description>\n";
1739
  $output .= ' <language>' . check_plain($langcode) . "</language>\n";
1740
  $output .= format_xml_elements($args);
1741
  $output .= $items;
1742
  $output .= "</channel>\n";
1743

    
1744
  return $output;
1745
}
1746

    
1747
/**
1748
 * Formats a single RSS item.
1749
 *
1750
 * Arbitrary elements may be added using the $args associative array.
1751
 */
1752
function format_rss_item($title, $link, $description, $args = array()) {
1753
  $output = "<item>\n";
1754
  $output .= ' <title>' . check_plain($title) . "</title>\n";
1755
  $output .= ' <link>' . check_url($link) . "</link>\n";
1756
  $output .= ' <description>' . check_plain($description) . "</description>\n";
1757
  $output .= format_xml_elements($args);
1758
  $output .= "</item>\n";
1759

    
1760
  return $output;
1761
}
1762

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

    
1793
        if (isset($value['value']) && $value['value'] != '') {
1794
          $output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : (!empty($value['encoded']) ? $value['value'] : check_plain($value['value']))) . '</' . $value['key'] . ">\n";
1795
        }
1796
        else {
1797
          $output .= " />\n";
1798
        }
1799
      }
1800
    }
1801
    else {
1802
      $output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</$key>\n";
1803
    }
1804
  }
1805
  return $output;
1806
}
1807

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

    
1859
  // Get the plural index through the gettext formula.
1860
  $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, isset($options['langcode']) ? $options['langcode'] : NULL) : -1;
1861
  // If the index cannot be computed, use the plural as a fallback (which
1862
  // allows for most flexiblity with the replaceable @count value).
1863
  if ($index < 0) {
1864
    return t($plural, $args, $options);
1865
  }
1866
  else {
1867
    switch ($index) {
1868
      case "0":
1869
        return t($singular, $args, $options);
1870
      case "1":
1871
        return t($plural, $args, $options);
1872
      default:
1873
        unset($args['@count']);
1874
        $args['@count[' . $index . ']'] = $count;
1875
        return t(strtr($plural, array('@count' => '@count[' . $index . ']')), $args, $options);
1876
    }
1877
  }
1878
}
1879

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

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

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

    
1975
    if ($granularity == 0) {
1976
      break;
1977
    }
1978
  }
1979
  return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
1980
}
1981

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

    
2018
  if (!isset($timezone)) {
2019
    $timezone = date_default_timezone_get();
2020
  }
2021
  // Store DateTimeZone objects in an array rather than repeatedly
2022
  // constructing identical objects over the life of a request.
2023
  if (!isset($timezones[$timezone])) {
2024
    $timezones[$timezone] = timezone_open($timezone);
2025
  }
2026

    
2027
  // Use the default langcode if none is set.
2028
  global $language;
2029
  if (empty($langcode)) {
2030
    $langcode = isset($language->language) ? $language->language : 'en';
2031
  }
2032

    
2033
  switch ($type) {
2034
    case 'short':
2035
      $format = variable_get('date_format_short', 'm/d/Y - H:i');
2036
      break;
2037

    
2038
    case 'long':
2039
      $format = variable_get('date_format_long', 'l, F j, Y - H:i');
2040
      break;
2041

    
2042
    case 'custom':
2043
      // No change to format.
2044
      break;
2045

    
2046
    case 'medium':
2047
    default:
2048
      // Retrieve the format of the custom $type passed.
2049
      if ($type != 'medium') {
2050
        $format = variable_get('date_format_' . $type, '');
2051
      }
2052
      // Fall back to 'medium'.
2053
      if ($format === '') {
2054
        $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
2055
      }
2056
      break;
2057
  }
2058

    
2059
  // Create a DateTime object from the timestamp.
2060
  $date_time = date_create('@' . $timestamp);
2061
  // Set the time zone for the DateTime object.
2062
  date_timezone_set($date_time, $timezones[$timezone]);
2063

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

    
2071
  // Call date_format().
2072
  $format = date_format($date_time, $format);
2073

    
2074
  // Pass the langcode to _format_date_callback().
2075
  _format_date_callback(NULL, $langcode);
2076

    
2077
  // Translate the marked sequences.
2078
  return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);
2079
}
2080

    
2081
/**
2082
 * Returns an ISO8601 formatted date based on the given date.
2083
 *
2084
 * Callback for use within hook_rdf_mapping() implementations.
2085
 *
2086
 * @param $date
2087
 *   A UNIX timestamp.
2088
 *
2089
 * @return string
2090
 *   An ISO8601 formatted date.
2091
 */
2092
function date_iso8601($date) {
2093
  // The DATE_ISO8601 constant cannot be used here because it does not match
2094
  // date('c') and produces invalid RDF markup.
2095
  return date('c', $date);
2096
}
2097

    
2098
/**
2099
 * Translates a formatted date string.
2100
 *
2101
 * Callback for preg_replace_callback() within format_date().
2102
 */
2103
function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
2104
  // We cache translations to avoid redundant and rather costly calls to t().
2105
  static $cache, $langcode;
2106

    
2107
  if (!isset($matches)) {
2108
    $langcode = $new_langcode;
2109
    return;
2110
  }
2111

    
2112
  $code = $matches[1];
2113
  $string = $matches[2];
2114

    
2115
  if (!isset($cache[$langcode][$code][$string])) {
2116
    $options = array(
2117
      'langcode' => $langcode,
2118
    );
2119

    
2120
    if ($code == 'F') {
2121
      $options['context'] = 'Long month name';
2122
    }
2123

    
2124
    if ($code == '') {
2125
      $cache[$langcode][$code][$string] = $string;
2126
    }
2127
    else {
2128
      $cache[$langcode][$code][$string] = t($string, array(), $options);
2129
    }
2130
  }
2131
  return $cache[$langcode][$code][$string];
2132
}
2133

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

    
2160
/**
2161
 * @} End of "defgroup format".
2162
 */
2163

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

    
2239
  // Determine whether this is an external link, but ensure that the current
2240
  // path is always treated as internal by default (to prevent external link
2241
  // injection vulnerabilities).
2242
  if (!isset($options['external'])) {
2243
    $options['external'] = $path === $_GET['q'] ? FALSE : url_is_external($path);
2244
  }
2245

    
2246
  // Preserve the original path before altering or aliasing.
2247
  $original_path = $path;
2248

    
2249
  // Allow other modules to alter the outbound URL and options.
2250
  drupal_alter('url_outbound', $path, $options, $original_path);
2251

    
2252
  if (isset($options['fragment']) && $options['fragment'] !== '') {
2253
    $options['fragment'] = '#' . $options['fragment'];
2254
  }
2255

    
2256
  if ($options['external']) {
2257
    // Split off the fragment.
2258
    if (strpos($path, '#') !== FALSE) {
2259
      list($path, $old_fragment) = explode('#', $path, 2);
2260
      // If $options contains no fragment, take it over from the path.
2261
      if (isset($old_fragment) && !$options['fragment']) {
2262
        $options['fragment'] = '#' . $old_fragment;
2263
      }
2264
    }
2265
    // Append the query.
2266
    if ($options['query']) {
2267
      $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($options['query']);
2268
    }
2269
    if (isset($options['https']) && variable_get('https', FALSE)) {
2270
      if ($options['https'] === TRUE) {
2271
        $path = str_replace('http://', 'https://', $path);
2272
      }
2273
      elseif ($options['https'] === FALSE) {
2274
        $path = str_replace('https://', 'http://', $path);
2275
      }
2276
    }
2277
    // Reassemble.
2278
    return $path . $options['fragment'];
2279
  }
2280

    
2281
  // Strip leading slashes from internal paths to prevent them becoming external
2282
  // URLs without protocol. /example.com should not be turned into
2283
  // //example.com.
2284
  $path = ltrim($path, '/');
2285

    
2286
  global $base_url, $base_secure_url, $base_insecure_url;
2287

    
2288
  // The base_url might be rewritten from the language rewrite in domain mode.
2289
  if (!isset($options['base_url'])) {
2290
    if (isset($options['https']) && variable_get('https', FALSE)) {
2291
      if ($options['https'] === TRUE) {
2292
        $options['base_url'] = $base_secure_url;
2293
        $options['absolute'] = TRUE;
2294
      }
2295
      elseif ($options['https'] === FALSE) {
2296
        $options['base_url'] = $base_insecure_url;
2297
        $options['absolute'] = TRUE;
2298
      }
2299
    }
2300
    else {
2301
      $options['base_url'] = $base_url;
2302
    }
2303
  }
2304

    
2305
  // The special path '<front>' links to the default front page.
2306
  if ($path == '<front>') {
2307
    $path = '';
2308
  }
2309
  elseif (!empty($path) && !$options['alias']) {
2310
    $language = isset($options['language']) && isset($options['language']->language) ? $options['language']->language : '';
2311
    $alias = drupal_get_path_alias($original_path, $language);
2312
    if ($alias != $original_path) {
2313
      $path = $alias;
2314
    }
2315
  }
2316

    
2317
  $base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
2318
  $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
2319

    
2320
  // With Clean URLs.
2321
  if (!empty($GLOBALS['conf']['clean_url'])) {
2322
    $path = drupal_encode_path($prefix . $path);
2323
    if ($options['query']) {
2324
      return $base . $path . '?' . drupal_http_build_query($options['query']) . $options['fragment'];
2325
    }
2326
    else {
2327
      return $base . $path . $options['fragment'];
2328
    }
2329
  }
2330
  // Without Clean URLs.
2331
  else {
2332
    $path = $prefix . $path;
2333
    $query = array();
2334
    if (!empty($path)) {
2335
      $query['q'] = $path;
2336
    }
2337
    if ($options['query']) {
2338
      // We do not use array_merge() here to prevent overriding $path via query
2339
      // parameters.
2340
      $query += $options['query'];
2341
    }
2342
    $query = $query ? ('?' . drupal_http_build_query($query)) : '';
2343
    $script = isset($options['script']) ? $options['script'] : '';
2344
    return $base . $script . $query . $options['fragment'];
2345
  }
2346
}
2347

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

    
2380
/**
2381
 * Formats an attribute string for an HTTP header.
2382
 *
2383
 * @param $attributes
2384
 *   An associative array of attributes such as 'rel'.
2385
 *
2386
 * @return
2387
 *   A ; separated string ready for insertion in a HTTP header. No escaping is
2388
 *   performed for HTML entities, so this string is not safe to be printed.
2389
 *
2390
 * @see drupal_add_http_header()
2391
 */
2392
function drupal_http_header_attributes(array $attributes = array()) {
2393
  foreach ($attributes as $attribute => &$data) {
2394
    if (is_array($data)) {
2395
      $data = implode(' ', $data);
2396
    }
2397
    $data = $attribute . '="' . $data . '"';
2398
  }
2399
  return $attributes ? ' ' . implode('; ', $attributes) : '';
2400
}
2401

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

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

    
2497
  // Merge in defaults.
2498
  $options += array(
2499
    'attributes' => array(),
2500
    'html' => FALSE,
2501
  );
2502

    
2503
  // Append active class.
2504
  if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
2505
      (empty($options['language']) || $options['language']->language == $language_url->language)) {
2506
    $options['attributes']['class'][] = 'active';
2507
  }
2508

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

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

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

    
2634
/**
2635
 * Packages and sends the result of a page callback to the browser as HTML.
2636
 *
2637
 * @param $page_callback_result
2638
 *   The result of a page callback. Can be one of:
2639
 *   - NULL: to indicate no content.
2640
 *   - An integer menu status constant: to indicate an error condition.
2641
 *   - A string of HTML content.
2642
 *   - A renderable array of content.
2643
 *
2644
 * @see drupal_deliver_page()
2645
 */
2646
function drupal_deliver_html_page($page_callback_result) {
2647
  // Emit the correct charset HTTP header, but not if the page callback
2648
  // result is NULL, since that likely indicates that it printed something
2649
  // in which case, no further headers may be sent, and not if code running
2650
  // for this page request has already set the content type header.
2651
  if (isset($page_callback_result) && is_null(drupal_get_http_header('Content-Type'))) {
2652
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
2653
  }
2654

    
2655
  // Send appropriate HTTP-Header for browsers and search engines.
2656
  global $language;
2657
  drupal_add_http_header('Content-Language', $language->language);
2658

    
2659
  // By default, do not allow the site to be rendered in an iframe on another
2660
  // domain, but provide a variable to override this. If the code running for
2661
  // this page request already set the X-Frame-Options header earlier, don't
2662
  // overwrite it here.
2663
  $frame_options = variable_get('x_frame_options', 'SAMEORIGIN');
2664
  if ($frame_options && is_null(drupal_get_http_header('X-Frame-Options'))) {
2665
    drupal_add_http_header('X-Frame-Options', $frame_options);
2666
  }
2667

    
2668
  // Menu status constants are integers; page content is a string or array.
2669
  if (is_int($page_callback_result)) {
2670
    // @todo: Break these up into separate functions?
2671
    switch ($page_callback_result) {
2672
      case MENU_NOT_FOUND:
2673
        // Print a 404 page.
2674
        drupal_add_http_header('Status', '404 Not Found');
2675

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

    
2678
        // Check for and return a fast 404 page if configured.
2679
        drupal_fast_404();
2680

    
2681
        // Keep old path for reference, and to allow forms to redirect to it.
2682
        if (!isset($_GET['destination'])) {
2683
          // Make sure that the current path is not interpreted as external URL.
2684
          if (!url_is_external($_GET['q'])) {
2685
            $_GET['destination'] = $_GET['q'];
2686
          }
2687
        }
2688

    
2689
        $path = drupal_get_normal_path(variable_get('site_404', ''));
2690
        if ($path && $path != $_GET['q']) {
2691
          // Custom 404 handler. Set the active item in case there are tabs to
2692
          // display, or other dependencies on the path.
2693
          menu_set_active_item($path);
2694
          $return = menu_execute_active_handler($path, FALSE);
2695
        }
2696

    
2697
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2698
          // Standard 404 handler.
2699
          drupal_set_title(t('Page not found'));
2700
          $return = t('The requested page "@path" could not be found.', array('@path' => request_uri()));
2701
        }
2702

    
2703
        drupal_set_page_content($return);
2704
        $page = element_info('page');
2705
        print drupal_render_page($page);
2706
        break;
2707

    
2708
      case MENU_ACCESS_DENIED:
2709
        // Print a 403 page.
2710
        drupal_add_http_header('Status', '403 Forbidden');
2711
        watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
2712

    
2713
        // Keep old path for reference, and to allow forms to redirect to it.
2714
        if (!isset($_GET['destination'])) {
2715
          // Make sure that the current path is not interpreted as external URL.
2716
          if (!url_is_external($_GET['q'])) {
2717
            $_GET['destination'] = $_GET['q'];
2718
          }
2719
        }
2720

    
2721
        $path = drupal_get_normal_path(variable_get('site_403', ''));
2722
        if ($path && $path != $_GET['q']) {
2723
          // Custom 403 handler. Set the active item in case there are tabs to
2724
          // display or other dependencies on the path.
2725
          menu_set_active_item($path);
2726
          $return = menu_execute_active_handler($path, FALSE);
2727
        }
2728

    
2729
        if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
2730
          // Standard 403 handler.
2731
          drupal_set_title(t('Access denied'));
2732
          $return = t('You are not authorized to access this page.');
2733
        }
2734

    
2735
        print drupal_render_page($return);
2736
        break;
2737

    
2738
      case MENU_SITE_OFFLINE:
2739
        // Print a 503 page.
2740
        drupal_maintenance_theme();
2741
        drupal_add_http_header('Status', '503 Service unavailable');
2742
        drupal_set_title(t('Site under maintenance'));
2743
        print theme('maintenance_page', array('content' => filter_xss_admin(variable_get('maintenance_mode_message',
2744
          t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))))));
2745
        break;
2746
    }
2747
  }
2748
  elseif (isset($page_callback_result)) {
2749
    // Print anything besides a menu constant, assuming it's not NULL or
2750
    // undefined.
2751
    print drupal_render_page($page_callback_result);
2752
  }
2753

    
2754
  // Perform end-of-request tasks.
2755
  drupal_page_footer();
2756
}
2757

    
2758
/**
2759
 * Performs end-of-request tasks.
2760
 *
2761
 * This function sets the page cache if appropriate, and allows modules to
2762
 * react to the closing of the page by calling hook_exit().
2763
 */
2764
function drupal_page_footer() {
2765
  global $user;
2766

    
2767
  module_invoke_all('exit');
2768

    
2769
  // Commit the user session, if needed.
2770
  drupal_session_commit();
2771

    
2772
  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
2773
    drupal_serve_page_from_cache($cache);
2774
  }
2775
  else {
2776
    ob_flush();
2777
  }
2778

    
2779
  _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
2780
  drupal_cache_system_paths();
2781
  module_implements_write_cache();
2782
  drupal_file_scan_write_cache();
2783
  system_run_automated_cron();
2784
}
2785

    
2786
/**
2787
 * Performs end-of-request tasks.
2788
 *
2789
 * In some cases page requests need to end without calling drupal_page_footer().
2790
 * In these cases, call drupal_exit() instead. There should rarely be a reason
2791
 * to call exit instead of drupal_exit();
2792
 *
2793
 * @param $destination
2794
 *   If this function is called from drupal_goto(), then this argument
2795
 *   will be a fully-qualified URL that is the destination of the redirect.
2796
 *   This should be passed along to hook_exit() implementations.
2797
 */
2798
function drupal_exit($destination = NULL) {
2799
  if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL) {
2800
    if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
2801
      module_invoke_all('exit', $destination);
2802
    }
2803
    drupal_session_commit();
2804
  }
2805
  exit;
2806
}
2807

    
2808
/**
2809
 * Forms an associative array from a linear array.
2810
 *
2811
 * This function walks through the provided array and constructs an associative
2812
 * array out of it. The keys of the resulting array will be the values of the
2813
 * input array. The values will be the same as the keys unless a function is
2814
 * specified, in which case the output of the function is used for the values
2815
 * instead.
2816
 *
2817
 * @param $array
2818
 *   A linear array.
2819
 * @param $function
2820
 *   A name of a function to apply to all values before output.
2821
 *
2822
 * @return
2823
 *   An associative array.
2824
 */
2825
function drupal_map_assoc($array, $function = NULL) {
2826
  // array_combine() fails with empty arrays:
2827
  // http://bugs.php.net/bug.php?id=34857.
2828
  $array = !empty($array) ? array_combine($array, $array) : array();
2829
  if (is_callable($function)) {
2830
    $array = array_map($function, $array);
2831
  }
2832
  return $array;
2833
}
2834

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

    
2873
/**
2874
 * Returns the path to a system item (module, theme, etc.).
2875
 *
2876
 * @param $type
2877
 *   The type of the item (i.e. theme, theme_engine, module, profile).
2878
 * @param $name
2879
 *   The name of the item for which the path is requested.
2880
 *
2881
 * @return
2882
 *   The path to the requested item or an empty string if the item is not found.
2883
 */
2884
function drupal_get_path($type, $name) {
2885
  return dirname(drupal_get_filename($type, $name));
2886
}
2887

    
2888
/**
2889
 * Returns the base URL path (i.e., directory) of the Drupal installation.
2890
 *
2891
 * base_path() adds a "/" to the beginning and end of the returned path if the
2892
 * path is not empty. At the very least, this will return "/".
2893
 *
2894
 * Examples:
2895
 * - http://example.com returns "/" because the path is empty.
2896
 * - http://example.com/drupal/folder returns "/drupal/folder/".
2897
 */
2898
function base_path() {
2899
  return $GLOBALS['base_path'];
2900
}
2901

    
2902
/**
2903
 * Adds a LINK tag with a distinct 'rel' attribute to the page's HEAD.
2904
 *
2905
 * This function can be called as long the HTML header hasn't been sent, which
2906
 * on normal pages is up through the preprocess step of theme('html'). Adding
2907
 * a link will overwrite a prior link with the exact same 'rel' and 'href'
2908
 * attributes.
2909
 *
2910
 * @param $attributes
2911
 *   Associative array of element attributes including 'href' and 'rel'.
2912
 * @param $header
2913
 *   Optional flag to determine if a HTTP 'Link:' header should be sent.
2914
 */
2915
function drupal_add_html_head_link($attributes, $header = FALSE) {
2916
  $element = array(
2917
    '#tag' => 'link',
2918
    '#attributes' => $attributes,
2919
  );
2920
  $href = $attributes['href'];
2921

    
2922
  if ($header) {
2923
    // Also add a HTTP header "Link:".
2924
    $href = '<' . check_plain($attributes['href']) . '>;';
2925
    unset($attributes['href']);
2926
    $element['#attached']['drupal_add_http_header'][] = array('Link',  $href . drupal_http_header_attributes($attributes), TRUE);
2927
  }
2928

    
2929
  drupal_add_html_head($element, 'drupal_add_html_head_link:' . $attributes['rel'] . ':' . $href);
2930
}
2931

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

    
3052
  // If the $css variable has been reset with drupal_static_reset(), there is
3053
  // no longer any CSS being tracked, so set the counter back to 0 also.
3054
  if (count($css) === 0) {
3055
    $count = 0;
3056
  }
3057

    
3058
  // Construct the options, taking the defaults into consideration.
3059
  if (isset($options)) {
3060
    if (!is_array($options)) {
3061
      $options = array('type' => $options);
3062
    }
3063
  }
3064
  else {
3065
    $options = array();
3066
  }
3067

    
3068
  // Create an array of CSS files for each media type first, since each type needs to be served
3069
  // to the browser differently.
3070
  if (isset($data)) {
3071
    $options += array(
3072
      'type' => 'file',
3073
      'group' => CSS_DEFAULT,
3074
      'weight' => 0,
3075
      'every_page' => FALSE,
3076
      'media' => 'all',
3077
      'preprocess' => TRUE,
3078
      'data' => $data,
3079
      'browsers' => array(),
3080
    );
3081
    $options['browsers'] += array(
3082
      'IE' => TRUE,
3083
      '!IE' => TRUE,
3084
    );
3085

    
3086
    // Files with a query string cannot be preprocessed.
3087
    if ($options['type'] === 'file' && $options['preprocess'] && strpos($options['data'], '?') !== FALSE) {
3088
      $options['preprocess'] = FALSE;
3089
    }
3090

    
3091
    // Always add a tiny value to the weight, to conserve the insertion order.
3092
    $options['weight'] += $count / 1000;
3093
    $count++;
3094

    
3095
    // Add the data to the CSS array depending on the type.
3096
    switch ($options['type']) {
3097
      case 'inline':
3098
        // For inline stylesheets, we don't want to use the $data as the array
3099
        // key as $data could be a very long string of CSS.
3100
        $css[] = $options;
3101
        break;
3102
      default:
3103
        // Local and external files must keep their name as the associative key
3104
        // so the same CSS file is not be added twice.
3105
        $css[$data] = $options;
3106
    }
3107
  }
3108

    
3109
  return $css;
3110
}
3111

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

    
3146
  // Allow modules and themes to alter the CSS items.
3147
  if (!$skip_alter) {
3148
    drupal_alter('css', $css);
3149
  }
3150

    
3151
  // Sort CSS items, so that they appear in the correct order.
3152
  uasort($css, 'drupal_sort_css_js');
3153

    
3154
  // Provide the page with information about the individual CSS files used,
3155
  // information not otherwise available when CSS aggregation is enabled. The
3156
  // setting is attached later in this function, but is set here, so that CSS
3157
  // files removed below are still considered "used" and prevented from being
3158
  // added in a later AJAX request.
3159
  // Skip if no files were added to the page or jQuery.extend() will overwrite
3160
  // the Drupal.settings.ajaxPageState.css object with an empty array.
3161
  if (!empty($css)) {
3162
    // Cast the array to an object to be on the safe side even if not empty.
3163
    $setting['ajaxPageState']['css'] = (object) array_fill_keys(array_keys($css), 1);
3164
  }
3165

    
3166
  // Remove the overridden CSS files. Later CSS files override former ones.
3167
  $previous_item = array();
3168
  foreach ($css as $key => $item) {
3169
    if ($item['type'] == 'file') {
3170
      // If defined, force a unique basename for this file.
3171
      $basename = isset($item['basename']) ? $item['basename'] : drupal_basename($item['data']);
3172
      if (isset($previous_item[$basename])) {
3173
        // Remove the previous item that shared the same base name.
3174
        unset($css[$previous_item[$basename]]);
3175
      }
3176
      $previous_item[$basename] = $key;
3177
    }
3178
  }
3179

    
3180
  // Render the HTML needed to load the CSS.
3181
  $styles = array(
3182
    '#type' => 'styles',
3183
    '#items' => $css,
3184
  );
3185

    
3186
  if (!empty($setting)) {
3187
    $styles['#attached']['js'][] = array('type' => 'setting', 'data' => $setting);
3188
  }
3189

    
3190
  return drupal_render($styles);
3191
}
3192

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

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

    
3297
    // If the item can be grouped with other items, set $group_keys to an array
3298
    // of information that must be the same for all items in its group. If the
3299
    // item can't be grouped with other items, set $group_keys to FALSE. We
3300
    // put items into a group that can be aggregated together: whether they will
3301
    // be aggregated is up to the _drupal_css_aggregate() function or an
3302
    // override of that function specified in hook_css_alter(), but regardless
3303
    // of the details of that function, a group represents items that can be
3304
    // aggregated. Since a group may be rendered with a single HTML tag, all
3305
    // items in the group must share the same information that would need to be
3306
    // part of that HTML tag.
3307
    switch ($item['type']) {
3308
      case 'file':
3309
        // Group file items if their 'preprocess' flag is TRUE.
3310
        // Help ensure maximum reuse of aggregate files by only grouping
3311
        // together items that share the same 'group' value and 'every_page'
3312
        // flag. See drupal_add_css() for details about that.
3313
        $group_keys = $item['preprocess'] ? array($item['type'], $item['group'], $item['every_page'], $item['media'], $item['browsers']) : FALSE;
3314
        break;
3315
      case 'inline':
3316
        // Always group inline items.
3317
        $group_keys = array($item['type'], $item['media'], $item['browsers']);
3318
        break;
3319
      case 'external':
3320
        // Do not group external items.
3321
        $group_keys = FALSE;
3322
        break;
3323
    }
3324

    
3325
    // If the group keys don't match the most recent group we're working with,
3326
    // then a new group must be made.
3327
    if ($group_keys !== $current_group_keys) {
3328
      $i++;
3329
      // Initialize the new group with the same properties as the first item
3330
      // being placed into it. The item's 'data' and 'weight' properties are
3331
      // unique to the item and should not be carried over to the group.
3332
      $groups[$i] = $item;
3333
      unset($groups[$i]['data'], $groups[$i]['weight']);
3334
      $groups[$i]['items'] = array();
3335
      $current_group_keys = $group_keys ? $group_keys : NULL;
3336
    }
3337

    
3338
    // Add the item to the current group.
3339
    $groups[$i]['items'][] = $item;
3340
  }
3341
  return $groups;
3342
}
3343

    
3344
/**
3345
 * Default callback to aggregate CSS files and inline content.
3346
 *
3347
 * Having the browser load fewer CSS files results in much faster page loads
3348
 * than when it loads many small files. This function aggregates files within
3349
 * the same group into a single file unless the site-wide setting to do so is
3350
 * disabled (commonly the case during site development). To optimize download,
3351
 * it also compresses the aggregate files by removing comments, whitespace, and
3352
 * other unnecessary content. Additionally, this functions aggregates inline
3353
 * content together, regardless of the site-wide aggregation setting.
3354
 *
3355
 * @param $css_groups
3356
 *   An array of CSS groups as returned by drupal_group_css(). This function
3357
 *   modifies the group's 'data' property for each group that is aggregated.
3358
 *
3359
 * @see drupal_group_css()
3360
 * @see drupal_pre_render_styles()
3361
 * @see system_element_info()
3362
 */
3363
function drupal_aggregate_css(&$css_groups) {
3364
  $preprocess_css = (variable_get('preprocess_css', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
3365

    
3366
  // For each group that needs aggregation, aggregate its items.
3367
  foreach ($css_groups as $key => $group) {
3368
    switch ($group['type']) {
3369
      // If a file group can be aggregated into a single file, do so, and set
3370
      // the group's data property to the file path of the aggregate file.
3371
      case 'file':
3372
        if ($group['preprocess'] && $preprocess_css) {
3373
          $css_groups[$key]['data'] = drupal_build_css_cache($group['items']);
3374
        }
3375
        break;
3376
      // Aggregate all inline CSS content into the group's data property.
3377
      case 'inline':
3378
        $css_groups[$key]['data'] = '';
3379
        foreach ($group['items'] as $item) {
3380
          $css_groups[$key]['data'] .= drupal_load_stylesheet_content($item['data'], $item['preprocess']);
3381
        }
3382
        break;
3383
    }
3384
  }
3385
}
3386

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

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

    
3463
  // For inline CSS to validate as XHTML, all CSS containing XHTML needs to be
3464
  // wrapped in CDATA. To make that backwards compatible with HTML 4, we need to
3465
  // comment out the CDATA-tag.
3466
  $embed_prefix = "\n<!--/*--><![CDATA[/*><!--*/\n";
3467
  $embed_suffix = "\n/*]]>*/-->\n";
3468

    
3469
  // Defaults for LINK and STYLE elements.
3470
  $link_element_defaults = array(
3471
    '#type' => 'html_tag',
3472
    '#tag' => 'link',
3473
    '#attributes' => array(
3474
      'type' => 'text/css',
3475
      'rel' => 'stylesheet',
3476
    ),
3477
  );
3478
  $style_element_defaults = array(
3479
    '#type' => 'html_tag',
3480
    '#tag' => 'style',
3481
    '#attributes' => array(
3482
      'type' => 'text/css',
3483
    ),
3484
  );
3485

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

    
3612
  return $elements;
3613
}
3614

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

    
3654
  if (empty($uri) || !file_exists($uri)) {
3655
    // Build aggregate CSS file.
3656
    foreach ($css as $stylesheet) {
3657
      // Only 'file' stylesheets can be aggregated.
3658
      if ($stylesheet['type'] == 'file') {
3659
        $contents = drupal_load_stylesheet($stylesheet['data'], TRUE);
3660

    
3661
        // Build the base URL of this CSS file: start with the full URL.
3662
        $css_base_url = file_create_url($stylesheet['data']);
3663
        // Move to the parent.
3664
        $css_base_url = substr($css_base_url, 0, strrpos($css_base_url, '/'));
3665
        // Simplify to a relative URL if the stylesheet URL starts with the
3666
        // base URL of the website.
3667
        if (substr($css_base_url, 0, strlen($GLOBALS['base_root'])) == $GLOBALS['base_root']) {
3668
          $css_base_url = substr($css_base_url, strlen($GLOBALS['base_root']));
3669
        }
3670

    
3671
        _drupal_build_css_path(NULL, $css_base_url . '/');
3672
        // Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
3673
        $data .= preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);
3674
      }
3675
    }
3676

    
3677
    // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
3678
    // @import rules must proceed any other style, so we move those to the top.
3679
    $regexp = '/@import[^;]+;/i';
3680
    preg_match_all($regexp, $data, $matches);
3681
    $data = preg_replace($regexp, '', $data);
3682
    $data = implode('', $matches[0]) . $data;
3683

    
3684
    // Prefix filename to prevent blocking by firewalls which reject files
3685
    // starting with "ad*".
3686
    $filename = 'css_' . drupal_hash_base64($data) . '.css';
3687
    // Create the css/ within the files folder.
3688
    $csspath = 'public://css';
3689
    $uri = $csspath . '/' . $filename;
3690
    // Create the CSS file.
3691
    file_prepare_directory($csspath, FILE_CREATE_DIRECTORY);
3692
    if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
3693
      return FALSE;
3694
    }
3695
    // If CSS gzip compression is enabled, clean URLs are enabled (which means
3696
    // that rewrite rules are working) and the zlib extension is available then
3697
    // create a gzipped version of this file. This file is served conditionally
3698
    // to browsers that accept gzip using .htaccess rules.
3699
    if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
3700
      if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
3701
        return FALSE;
3702
      }
3703
    }
3704
    // Save the updated map.
3705
    $map[$key] = $uri;
3706
    variable_set('drupal_css_cache_files', $map);
3707
  }
3708
  return $uri;
3709
}
3710

    
3711
/**
3712
 * Prefixes all paths within a CSS file for drupal_build_css_cache().
3713
 */
3714
function _drupal_build_css_path($matches, $base = NULL) {
3715
  $_base = &drupal_static(__FUNCTION__);
3716
  // Store base path for preg_replace_callback.
3717
  if (isset($base)) {
3718
    $_base = $base;
3719
  }
3720

    
3721
  // Prefix with base and remove '../' segments where possible.
3722
  $path = $_base . $matches[1];
3723
  $last = '';
3724
  while ($path != $last) {
3725
    $last = $path;
3726
    $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
3727
  }
3728
  return 'url(' . $path . ')';
3729
}
3730

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

    
3764
  // Stylesheets are relative one to each other. Start by adding a base path
3765
  // prefix provided by the parent stylesheet (if necessary).
3766
  if ($basepath && !file_uri_scheme($file)) {
3767
    $file = $basepath . '/' . $file;
3768
  }
3769
  // Store the parent base path to restore it later.
3770
  $parent_base_path = $basepath;
3771
  // Set the current base path to process possible child imports.
3772
  $basepath = dirname($file);
3773

    
3774
  // Load the CSS stylesheet. We suppress errors because themes may specify
3775
  // stylesheets in their .info file that don't exist in the theme's path,
3776
  // but are merely there to disable certain module CSS files.
3777
  $content = '';
3778
  if ($contents = @file_get_contents($file)) {
3779
    // Return the processed stylesheet.
3780
    $content = drupal_load_stylesheet_content($contents, $_optimize);
3781
  }
3782

    
3783
  // Restore the parent base path as the file and its childen are processed.
3784
  $basepath = $parent_base_path;
3785
  return $content;
3786
}
3787

    
3788
/**
3789
 * Processes the contents of a stylesheet for aggregation.
3790
 *
3791
 * @param $contents
3792
 *   The contents of the stylesheet.
3793
 * @param $optimize
3794
 *   (optional) Boolean whether CSS contents should be minified. Defaults to
3795
 *   FALSE.
3796
 *
3797
 * @return
3798
 *   Contents of the stylesheet including the imported stylesheets.
3799
 */
3800
function drupal_load_stylesheet_content($contents, $optimize = FALSE) {
3801
  // Remove multiple charset declarations for standards compliance (and fixing Safari problems).
3802
  $contents = preg_replace('/^@charset\s+[\'"](\S*?)\b[\'"];/i', '', $contents);
3803

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

    
3844
  // Replaces @import commands with the actual stylesheet content.
3845
  // This happens recursively but omits external files.
3846
  $contents = preg_replace_callback('/@import\s*(?:url\(\s*)?[\'"]?(?![a-z]+:)(?!\/\/)([^\'"\()]+)[\'"]?\s*\)?\s*;/', '_drupal_load_stylesheet', $contents);
3847
  return $contents;
3848
}
3849

    
3850
/**
3851
 * Loads stylesheets recursively and returns contents with corrected paths.
3852
 *
3853
 * This function is used for recursive loading of stylesheets and
3854
 * returns the stylesheet content with all url() paths corrected.
3855
 */
3856
function _drupal_load_stylesheet($matches) {
3857
  $filename = $matches[1];
3858
  // Load the imported stylesheet and replace @import commands in there as well.
3859
  $file = drupal_load_stylesheet($filename, NULL, FALSE);
3860

    
3861
  // Determine the file's directory.
3862
  $directory = dirname($filename);
3863
  // If the file is in the current directory, make sure '.' doesn't appear in
3864
  // the url() path.
3865
  $directory = $directory == '.' ? '' : $directory .'/';
3866

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

    
3873
/**
3874
 * Deletes old cached CSS files.
3875
 */
3876
function drupal_clear_css_cache() {
3877
  variable_del('drupal_css_cache_files');
3878
  file_scan_directory('public://css', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
3879
}
3880

    
3881
/**
3882
 * Callback to delete files modified more than a set time ago.
3883
 */
3884
function drupal_delete_file_if_stale($uri) {
3885
  // Default stale file threshold is 30 days.
3886
  if (REQUEST_TIME - filemtime($uri) > variable_get('drupal_stale_file_threshold', 2592000)) {
3887
    file_unmanaged_delete($uri);
3888
  }
3889
}
3890

    
3891
/**
3892
 * Prepares a string for use as a CSS identifier (element, class, or ID name).
3893
 *
3894
 * http://www.w3.org/TR/CSS21/syndata.html#characters shows the syntax for valid
3895
 * CSS identifiers (including element names, classes, and IDs in selectors.)
3896
 *
3897
 * @param $identifier
3898
 *   The identifier to clean.
3899
 * @param $filter
3900
 *   An array of string replacements to use on the identifier.
3901
 *
3902
 * @return
3903
 *   The cleaned identifier.
3904
 */
3905
function drupal_clean_css_identifier($identifier, $filter = array(' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '')) {
3906
  // Use the advanced drupal_static() pattern, since this is called very often.
3907
  static $drupal_static_fast;
3908
  if (!isset($drupal_static_fast)) {
3909
    $drupal_static_fast['allow_css_double_underscores'] = &drupal_static(__FUNCTION__ . ':allow_css_double_underscores');
3910
  }
3911
  $allow_css_double_underscores = &$drupal_static_fast['allow_css_double_underscores'];
3912
  if (!isset($allow_css_double_underscores)) {
3913
    $allow_css_double_underscores = variable_get('allow_css_double_underscores', FALSE);
3914
  }
3915

    
3916
  // Preserve BEM-style double-underscores depending on custom setting.
3917
  if ($allow_css_double_underscores) {
3918
    $filter['__'] = '__';
3919
  }
3920

    
3921
  // By default, we filter using Drupal's coding standards.
3922
  $identifier = strtr($identifier, $filter);
3923

    
3924
  // Valid characters in a CSS identifier are:
3925
  // - the hyphen (U+002D)
3926
  // - a-z (U+0030 - U+0039)
3927
  // - A-Z (U+0041 - U+005A)
3928
  // - the underscore (U+005F)
3929
  // - 0-9 (U+0061 - U+007A)
3930
  // - ISO 10646 characters U+00A1 and higher
3931
  // We strip out any character not in the above list.
3932
  $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);
3933

    
3934
  return $identifier;
3935
}
3936

    
3937
/**
3938
 * Prepares a string for use as a valid class name.
3939
 *
3940
 * Do not pass one string containing multiple classes as they will be
3941
 * incorrectly concatenated with dashes, i.e. "one two" will become "one-two".
3942
 *
3943
 * @param $class
3944
 *   The class name to clean.
3945
 *
3946
 * @return
3947
 *   The cleaned class name.
3948
 */
3949
function drupal_html_class($class) {
3950
  // The output of this function will never change, so this uses a normal
3951
  // static instead of drupal_static().
3952
  static $classes = array();
3953

    
3954
  if (!isset($classes[$class])) {
3955
    $classes[$class] = drupal_clean_css_identifier(drupal_strtolower($class));
3956
  }
3957
  return $classes[$class];
3958
}
3959

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

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

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

    
4056
  // Removing multiple consecutive hyphens.
4057
  $id = preg_replace('/\-+/', '-', $id);
4058
  // Ensure IDs are unique by appending a counter after the first occurrence.
4059
  // The counter needs to be appended with a delimiter that does not exist in
4060
  // the base ID. Requiring a unique delimiter helps ensure that we really do
4061
  // return unique IDs and also helps us re-create the $seen_ids array during
4062
  // Ajax requests.
4063
  if (isset($seen_ids[$id])) {
4064
    $id = $id . '--' . ++$seen_ids[$id];
4065
  }
4066
  else {
4067
    $seen_ids[$id] = 1;
4068
  }
4069

    
4070
  return $id;
4071
}
4072

    
4073
/**
4074
 * Provides a standard HTML class name that identifies a page region.
4075
 *
4076
 * It is recommended that template preprocess functions apply this class to any
4077
 * page region that is output by the theme (Drupal core already handles this in
4078
 * the standard template preprocess implementation). Standardizing the class
4079
 * names in this way allows modules to implement certain features, such as
4080
 * drag-and-drop or dynamic Ajax loading, in a theme-independent way.
4081
 *
4082
 * @param $region
4083
 *   The name of the page region (for example, 'page_top' or 'content').
4084
 *
4085
 * @return
4086
 *   An HTML class that identifies the region (for example, 'region-page-top'
4087
 *   or 'region-content').
4088
 *
4089
 * @see template_preprocess_region()
4090
 */
4091
function drupal_region_class($region) {
4092
  return drupal_html_class("region-$region");
4093
}
4094

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

    
4254
  // If the $javascript variable has been reset with drupal_static_reset(),
4255
  // jQuery and related files will have been removed from the list, so set the
4256
  // variable back to FALSE to indicate they have not yet been added.
4257
  if (empty($javascript)) {
4258
    $jquery_added = FALSE;
4259
  }
4260

    
4261
  // Construct the options, taking the defaults into consideration.
4262
  if (isset($options)) {
4263
    if (!is_array($options)) {
4264
      $options = array('type' => $options);
4265
    }
4266
  }
4267
  else {
4268
    $options = array();
4269
  }
4270
  if (isset($options['type']) && $options['type'] == 'setting') {
4271
    $options += array('requires_jquery' => FALSE);
4272
  }
4273
  $options += drupal_js_defaults($data);
4274

    
4275
  // Preprocess can only be set if caching is enabled.
4276
  $options['preprocess'] = $options['cache'] ? $options['preprocess'] : FALSE;
4277

    
4278
  // Tweak the weight so that files of the same weight are included in the
4279
  // order of the calls to drupal_add_js().
4280
  $options['weight'] += count($javascript) / 1000;
4281

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

    
4325
    switch ($options['type']) {
4326
      case 'setting':
4327
        // All JavaScript settings are placed in the header of the page with
4328
        // the library weight so that inline scripts appear afterwards.
4329
        $javascript['settings']['data'][] = $data;
4330
        break;
4331

    
4332
      case 'inline':
4333
        $javascript[] = $options;
4334
        break;
4335

    
4336
      default: // 'file' and 'external'
4337
        // Local and external files must keep their name as the associative key
4338
        // so the same JavaScript file is not added twice.
4339
        $javascript[$options['data']] = $options;
4340
    }
4341
  }
4342
  return $javascript;
4343
}
4344

    
4345
/**
4346
 * Constructs an array of the defaults that are used for JavaScript items.
4347
 *
4348
 * @param $data
4349
 *   (optional) The default data parameter for the JavaScript item array.
4350
 *
4351
 * @see drupal_get_js()
4352
 * @see drupal_add_js()
4353
 */
4354
function drupal_js_defaults($data = NULL) {
4355
  return array(
4356
    'type' => 'file',
4357
    'group' => JS_DEFAULT,
4358
    'every_page' => FALSE,
4359
    'weight' => 0,
4360
    'requires_jquery' => TRUE,
4361
    'scope' => 'header',
4362
    'cache' => TRUE,
4363
    'defer' => FALSE,
4364
    'preprocess' => TRUE,
4365
    'version' => NULL,
4366
    'data' => $data,
4367
  );
4368
}
4369

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

    
4408
  // If no JavaScript items have been added, or if the only JavaScript items
4409
  // that have been added are JavaScript settings (which don't do anything
4410
  // without any JavaScript code to use them), then no JavaScript code should
4411
  // be added to the page.
4412
  if (empty($javascript) || (isset($javascript['settings']) && count($javascript) == 1)) {
4413
    return '';
4414
  }
4415

    
4416
  // Allow modules to alter the JavaScript.
4417
  if (!$skip_alter) {
4418
    drupal_alter('js', $javascript);
4419
  }
4420

    
4421
  // Filter out elements of the given scope.
4422
  $items = array();
4423
  foreach ($javascript as $key => $item) {
4424
    if ($item['scope'] == $scope) {
4425
      $items[$key] = $item;
4426
    }
4427
  }
4428

    
4429
  $output = '';
4430
  // The index counter is used to keep aggregated and non-aggregated files in
4431
  // order by weight.
4432
  $index = 1;
4433
  $processed = array();
4434
  $files = array();
4435
  $preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
4436

    
4437
  // A dummy query-string is added to filenames, to gain control over
4438
  // browser-caching. The string changes on every update or full cache
4439
  // flush, forcing browsers to load a new copy of the files, as the
4440
  // URL changed. Files that should not be cached (see drupal_add_js())
4441
  // get REQUEST_TIME as query-string instead, to enforce reload on every
4442
  // page request.
4443
  $default_query_string = variable_get('css_js_query_string', '0');
4444

    
4445
  // For inline JavaScript to validate as XHTML, all JavaScript containing
4446
  // XHTML needs to be wrapped in CDATA. To make that backwards compatible
4447
  // with HTML 4, we need to comment out the CDATA-tag.
4448
  $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
4449
  $embed_suffix = "\n//--><!]]>\n";
4450

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

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

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

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

    
4474
  // Loop through the JavaScript to construct the rendered output.
4475
  $element = array(
4476
    '#tag' => 'script',
4477
    '#value' => '',
4478
    '#attributes' => array(
4479
      'type' => 'text/javascript',
4480
    ),
4481
  );
4482
  foreach ($items as $item) {
4483
    $query_string =  empty($item['version']) ? $default_query_string : $js_version_string . $item['version'];
4484

    
4485
    switch ($item['type']) {
4486
      case 'setting':
4487
        $js_element = $element;
4488
        $js_element['#value_prefix'] = $embed_prefix;
4489
        $js_element['#value'] = 'jQuery.extend(Drupal.settings, ' . drupal_json_encode(drupal_array_merge_deep_array($item['data'])) . ");";
4490
        $js_element['#value_suffix'] = $embed_suffix;
4491
        $output .= theme('html_tag', array('element' => $js_element));
4492
        break;
4493

    
4494
      case 'inline':
4495
        $js_element = $element;
4496
        if ($item['defer']) {
4497
          $js_element['#attributes']['defer'] = 'defer';
4498
        }
4499
        $js_element['#value_prefix'] = $embed_prefix;
4500
        $js_element['#value'] = $item['data'];
4501
        $js_element['#value_suffix'] = $embed_suffix;
4502
        $processed[$index++] = theme('html_tag', array('element' => $js_element));
4503
        break;
4504

    
4505
      case 'file':
4506
        $js_element = $element;
4507
        if (!$item['preprocess'] || !$preprocess_js) {
4508
          if ($item['defer']) {
4509
            $js_element['#attributes']['defer'] = 'defer';
4510
          }
4511
          $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
4512
          $js_element['#attributes']['src'] = file_create_url($item['data']) . $query_string_separator . ($item['cache'] ? $query_string : REQUEST_TIME);
4513
          $processed[$index++] = theme('html_tag', array('element' => $js_element));
4514
        }
4515
        else {
4516
          // By increasing the index for each aggregated file, we maintain
4517
          // the relative ordering of JS by weight. We also set the key such
4518
          // that groups are split by items sharing the same 'group' value and
4519
          // 'every_page' flag. While this potentially results in more aggregate
4520
          // files, it helps make each one more reusable across a site visit,
4521
          // leading to better front-end performance of a website as a whole.
4522
          // See drupal_add_js() for details.
4523
          $key = 'aggregate_' . $item['group'] . '_' . $item['every_page'] . '_' . $index;
4524
          $processed[$key] = '';
4525
          $files[$key][$item['data']] = $item;
4526
        }
4527
        break;
4528

    
4529
      case 'external':
4530
        $js_element = $element;
4531
        // Preprocessing for external JavaScript files is ignored.
4532
        if ($item['defer']) {
4533
          $js_element['#attributes']['defer'] = 'defer';
4534
        }
4535
        $js_element['#attributes']['src'] = $item['data'];
4536
        $processed[$index++] = theme('html_tag', array('element' => $js_element));
4537
        break;
4538
    }
4539
  }
4540

    
4541
  // Aggregate any remaining JS files that haven't already been output.
4542
  if ($preprocess_js && count($files) > 0) {
4543
    foreach ($files as $key => $file_set) {
4544
      $uri = drupal_build_js_cache($file_set);
4545
      // Only include the file if was written successfully. Errors are logged
4546
      // using watchdog.
4547
      if ($uri) {
4548
        $preprocess_file = file_create_url($uri);
4549
        $js_element = $element;
4550
        $js_element['#attributes']['src'] = $preprocess_file;
4551
        $processed[$key] = theme('html_tag', array('element' => $js_element));
4552
      }
4553
    }
4554
  }
4555

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

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

    
4625
  // Add the libraries first.
4626
  $success = TRUE;
4627
  foreach ($elements['#attached']['library'] as $library) {
4628
    if (drupal_add_library($library[0], $library[1], $every_page) === FALSE) {
4629
      $success = FALSE;
4630
      // Exit if the dependency is missing.
4631
      if ($dependency_check) {
4632
        return $success;
4633
      }
4634
    }
4635
  }
4636
  unset($elements['#attached']['library']);
4637

    
4638
  // Add both the JavaScript and the CSS.
4639
  // The parameters for drupal_add_js() and drupal_add_css() require special
4640
  // handling.
4641
  foreach (array('js', 'css') as $type) {
4642
    foreach ($elements['#attached'][$type] as $data => $options) {
4643
      // If the value is not an array, it's a filename and passed as first
4644
      // (and only) argument.
4645
      if (!is_array($options)) {
4646
        $data = $options;
4647
        $options = NULL;
4648
      }
4649
      // In some cases, the first parameter ($data) is an array. Arrays can't be
4650
      // passed as keys in PHP, so we have to get $data from the value array.
4651
      if (is_numeric($data)) {
4652
        $data = $options['data'];
4653
        unset($options['data']);
4654
      }
4655
      // Apply the default group if it isn't explicitly given.
4656
      if (!isset($options['group'])) {
4657
        $options['group'] = $group;
4658
      }
4659
      // Set the every_page flag if one was passed.
4660
      if (isset($every_page)) {
4661
        $options['every_page'] = $every_page;
4662
      }
4663
      call_user_func('drupal_add_' . $type, $data, $options);
4664
    }
4665
    unset($elements['#attached'][$type]);
4666
  }
4667

    
4668
  // Add additional types of attachments specified in the render() structure.
4669
  // Libraries, JavaScript and CSS have been added already, as they require
4670
  // special handling.
4671
  foreach ($elements['#attached'] as $callback => $options) {
4672
    if (function_exists($callback)) {
4673
      foreach ($elements['#attached'][$callback] as $args) {
4674
        call_user_func_array($callback, $args);
4675
      }
4676
    }
4677
  }
4678

    
4679
  return $success;
4680
}
4681

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

    
4813
/**
4814
 * Adds multiple JavaScript or CSS files at the same time.
4815
 *
4816
 * A library defines a set of JavaScript and/or CSS files, optionally using
4817
 * settings, and optionally requiring another library. For example, a library
4818
 * can be a jQuery plugin, a JavaScript framework, or a CSS framework. This
4819
 * function allows modules to load a library defined/shipped by itself or a
4820
 * depending module, without having to add all files of the library separately.
4821
 * Each library is only loaded once.
4822
 *
4823
 * @param $module
4824
 *   The name of the module that registered the library.
4825
 * @param $name
4826
 *   The name of the library to add.
4827
 * @param $every_page
4828
 *   Set to TRUE if this library is added to every page on the site. Only items
4829
 *   with the every_page flag set to TRUE can participate in aggregation.
4830
 *
4831
 * @return
4832
 *   TRUE if the library was successfully added; FALSE if the library or one of
4833
 *   its dependencies could not be added.
4834
 *
4835
 * @see drupal_get_library()
4836
 * @see hook_library()
4837
 * @see hook_library_alter()
4838
 */
4839
function drupal_add_library($module, $name, $every_page = NULL) {
4840
  $added = &drupal_static(__FUNCTION__, array());
4841

    
4842
  // Only process the library if it exists and it was not added already.
4843
  if (!isset($added[$module][$name])) {
4844
    if ($library = drupal_get_library($module, $name)) {
4845
      // Add all components within the library.
4846
      $elements['#attached'] = array(
4847
        'library' => $library['dependencies'],
4848
        'js' => $library['js'],
4849
        'css' => $library['css'],
4850
      );
4851
      $added[$module][$name] = drupal_process_attached($elements, JS_LIBRARY, TRUE, $every_page);
4852
    }
4853
    else {
4854
      // Requested library does not exist.
4855
      $added[$module][$name] = FALSE;
4856
    }
4857
  }
4858

    
4859
  return $added[$module][$name];
4860
}
4861

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

    
4896
  if (!isset($libraries[$module])) {
4897
    // Retrieve all libraries associated with the module.
4898
    $module_libraries = module_invoke($module, 'library');
4899
    if (empty($module_libraries)) {
4900
      $module_libraries = array();
4901
    }
4902
    // Allow modules to alter the module's registered libraries.
4903
    drupal_alter('library', $module_libraries, $module);
4904

    
4905
    foreach ($module_libraries as $key => $data) {
4906
      if (is_array($data)) {
4907
        // Add default elements to allow for easier processing.
4908
        $module_libraries[$key] += array('dependencies' => array(), 'js' => array(), 'css' => array());
4909
        foreach ($module_libraries[$key]['js'] as $file => $options) {
4910
          $module_libraries[$key]['js'][$file]['version'] = $module_libraries[$key]['version'];
4911
        }
4912
      }
4913
    }
4914
    $libraries[$module] = $module_libraries;
4915
  }
4916
  if (isset($name)) {
4917
    if (!isset($libraries[$module][$name])) {
4918
      $libraries[$module][$name] = FALSE;
4919
    }
4920
    return $libraries[$module][$name];
4921
  }
4922
  return $libraries[$module];
4923
}
4924

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

    
5043
  // If a subgroup or source isn't set, assume it is the same as the group.
5044
  $target = isset($subgroup) ? $subgroup : $group;
5045
  $source = isset($source) ? $source : $target;
5046
  $settings['tableDrag'][$table_id][$group][] = array(
5047
    'target' => $target,
5048
    'source' => $source,
5049
    'relationship' => $relationship,
5050
    'action' => $action,
5051
    'hidden' => $hidden,
5052
    'limit' => $limit,
5053
  );
5054
  drupal_add_js($settings, 'setting');
5055
}
5056

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

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

    
5130
/**
5131
 * Deletes old cached JavaScript files and variables.
5132
 */
5133
function drupal_clear_js_cache() {
5134
  variable_del('javascript_parsed');
5135
  variable_del('drupal_js_cache_files');
5136
  file_scan_directory('public://js', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
5137
}
5138

    
5139
/**
5140
 * Converts a PHP variable into its JavaScript equivalent.
5141
 *
5142
 * We use HTML-safe strings, with several characters escaped.
5143
 *
5144
 * @see drupal_json_decode()
5145
 * @see drupal_json_encode_helper()
5146
 * @ingroup php_wrappers
5147
 */
5148
function drupal_json_encode($var) {
5149
  // The PHP version cannot change within a request.
5150
  static $php530;
5151

    
5152
  if (!isset($php530)) {
5153
    $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
5154
  }
5155

    
5156
  if ($php530) {
5157
    // Encode <, >, ', &, and " using the json_encode() options parameter.
5158
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
5159
  }
5160

    
5161
  // json_encode() escapes <, >, ', &, and " using its options parameter, but
5162
  // does not support this parameter prior to PHP 5.3.0.  Use a helper instead.
5163
  include_once DRUPAL_ROOT . '/includes/json-encode.inc';
5164
  return drupal_json_encode_helper($var);
5165
}
5166

    
5167
/**
5168
 * Converts an HTML-safe JSON string into its PHP equivalent.
5169
 *
5170
 * @see drupal_json_encode()
5171
 * @ingroup php_wrappers
5172
 */
5173
function drupal_json_decode($var) {
5174
  return json_decode($var, TRUE);
5175
}
5176

    
5177
/**
5178
 * Returns data in JSON format.
5179
 *
5180
 * This function should be used for JavaScript callback functions returning
5181
 * data in JSON format. It sets the header for JavaScript output.
5182
 *
5183
 * @param $var
5184
 *   (optional) If set, the variable will be converted to JSON and output.
5185
 */
5186
function drupal_json_output($var = NULL) {
5187
  // We are returning JSON, so tell the browser.
5188
  drupal_add_http_header('Content-Type', 'application/json');
5189

    
5190
  if (isset($var)) {
5191
    echo drupal_json_encode($var);
5192
  }
5193
}
5194

    
5195
/**
5196
 * Ensures the private key variable used to generate tokens is set.
5197
 *
5198
 * @return
5199
 *   The private key.
5200
 */
5201
function drupal_get_private_key() {
5202
  if (!($key = variable_get('drupal_private_key', 0))) {
5203
    $key = drupal_random_key();
5204
    variable_set('drupal_private_key', $key);
5205
  }
5206
  return $key;
5207
}
5208

    
5209
/**
5210
 * Generates a token based on $value, the user session, and the private key.
5211
 *
5212
 * @param $value
5213
 *   An additional value to base the token on.
5214
 *
5215
 * The generated token is based on the session ID of the current user. Normally,
5216
 * anonymous users do not have a session, so the generated token will be
5217
 * different on every page request. To generate a token for users without a
5218
 * session, manually start a session prior to calling this function.
5219
 *
5220
 * @return string
5221
 *   A 43-character URL-safe token for validation, based on the user session ID,
5222
 *   the hash salt provided from drupal_get_hash_salt(), and the
5223
 *   'drupal_private_key' configuration variable.
5224
 *
5225
 * @see drupal_get_hash_salt()
5226
 */
5227
function drupal_get_token($value = '') {
5228
  return drupal_hmac_base64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());
5229
}
5230

    
5231
/**
5232
 * Validates a token based on $value, the user session, and the private key.
5233
 *
5234
 * @param $token
5235
 *   The token to be validated.
5236
 * @param $value
5237
 *   An additional value to base the token on.
5238
 * @param $skip_anonymous
5239
 *   Set to true to skip token validation for anonymous users.
5240
 *
5241
 * @return
5242
 *   True for a valid token, false for an invalid token. When $skip_anonymous
5243
 *   is true, the return value will always be true for anonymous users.
5244
 */
5245
function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
5246
  global $user;
5247
  return (($skip_anonymous && $user->uid == 0) || ($token === drupal_get_token($value)));
5248
}
5249

    
5250
function _drupal_bootstrap_full() {
5251
  static $called = FALSE;
5252

    
5253
  if ($called) {
5254
    return;
5255
  }
5256
  $called = TRUE;
5257
  require_once DRUPAL_ROOT . '/' . variable_get('path_inc', 'includes/path.inc');
5258
  require_once DRUPAL_ROOT . '/includes/theme.inc';
5259
  require_once DRUPAL_ROOT . '/includes/pager.inc';
5260
  require_once DRUPAL_ROOT . '/' . variable_get('menu_inc', 'includes/menu.inc');
5261
  require_once DRUPAL_ROOT . '/includes/tablesort.inc';
5262
  require_once DRUPAL_ROOT . '/includes/file.inc';
5263
  require_once DRUPAL_ROOT . '/includes/unicode.inc';
5264
  require_once DRUPAL_ROOT . '/includes/image.inc';
5265
  require_once DRUPAL_ROOT . '/includes/form.inc';
5266
  require_once DRUPAL_ROOT . '/includes/mail.inc';
5267
  require_once DRUPAL_ROOT . '/includes/actions.inc';
5268
  require_once DRUPAL_ROOT . '/includes/ajax.inc';
5269
  require_once DRUPAL_ROOT . '/includes/token.inc';
5270
  require_once DRUPAL_ROOT . '/includes/errors.inc';
5271

    
5272
  // Detect string handling method
5273
  unicode_check();
5274
  // Undo magic quotes
5275
  fix_gpc_magic();
5276
  // Load all enabled modules
5277
  module_load_all();
5278
  // Reset drupal_alter() and module_implements() static caches as these
5279
  // include implementations for vital modules only when called early on
5280
  // in the bootstrap.
5281
  drupal_static_reset('drupal_alter');
5282
  drupal_static_reset('module_implements');
5283
  // Make sure all stream wrappers are registered.
5284
  file_get_stream_wrappers();
5285
  // Ensure mt_rand is reseeded, to prevent random values from one page load
5286
  // being exploited to predict random values in subsequent page loads.
5287
  $seed = unpack("L", drupal_random_bytes(4));
5288
  mt_srand($seed[1]);
5289

    
5290
  $test_info = &$GLOBALS['drupal_test_info'];
5291
  if (!empty($test_info['in_child_site'])) {
5292
    // Running inside the simpletest child site, log fatal errors to test
5293
    // specific file directory.
5294
    ini_set('log_errors', 1);
5295
    ini_set('error_log', 'public://error.log');
5296
  }
5297

    
5298
  // Initialize $_GET['q'] prior to invoking hook_init().
5299
  drupal_path_initialize();
5300

    
5301
  // Let all modules take action before the menu system handles the request.
5302
  // We do not want this while running update.php.
5303
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
5304
    // Prior to invoking hook_init(), initialize the theme (potentially a custom
5305
    // one for this page), so that:
5306
    // - Modules with hook_init() implementations that call theme() or
5307
    //   theme_get_registry() don't initialize the incorrect theme.
5308
    // - The theme can have hook_*_alter() implementations affect page building
5309
    //   (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
5310
    //   ahead of when rendering starts.
5311
    menu_set_custom_theme();
5312
    drupal_theme_initialize();
5313
    module_invoke_all('init');
5314
  }
5315
}
5316

    
5317
/**
5318
 * Stores the current page in the cache.
5319
 *
5320
 * If page_compression is enabled, a gzipped version of the page is stored in
5321
 * the cache to avoid compressing the output on each request. The cache entry
5322
 * is unzipped in the relatively rare event that the page is requested by a
5323
 * client without gzip support.
5324
 *
5325
 * Page compression requires the PHP zlib extension
5326
 * (http://php.net/manual/ref.zlib.php).
5327
 *
5328
 * @see drupal_page_header()
5329
 */
5330
function drupal_page_set_cache() {
5331
  global $base_root;
5332

    
5333
  if (drupal_page_is_cacheable()) {
5334

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

    
5338
    $cache = (object) array(
5339
      'cid' => $base_root . request_uri(),
5340
      'data' => array(
5341
        'path' => $_GET['q'],
5342
        'body' => ob_get_clean(),
5343
        'title' => drupal_get_title(),
5344
        'headers' => array(),
5345
        // We need to store whether page was compressed or not,
5346
        // because by the time it is read, the configuration might change.
5347
        'page_compressed' => $page_compressed,
5348
      ),
5349
      'expire' => CACHE_TEMPORARY,
5350
      'created' => REQUEST_TIME,
5351
    );
5352

    
5353
    // Restore preferred header names based on the lower-case names returned
5354
    // by drupal_get_http_header().
5355
    $header_names = _drupal_set_preferred_header_name();
5356
    foreach (drupal_get_http_header() as $name_lower => $value) {
5357
      $cache->data['headers'][$header_names[$name_lower]] = $value;
5358
      if ($name_lower == 'expires') {
5359
        // Use the actual timestamp from an Expires header if available.
5360
        $cache->expire = strtotime($value);
5361
      }
5362
    }
5363

    
5364
    if ($cache->data['body']) {
5365
      if ($page_compressed) {
5366
        $cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
5367
      }
5368
      cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire);
5369
    }
5370
    return $cache;
5371
  }
5372
}
5373

    
5374
/**
5375
 * Executes a cron run when called.
5376
 *
5377
 * Do not call this function from a test. Use $this->cronRun() instead.
5378
 *
5379
 * @return bool
5380
 *   TRUE if cron ran successfully and FALSE if cron is already running.
5381
 */
5382
function drupal_cron_run() {
5383
  // Allow execution to continue even if the request gets canceled.
5384
  @ignore_user_abort(TRUE);
5385

    
5386
  // Prevent session information from being saved while cron is running.
5387
  $original_session_saving = drupal_save_session();
5388
  drupal_save_session(FALSE);
5389

    
5390
  // Force the current user to anonymous to ensure consistent permissions on
5391
  // cron runs.
5392
  $original_user = $GLOBALS['user'];
5393
  $GLOBALS['user'] = drupal_anonymous_user();
5394

    
5395
  // Try to allocate enough time to run all the hook_cron implementations.
5396
  drupal_set_time_limit(240);
5397

    
5398
  $return = FALSE;
5399
  // Grab the defined cron queues.
5400
  $queues = module_invoke_all('cron_queue_info');
5401
  drupal_alter('cron_queue_info', $queues);
5402

    
5403
  // Try to acquire cron lock.
5404
  if (!lock_acquire('cron', 240.0)) {
5405
    // Cron is still running normally.
5406
    watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
5407
  }
5408
  else {
5409
    // Make sure every queue exists. There is no harm in trying to recreate an
5410
    // existing queue.
5411
    foreach ($queues as $queue_name => $info) {
5412
      DrupalQueue::get($queue_name)->createQueue();
5413
    }
5414

    
5415
    // Iterate through the modules calling their cron handlers (if any):
5416
    foreach (module_implements('cron') as $module) {
5417
      // Do not let an exception thrown by one module disturb another.
5418
      try {
5419
        module_invoke($module, 'cron');
5420
      }
5421
      catch (Exception $e) {
5422
        watchdog_exception('cron', $e);
5423
      }
5424
    }
5425

    
5426
    // Record cron time.
5427
    variable_set('cron_last', REQUEST_TIME);
5428
    watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
5429

    
5430
    // Release cron lock.
5431
    lock_release('cron');
5432

    
5433
    // Return TRUE so other functions can check if it did run successfully
5434
    $return = TRUE;
5435
  }
5436

    
5437
  foreach ($queues as $queue_name => $info) {
5438
    if (!empty($info['skip on cron'])) {
5439
      // Do not run if queue wants to skip.
5440
      continue;
5441
    }
5442
    $callback = $info['worker callback'];
5443
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
5444
    $queue = DrupalQueue::get($queue_name);
5445
    while (time() < $end && ($item = $queue->claimItem())) {
5446
      try {
5447
        call_user_func($callback, $item->data);
5448
        $queue->deleteItem($item);
5449
      }
5450
      catch (Exception $e) {
5451
        // In case of exception log it and leave the item in the queue
5452
        // to be processed again later.
5453
        watchdog_exception('cron', $e);
5454
      }
5455
    }
5456
  }
5457
  // Restore the user.
5458
  $GLOBALS['user'] = $original_user;
5459
  drupal_save_session($original_session_saving);
5460

    
5461
  return $return;
5462
}
5463

    
5464
/**
5465
 * DEPRECATED: Shutdown function: Performs cron cleanup.
5466
 *
5467
 * This function is deprecated because the 'cron_semaphore' variable it
5468
 * references no longer exists. It is therefore no longer used as a shutdown
5469
 * function by Drupal core.
5470
 *
5471
 * @deprecated
5472
 */
5473
function drupal_cron_cleanup() {
5474
  // See if the semaphore is still locked.
5475
  if (variable_get('cron_semaphore', FALSE)) {
5476
    watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);
5477

    
5478
    // Release cron semaphore.
5479
    variable_del('cron_semaphore');
5480
  }
5481
}
5482

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

    
5534
  $searchdir = array($directory);
5535
  $files = array();
5536

    
5537
  // The 'profiles' directory contains pristine collections of modules and
5538
  // themes as organized by a distribution. It is pristine in the same way
5539
  // that /modules is pristine for core; users should avoid changing anything
5540
  // there in favor of sites/all or sites/<domain> directories.
5541
  $profiles = array();
5542
  $profile = drupal_get_profile();
5543
  // For SimpleTest to be able to test modules packaged together with a
5544
  // distribution we need to include the profile of the parent site (in which
5545
  // test runs are triggered).
5546
  if (drupal_valid_test_ua()) {
5547
    $testing_profile = variable_get('simpletest_parent_profile', FALSE);
5548
    if ($testing_profile && $testing_profile != $profile) {
5549
      $profiles[] = $testing_profile;
5550
    }
5551
  }
5552
  // In case both profile directories contain the same extension, the actual
5553
  // profile always has precedence.
5554
  $profiles[] = $profile;
5555
  foreach ($profiles as $profile) {
5556
    if (file_exists("profiles/$profile/$directory")) {
5557
      $searchdir[] = "profiles/$profile/$directory";
5558
    }
5559
  }
5560

    
5561
  // Always search sites/all/* as well as the global directories.
5562
  $searchdir[] = 'sites/all/' . $directory;
5563

    
5564
  if (file_exists("$config/$directory")) {
5565
    $searchdir[] = "$config/$directory";
5566
  }
5567

    
5568
  // Get current list of items.
5569
  if (!function_exists('file_scan_directory')) {
5570
    require_once DRUPAL_ROOT . '/includes/file.inc';
5571
  }
5572
  foreach ($searchdir as $dir) {
5573
    $files_to_add = file_scan_directory($dir, $mask, array('key' => $key, 'min_depth' => $min_depth));
5574

    
5575
    // Duplicate files found in later search directories take precedence over
5576
    // earlier ones, so we want them to overwrite keys in our resulting
5577
    // $files array.
5578
    // The exception to this is if the later file is from a module or theme not
5579
    // compatible with Drupal core. This may occur during upgrades of Drupal
5580
    // core when new modules exist in core while older contrib modules with the
5581
    // same name exist in a directory such as sites/all/modules/.
5582
    foreach (array_intersect_key($files_to_add, $files) as $file_key => $file) {
5583
      // If it has no info file, then we just behave liberally and accept the
5584
      // new resource on the list for merging.
5585
      if (file_exists($info_file = dirname($file->uri) . '/' . $file->name . '.info')) {
5586
        // Get the .info file for the module or theme this file belongs to.
5587
        $info = drupal_parse_info_file($info_file);
5588

    
5589
        // If the module or theme is incompatible with Drupal core, remove it
5590
        // from the array for the current search directory, so it is not
5591
        // overwritten when merged with the $files array.
5592
        if (isset($info['core']) && $info['core'] != DRUPAL_CORE_COMPATIBILITY) {
5593
          unset($files_to_add[$file_key]);
5594
        }
5595
      }
5596
    }
5597
    $files = array_merge($files, $files_to_add);
5598
  }
5599

    
5600
  return $files;
5601
}
5602

    
5603
/**
5604
 * Sets the main page content value for later use.
5605
 *
5606
 * Given the nature of the Drupal page handling, this will be called once with
5607
 * a string or array. We store that and return it later as the block is being
5608
 * displayed.
5609
 *
5610
 * @param $content
5611
 *   A string or renderable array representing the body of the page.
5612
 *
5613
 * @return
5614
 *   If called without $content, a renderable array representing the body of
5615
 *   the page.
5616
 */
5617
function drupal_set_page_content($content = NULL) {
5618
  $content_block = &drupal_static(__FUNCTION__, NULL);
5619
  $main_content_display = &drupal_static('system_main_content_added', FALSE);
5620

    
5621
  if (!empty($content)) {
5622
    $content_block = (is_array($content) ? $content : array('main' => array('#markup' => $content)));
5623
  }
5624
  else {
5625
    // Indicate that the main content has been requested. We assume that
5626
    // the module requesting the content will be adding it to the page.
5627
    // A module can indicate that it does not handle the content by setting
5628
    // the static variable back to FALSE after calling this function.
5629
    $main_content_display = TRUE;
5630
    return $content_block;
5631
  }
5632
}
5633

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

    
5670
  // If rendering in all browsers, no need for conditional comments.
5671
  if ($browsers['IE'] === TRUE && $browsers['!IE']) {
5672
    return $elements;
5673
  }
5674

    
5675
  // Determine the conditional comment expression for Internet Explorer to
5676
  // evaluate.
5677
  if ($browsers['IE'] === TRUE) {
5678
    $expression = 'IE';
5679
  }
5680
  elseif ($browsers['IE'] === FALSE) {
5681
    $expression = '!IE';
5682
  }
5683
  else {
5684
    $expression = $browsers['IE'];
5685
  }
5686

    
5687
  // Wrap the element's potentially existing #prefix and #suffix properties with
5688
  // conditional comment markup. The conditional comment expression is evaluated
5689
  // by Internet Explorer only. To control the rendering by other browsers,
5690
  // either the "downlevel-hidden" or "downlevel-revealed" technique must be
5691
  // used. See http://en.wikipedia.org/wiki/Conditional_comment for details.
5692
  $elements += array(
5693
    '#prefix' => '',
5694
    '#suffix' => '',
5695
  );
5696
  if (!$browsers['!IE']) {
5697
    // "downlevel-hidden".
5698
    $elements['#prefix'] = "\n<!--[if $expression]>\n" . $elements['#prefix'];
5699
    $elements['#suffix'] .= "<![endif]-->\n";
5700
  }
5701
  else {
5702
    // "downlevel-revealed".
5703
    $elements['#prefix'] = "\n<!--[if $expression]><!-->\n" . $elements['#prefix'];
5704
    $elements['#suffix'] .= "<!--<![endif]-->\n";
5705
  }
5706

    
5707
  return $elements;
5708
}
5709

    
5710
/**
5711
 * #pre_render callback to render a link into #markup.
5712
 *
5713
 * Doing so during pre_render gives modules a chance to alter the link parts.
5714
 *
5715
 * @param $elements
5716
 *   A structured array whose keys form the arguments to l():
5717
 *   - #title: The link text to pass as argument to l().
5718
 *   - #href: The URL path component to pass as argument to l().
5719
 *   - #options: (optional) An array of options to pass to l().
5720
 *
5721
 * @return
5722
 *   The passed-in elements containing a rendered link in '#markup'.
5723
 */
5724
function drupal_pre_render_link($element) {
5725
  // By default, link options to pass to l() are normally set in #options.
5726
  $element += array('#options' => array());
5727
  // However, within the scope of renderable elements, #attributes is a valid
5728
  // way to specify attributes, too. Take them into account, but do not override
5729
  // attributes from #options.
5730
  if (isset($element['#attributes'])) {
5731
    $element['#options'] += array('attributes' => array());
5732
    $element['#options']['attributes'] += $element['#attributes'];
5733
  }
5734

    
5735
  // This #pre_render callback can be invoked from inside or outside of a Form
5736
  // API context, and depending on that, a HTML ID may be already set in
5737
  // different locations. #options should have precedence over Form API's #id.
5738
  // #attributes have been taken over into #options above already.
5739
  if (isset($element['#options']['attributes']['id'])) {
5740
    $element['#id'] = $element['#options']['attributes']['id'];
5741
  }
5742
  elseif (isset($element['#id'])) {
5743
    $element['#options']['attributes']['id'] = $element['#id'];
5744
  }
5745

    
5746
  // Conditionally invoke ajax_pre_render_element(), if #ajax is set.
5747
  if (isset($element['#ajax']) && !isset($element['#ajax_processed'])) {
5748
    // If no HTML ID was found above, automatically create one.
5749
    if (!isset($element['#id'])) {
5750
      $element['#id'] = $element['#options']['attributes']['id'] = drupal_html_id('ajax-link');
5751
    }
5752
    // If #ajax['path] was not specified, use the href as Ajax request URL.
5753
    if (!isset($element['#ajax']['path'])) {
5754
      $element['#ajax']['path'] = $element['#href'];
5755
      $element['#ajax']['options'] = $element['#options'];
5756
    }
5757
    $element = ajax_pre_render_element($element);
5758
  }
5759

    
5760
  $element['#markup'] = l($element['#title'], $element['#href'], $element['#options']);
5761
  return $element;
5762
}
5763

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

    
5855
/**
5856
 * #pre_render callback to append contents in #markup to #children.
5857
 *
5858
 * This needs to be a #pre_render callback, because eventually assigned
5859
 * #theme_wrappers will expect the element's rendered content in #children.
5860
 * Note that if also a #theme is defined for the element, then the result of
5861
 * the theme callback will override #children.
5862
 *
5863
 * @param $elements
5864
 *   A structured array using the #markup key.
5865
 *
5866
 * @return
5867
 *   The passed-in elements, but #markup appended to #children.
5868
 *
5869
 * @see drupal_render()
5870
 */
5871
function drupal_pre_render_markup($elements) {
5872
  $elements['#children'] = $elements['#markup'];
5873
  return $elements;
5874
}
5875

    
5876
/**
5877
 * Renders the page, including all theming.
5878
 *
5879
 * @param $page
5880
 *   A string or array representing the content of a page. The array consists of
5881
 *   the following keys:
5882
 *   - #type: Value is always 'page'. This pushes the theming through
5883
 *     page.tpl.php (required).
5884
 *   - #show_messages: Suppress drupal_get_message() items. Used by Batch
5885
 *     API (optional).
5886
 *
5887
 * @see hook_page_alter()
5888
 * @see element_info()
5889
 */
5890
function drupal_render_page($page) {
5891
  $main_content_display = &drupal_static('system_main_content_added', FALSE);
5892

    
5893
  // Allow menu callbacks to return strings or arbitrary arrays to render.
5894
  // If the array returned is not of #type page directly, we need to fill
5895
  // in the page with defaults.
5896
  if (is_string($page) || (is_array($page) && (!isset($page['#type']) || ($page['#type'] != 'page')))) {
5897
    drupal_set_page_content($page);
5898
    $page = element_info('page');
5899
  }
5900

    
5901
  // Modules can add elements to $page as needed in hook_page_build().
5902
  foreach (module_implements('page_build') as $module) {
5903
    $function = $module . '_page_build';
5904
    $function($page);
5905
  }
5906
  // Modules alter the $page as needed. Blocks are populated into regions like
5907
  // 'sidebar_first', 'footer', etc.
5908
  drupal_alter('page', $page);
5909

    
5910
  // If no module has taken care of the main content, add it to the page now.
5911
  // This allows the site to still be usable even if no modules that
5912
  // control page regions (for example, the Block module) are enabled.
5913
  if (!$main_content_display) {
5914
    $page['content']['system_main'] = drupal_set_page_content();
5915
  }
5916

    
5917
  return drupal_render($page);
5918
}
5919

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

    
6003
  // Do not print elements twice.
6004
  if (!empty($elements['#printed'])) {
6005
    return '';
6006
  }
6007

    
6008
  // Try to fetch the element's markup from cache and return.
6009
  if (isset($elements['#cache'])) {
6010
    $cached_output = drupal_render_cache_get($elements);
6011
    if ($cached_output !== FALSE) {
6012
      return $cached_output;
6013
    }
6014
  }
6015

    
6016
  // If #markup is set, ensure #type is set. This allows to specify just #markup
6017
  // on an element without setting #type.
6018
  if (isset($elements['#markup']) && !isset($elements['#type'])) {
6019
    $elements['#type'] = 'markup';
6020
  }
6021

    
6022
  // If the default values for this element have not been loaded yet, populate
6023
  // them.
6024
  if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
6025
    $elements += element_info($elements['#type']);
6026
  }
6027

    
6028
  // Make any final changes to the element before it is rendered. This means
6029
  // that the $element or the children can be altered or corrected before the
6030
  // element is rendered into the final text.
6031
  if (isset($elements['#pre_render'])) {
6032
    foreach ($elements['#pre_render'] as $function) {
6033
      if (function_exists($function)) {
6034
        $elements = $function($elements);
6035
      }
6036
    }
6037
  }
6038

    
6039
  // Allow #pre_render to abort rendering.
6040
  if (!empty($elements['#printed'])) {
6041
    return '';
6042
  }
6043

    
6044
  // Get the children of the element, sorted by weight.
6045
  $children = element_children($elements, TRUE);
6046

    
6047
  // Initialize this element's #children, unless a #pre_render callback already
6048
  // preset #children.
6049
  if (!isset($elements['#children'])) {
6050
    $elements['#children'] = '';
6051
  }
6052
  // Call the element's #theme function if it is set. Then any children of the
6053
  // element have to be rendered there.
6054
  if (isset($elements['#theme'])) {
6055
    $elements['#children'] = theme($elements['#theme'], $elements);
6056
  }
6057
  // If #theme was not set and the element has children, render them now.
6058
  // This is the same process as drupal_render_children() but is inlined
6059
  // for speed.
6060
  if ($elements['#children'] == '') {
6061
    foreach ($children as $key) {
6062
      $elements['#children'] .= drupal_render($elements[$key]);
6063
    }
6064
  }
6065

    
6066
  // Let the theme functions in #theme_wrappers add markup around the rendered
6067
  // children.
6068
  if (isset($elements['#theme_wrappers'])) {
6069
    foreach ($elements['#theme_wrappers'] as $theme_wrapper) {
6070
      $elements['#children'] = theme($theme_wrapper, $elements);
6071
    }
6072
  }
6073

    
6074
  // Filter the outputted content and make any last changes before the
6075
  // content is sent to the browser. The changes are made on $content
6076
  // which allows the output'ed text to be filtered.
6077
  if (isset($elements['#post_render'])) {
6078
    foreach ($elements['#post_render'] as $function) {
6079
      if (function_exists($function)) {
6080
        $elements['#children'] = $function($elements['#children'], $elements);
6081
      }
6082
    }
6083
  }
6084

    
6085
  // Add any JavaScript state information associated with the element.
6086
  if (!empty($elements['#states'])) {
6087
    drupal_process_states($elements);
6088
  }
6089

    
6090
  // Add additional libraries, CSS, JavaScript an other custom
6091
  // attached data associated with this element.
6092
  if (!empty($elements['#attached'])) {
6093
    drupal_process_attached($elements);
6094
  }
6095

    
6096
  $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
6097
  $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
6098
  $output = $prefix . $elements['#children'] . $suffix;
6099

    
6100
  // Cache the processed element if #cache is set.
6101
  if (isset($elements['#cache'])) {
6102
    drupal_render_cache_set($output, $elements);
6103
  }
6104

    
6105
  $elements['#printed'] = TRUE;
6106
  return $output;
6107
}
6108

    
6109
/**
6110
 * Renders children of an element and concatenates them.
6111
 *
6112
 * @param array $element
6113
 *   The structured array whose children shall be rendered.
6114
 * @param array $children_keys
6115
 *   (optional) If the keys of the element's children are already known, they
6116
 *   can be passed in to save another run of element_children().
6117
 *
6118
 * @return string
6119
 *   The rendered HTML of all children of the element.
6120

    
6121
 * @see drupal_render()
6122
 */
6123
function drupal_render_children(&$element, $children_keys = NULL) {
6124
  if ($children_keys === NULL) {
6125
    $children_keys = element_children($element);
6126
  }
6127
  $output = '';
6128
  foreach ($children_keys as $key) {
6129
    if (!empty($element[$key])) {
6130
      $output .= drupal_render($element[$key]);
6131
    }
6132
  }
6133
  return $output;
6134
}
6135

    
6136
/**
6137
 * Renders an element.
6138
 *
6139
 * This function renders an element using drupal_render(). The top level
6140
 * element is shown with show() before rendering, so it will always be rendered
6141
 * even if hide() had been previously used on it.
6142
 *
6143
 * @param $element
6144
 *   The element to be rendered.
6145
 *
6146
 * @return
6147
 *   The rendered element.
6148
 *
6149
 * @see drupal_render()
6150
 * @see show()
6151
 * @see hide()
6152
 */
6153
function render(&$element) {
6154
  if (is_array($element)) {
6155
    show($element);
6156
    return drupal_render($element);
6157
  }
6158
  else {
6159
    // Safe-guard for inappropriate use of render() on flat variables: return
6160
    // the variable as-is.
6161
    return $element;
6162
  }
6163
}
6164

    
6165
/**
6166
 * Hides an element from later rendering.
6167
 *
6168
 * The first time render() or drupal_render() is called on an element tree,
6169
 * as each element in the tree is rendered, it is marked with a #printed flag
6170
 * and the rendered children of the element are cached. Subsequent calls to
6171
 * render() or drupal_render() will not traverse the child tree of this element
6172
 * again: they will just use the cached children. So if you want to hide an
6173
 * element, be sure to call hide() on the element before its parent tree is
6174
 * rendered for the first time, as it will have no effect on subsequent
6175
 * renderings of the parent tree.
6176
 *
6177
 * @param $element
6178
 *   The element to be hidden.
6179
 *
6180
 * @return
6181
 *   The element.
6182
 *
6183
 * @see render()
6184
 * @see show()
6185
 */
6186
function hide(&$element) {
6187
  $element['#printed'] = TRUE;
6188
  return $element;
6189
}
6190

    
6191
/**
6192
 * Shows a hidden element for later rendering.
6193
 *
6194
 * You can also use render($element), which shows the element while rendering
6195
 * it.
6196
 *
6197
 * The first time render() or drupal_render() is called on an element tree,
6198
 * as each element in the tree is rendered, it is marked with a #printed flag
6199
 * and the rendered children of the element are cached. Subsequent calls to
6200
 * render() or drupal_render() will not traverse the child tree of this element
6201
 * again: they will just use the cached children. So if you want to show an
6202
 * element, be sure to call show() on the element before its parent tree is
6203
 * rendered for the first time, as it will have no effect on subsequent
6204
 * renderings of the parent tree.
6205
 *
6206
 * @param $element
6207
 *   The element to be shown.
6208
 *
6209
 * @return
6210
 *   The element.
6211
 *
6212
 * @see render()
6213
 * @see hide()
6214
 */
6215
function show(&$element) {
6216
  $element['#printed'] = FALSE;
6217
  return $element;
6218
}
6219

    
6220
/**
6221
 * Gets the rendered output of a renderable element from the cache.
6222
 *
6223
 * @param $elements
6224
 *   A renderable array.
6225
 *
6226
 * @return
6227
 *   A markup string containing the rendered content of the element, or FALSE
6228
 *   if no cached copy of the element is available.
6229
 *
6230
 * @see drupal_render()
6231
 * @see drupal_render_cache_set()
6232
 */
6233
function drupal_render_cache_get($elements) {
6234
  if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
6235
    return FALSE;
6236
  }
6237
  $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
6238

    
6239
  if (!empty($cid) && $cache = cache_get($cid, $bin)) {
6240
    // Add additional libraries, JavaScript, CSS and other data attached
6241
    // to this element.
6242
    if (isset($cache->data['#attached'])) {
6243
      drupal_process_attached($cache->data);
6244
    }
6245
    // Return the rendered output.
6246
    return $cache->data['#markup'];
6247
  }
6248
  return FALSE;
6249
}
6250

    
6251
/**
6252
 * Caches the rendered output of a renderable element.
6253
 *
6254
 * This is called by drupal_render() if the #cache property is set on an
6255
 * element.
6256
 *
6257
 * @param $markup
6258
 *   The rendered output string of $elements.
6259
 * @param $elements
6260
 *   A renderable array.
6261
 *
6262
 * @see drupal_render_cache_get()
6263
 */
6264
function drupal_render_cache_set(&$markup, $elements) {
6265
  // Create the cache ID for the element.
6266
  if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
6267
    return FALSE;
6268
  }
6269

    
6270
  // Cache implementations are allowed to modify the markup, to support
6271
  // replacing markup with edge-side include commands. The supporting cache
6272
  // backend will store the markup in some other key (like
6273
  // $data['#real-value']) and return an include command instead. When the
6274
  // ESI command is executed by the content accelerator, the real value can
6275
  // be retrieved and used.
6276
  $data['#markup'] = &$markup;
6277
  // Persist attached data associated with this element.
6278
  $attached = drupal_render_collect_attached($elements, TRUE);
6279
  if ($attached) {
6280
    $data['#attached'] = $attached;
6281
  }
6282
  $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
6283
  $expire = isset($elements['#cache']['expire']) ? $elements['#cache']['expire'] : CACHE_PERMANENT;
6284
  cache_set($cid, $data, $bin, $expire);
6285
}
6286

    
6287
/**
6288
 * Collects #attached for an element and its children into a single array.
6289
 *
6290
 * When caching elements, it is necessary to collect all libraries, JavaScript
6291
 * and CSS into a single array, from both the element itself and all child
6292
 * elements. This allows drupal_render() to add these back to the page when the
6293
 * element is returned from cache.
6294
 *
6295
 * @param $elements
6296
 *   The element to collect #attached from.
6297
 * @param $return
6298
 *   Whether to return the attached elements and reset the internal static.
6299
 *
6300
 * @return
6301
 *   The #attached array for this element and its descendants.
6302
 */
6303
function drupal_render_collect_attached($elements, $return = FALSE) {
6304
  $attached = &drupal_static(__FUNCTION__, array());
6305

    
6306
  // Collect all #attached for this element.
6307
  if (isset($elements['#attached'])) {
6308
    foreach ($elements['#attached'] as $key => $value) {
6309
      if (!isset($attached[$key])) {
6310
        $attached[$key] = array();
6311
      }
6312
      $attached[$key] = array_merge($attached[$key], $value);
6313
    }
6314
  }
6315
  if ($children = element_children($elements)) {
6316
    foreach ($children as $child) {
6317
      drupal_render_collect_attached($elements[$child]);
6318
    }
6319
  }
6320

    
6321
  // If this was the first call to the function, return all attached elements
6322
  // and reset the static cache.
6323
  if ($return) {
6324
    $return = $attached;
6325
    $attached = array();
6326
    return $return;
6327
  }
6328
}
6329

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

    
6371
/**
6372
 * Returns cache ID parts for building a cache ID.
6373
 *
6374
 * @param $granularity
6375
 *   One or more cache granularity constants. For example, to cache separately
6376
 *   for each user, use DRUPAL_CACHE_PER_USER. To cache separately for each
6377
 *   page and role, use the expression:
6378
 *   @code
6379
 *   DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE
6380
 *   @endcode
6381
 *
6382
 * @return
6383
 *   An array of cache ID parts, always containing the active theme. If the
6384
 *   locale module is enabled it also contains the active language. If
6385
 *   $granularity was passed in, more parts are added.
6386
 */
6387
function drupal_render_cid_parts($granularity = NULL) {
6388
  global $theme, $base_root, $user;
6389

    
6390
  $cid_parts[] = $theme;
6391
  // If Locale is enabled but we have only one language we do not need it as cid
6392
  // part.
6393
  if (drupal_multilingual()) {
6394
    foreach (language_types_configurable() as $language_type) {
6395
      $cid_parts[] = $GLOBALS[$language_type]->language;
6396
    }
6397
  }
6398

    
6399
  if (!empty($granularity)) {
6400
    $cache_per_role = $granularity & DRUPAL_CACHE_PER_ROLE;
6401
    $cache_per_user = $granularity & DRUPAL_CACHE_PER_USER;
6402
    // User 1 has special permissions outside of the role system, so when
6403
    // caching per role is requested, it should cache per user instead.
6404
    if ($user->uid == 1 && $cache_per_role) {
6405
      $cache_per_user = TRUE;
6406
      $cache_per_role = FALSE;
6407
    }
6408
    // 'PER_ROLE' and 'PER_USER' are mutually exclusive. 'PER_USER' can be a
6409
    // resource drag for sites with many users, so when a module is being
6410
    // equivocal, we favor the less expensive 'PER_ROLE' pattern.
6411
    if ($cache_per_role) {
6412
      $cid_parts[] = 'r.' . implode(',', array_keys($user->roles));
6413
    }
6414
    elseif ($cache_per_user) {
6415
      $cid_parts[] = "u.$user->uid";
6416
    }
6417

    
6418
    if ($granularity & DRUPAL_CACHE_PER_PAGE) {
6419
      $cid_parts[] = $base_root . request_uri();
6420
    }
6421
  }
6422

    
6423
  return $cid_parts;
6424
}
6425

    
6426
/**
6427
 * Creates the cache ID for a renderable element.
6428
 *
6429
 * This creates the cache ID string, either by returning the #cache['cid']
6430
 * property if present or by building the cache ID out of the #cache['keys']
6431
 * and, optionally, the #cache['granularity'] properties.
6432
 *
6433
 * @param $elements
6434
 *   A renderable array.
6435
 *
6436
 * @return
6437
 *   The cache ID string, or FALSE if the element may not be cached.
6438
 */
6439
function drupal_render_cid_create($elements) {
6440
  if (isset($elements['#cache']['cid'])) {
6441
    return $elements['#cache']['cid'];
6442
  }
6443
  elseif (isset($elements['#cache']['keys'])) {
6444
    $granularity = isset($elements['#cache']['granularity']) ? $elements['#cache']['granularity'] : NULL;
6445
    // Merge in additional cache ID parts based provided by drupal_render_cid_parts().
6446
    $cid_parts = array_merge($elements['#cache']['keys'], drupal_render_cid_parts($granularity));
6447
    return implode(':', $cid_parts);
6448
  }
6449
  return FALSE;
6450
}
6451

    
6452
/**
6453
 * Function used by uasort to sort structured arrays by weight.
6454
 */
6455
function element_sort($a, $b) {
6456
  $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
6457
  $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
6458
  if ($a_weight == $b_weight) {
6459
    return 0;
6460
  }
6461
  return ($a_weight < $b_weight) ? -1 : 1;
6462
}
6463

    
6464
/**
6465
 * Array sorting callback; sorts elements by title.
6466
 */
6467
function element_sort_by_title($a, $b) {
6468
  $a_title = (is_array($a) && isset($a['#title'])) ? $a['#title'] : '';
6469
  $b_title = (is_array($b) && isset($b['#title'])) ? $b['#title'] : '';
6470
  return strnatcasecmp($a_title, $b_title);
6471
}
6472

    
6473
/**
6474
 * Retrieves the default properties for the defined element type.
6475
 *
6476
 * @param $type
6477
 *   An element type as defined by hook_element_info().
6478
 */
6479
function element_info($type) {
6480
  // Use the advanced drupal_static() pattern, since this is called very often.
6481
  static $drupal_static_fast;
6482
  if (!isset($drupal_static_fast)) {
6483
    $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__);
6484
  }
6485
  $cache = &$drupal_static_fast['cache'];
6486

    
6487
  if (!isset($cache)) {
6488
    $cache = module_invoke_all('element_info');
6489
    foreach ($cache as $element_type => $info) {
6490
      $cache[$element_type]['#type'] = $element_type;
6491
    }
6492
    // Allow modules to alter the element type defaults.
6493
    drupal_alter('element_info', $cache);
6494
  }
6495

    
6496
  return isset($cache[$type]) ? $cache[$type] : array();
6497
}
6498

    
6499
/**
6500
 * Retrieves a single property for the defined element type.
6501
 *
6502
 * @param $type
6503
 *   An element type as defined by hook_element_info().
6504
 * @param $property_name
6505
 *   The property within the element type that should be returned.
6506
 * @param $default
6507
 *   (Optional) The value to return if the element type does not specify a
6508
 *   value for the property. Defaults to NULL.
6509
 */
6510
function element_info_property($type, $property_name, $default = NULL) {
6511
  return (($info = element_info($type)) && array_key_exists($property_name, $info)) ? $info[$property_name] : $default;
6512
}
6513

    
6514
/**
6515
 * Sorts a structured array by the 'weight' element.
6516
 *
6517
 * Note that the sorting is by the 'weight' array element, not by the render
6518
 * element property '#weight'.
6519
 *
6520
 * Callback for uasort() used in various functions.
6521
 *
6522
 * @param $a
6523
 *   First item for comparison. The compared items should be associative arrays
6524
 *   that optionally include a 'weight' element. For items without a 'weight'
6525
 *   element, a default value of 0 will be used.
6526
 * @param $b
6527
 *   Second item for comparison.
6528
 */
6529
function drupal_sort_weight($a, $b) {
6530
  $a_weight = (is_array($a) && isset($a['weight'])) ? $a['weight'] : 0;
6531
  $b_weight = (is_array($b) && isset($b['weight'])) ? $b['weight'] : 0;
6532
  if ($a_weight == $b_weight) {
6533
    return 0;
6534
  }
6535
  return ($a_weight < $b_weight) ? -1 : 1;
6536
}
6537

    
6538
/**
6539
 * Array sorting callback; sorts elements by 'title' key.
6540
 */
6541
function drupal_sort_title($a, $b) {
6542
  if (!isset($b['title'])) {
6543
    return -1;
6544
  }
6545
  if (!isset($a['title'])) {
6546
    return 1;
6547
  }
6548
  return strcasecmp($a['title'], $b['title']);
6549
}
6550

    
6551
/**
6552
 * Checks if the key is a property.
6553
 */
6554
function element_property($key) {
6555
  return $key[0] == '#';
6556
}
6557

    
6558
/**
6559
 * Gets properties of a structured array element (keys beginning with '#').
6560
 */
6561
function element_properties($element) {
6562
  return array_filter(array_keys((array) $element), 'element_property');
6563
}
6564

    
6565
/**
6566
 * Checks if the key is a child.
6567
 */
6568
function element_child($key) {
6569
  return !isset($key[0]) || $key[0] != '#';
6570
}
6571

    
6572
/**
6573
 * Identifies the children of an element array, optionally sorted by weight.
6574
 *
6575
 * The children of a element array are those key/value pairs whose key does
6576
 * not start with a '#'. See drupal_render() for details.
6577
 *
6578
 * @param $elements
6579
 *   The element array whose children are to be identified.
6580
 * @param $sort
6581
 *   Boolean to indicate whether the children should be sorted by weight.
6582
 *
6583
 * @return
6584
 *   The array keys of the element's children.
6585
 */
6586
function element_children(&$elements, $sort = FALSE) {
6587
  // Do not attempt to sort elements which have already been sorted.
6588
  $sort = isset($elements['#sorted']) ? !$elements['#sorted'] : $sort;
6589

    
6590
  // Filter out properties from the element, leaving only children.
6591
  $children = array();
6592
  $sortable = FALSE;
6593
  foreach ($elements as $key => $value) {
6594
    if ($key === '' || $key[0] !== '#') {
6595
      $children[$key] = $value;
6596
      if (is_array($value) && isset($value['#weight'])) {
6597
        $sortable = TRUE;
6598
      }
6599
    }
6600
  }
6601
  // Sort the children if necessary.
6602
  if ($sort && $sortable) {
6603
    uasort($children, 'element_sort');
6604
    // Put the sorted children back into $elements in the correct order, to
6605
    // preserve sorting if the same element is passed through
6606
    // element_children() twice.
6607
    foreach ($children as $key => $child) {
6608
      unset($elements[$key]);
6609
      $elements[$key] = $child;
6610
    }
6611
    $elements['#sorted'] = TRUE;
6612
  }
6613

    
6614
  return array_keys($children);
6615
}
6616

    
6617
/**
6618
 * Returns the visible children of an element.
6619
 *
6620
 * @param $elements
6621
 *   The parent element.
6622
 *
6623
 * @return
6624
 *   The array keys of the element's visible children.
6625
 */
6626
function element_get_visible_children(array $elements) {
6627
  $visible_children = array();
6628

    
6629
  foreach (element_children($elements) as $key) {
6630
    $child = $elements[$key];
6631

    
6632
    // Skip un-accessible children.
6633
    if (isset($child['#access']) && !$child['#access']) {
6634
      continue;
6635
    }
6636

    
6637
    // Skip value and hidden elements, since they are not rendered.
6638
    if (isset($child['#type']) && in_array($child['#type'], array('value', 'hidden'))) {
6639
      continue;
6640
    }
6641

    
6642
    $visible_children[$key] = $child;
6643
  }
6644

    
6645
  return array_keys($visible_children);
6646
}
6647

    
6648
/**
6649
 * Sets HTML attributes based on element properties.
6650
 *
6651
 * @param $element
6652
 *   The renderable element to process.
6653
 * @param $map
6654
 *   An associative array whose keys are element property names and whose values
6655
 *   are the HTML attribute names to set for corresponding the property; e.g.,
6656
 *   array('#propertyname' => 'attributename'). If both names are identical
6657
 *   except for the leading '#', then an attribute name value is sufficient and
6658
 *   no property name needs to be specified.
6659
 */
6660
function element_set_attributes(array &$element, array $map) {
6661
  foreach ($map as $property => $attribute) {
6662
    // If the key is numeric, the attribute name needs to be taken over.
6663
    if (is_int($property)) {
6664
      $property = '#' . $attribute;
6665
    }
6666
    // Do not overwrite already existing attributes.
6667
    if (isset($element[$property]) && !isset($element['#attributes'][$attribute])) {
6668
      $element['#attributes'][$attribute] = $element[$property];
6669
    }
6670
  }
6671
}
6672

    
6673
/**
6674
 * Recursively computes the difference of arrays with additional index check.
6675
 *
6676
 * This is a version of array_diff_assoc() that supports multidimensional
6677
 * arrays.
6678
 *
6679
 * @param array $array1
6680
 *   The array to compare from.
6681
 * @param array $array2
6682
 *   The array to compare to.
6683
 *
6684
 * @return array
6685
 *   Returns an array containing all the values from array1 that are not present
6686
 *   in array2.
6687
 */
6688
function drupal_array_diff_assoc_recursive($array1, $array2) {
6689
  $difference = array();
6690

    
6691
  foreach ($array1 as $key => $value) {
6692
    if (is_array($value)) {
6693
      if (!array_key_exists($key, $array2) || !is_array($array2[$key])) {
6694
        $difference[$key] = $value;
6695
      }
6696
      else {
6697
        $new_diff = drupal_array_diff_assoc_recursive($value, $array2[$key]);
6698
        if (!empty($new_diff)) {
6699
          $difference[$key] = $new_diff;
6700
        }
6701
      }
6702
    }
6703
    elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
6704
      $difference[$key] = $value;
6705
    }
6706
  }
6707

    
6708
  return $difference;
6709
}
6710

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

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

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

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

    
7097
/**
7098
 * @addtogroup schemaapi
7099
 * @{
7100
 */
7101

    
7102
/**
7103
 * Creates all tables defined in a module's hook_schema().
7104
 *
7105
 * Note: This function does not pass the module's schema through
7106
 * hook_schema_alter(). The module's tables will be created exactly as the
7107
 * module defines them.
7108
 *
7109
 * @param $module
7110
 *   The module for which the tables will be created.
7111
 */
7112
function drupal_install_schema($module) {
7113
  $schema = drupal_get_schema_unprocessed($module);
7114
  _drupal_schema_initialize($schema, $module, FALSE);
7115

    
7116
  foreach ($schema as $name => $table) {
7117
    db_create_table($name, $table);
7118
  }
7119
}
7120

    
7121
/**
7122
 * Removes all tables defined in a module's hook_schema().
7123
 *
7124
 * Note: This function does not pass the module's schema through
7125
 * hook_schema_alter(). The module's tables will be created exactly as the
7126
 * module defines them.
7127
 *
7128
 * @param $module
7129
 *   The module for which the tables will be removed.
7130
 *
7131
 * @return
7132
 *   An array of arrays with the following key/value pairs:
7133
 *    - success: a boolean indicating whether the query succeeded.
7134
 *    - query: the SQL query(s) executed, passed through check_plain().
7135
 */
7136
function drupal_uninstall_schema($module) {
7137
  $schema = drupal_get_schema_unprocessed($module);
7138
  _drupal_schema_initialize($schema, $module, FALSE);
7139

    
7140
  foreach ($schema as $table) {
7141
    if (db_table_exists($table['name'])) {
7142
      db_drop_table($table['name']);
7143
    }
7144
  }
7145
}
7146

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

    
7177
  if (isset($table) && isset($schema[$table])) {
7178
    return $schema[$table];
7179
  }
7180
  elseif (!empty($schema)) {
7181
    return $schema;
7182
  }
7183
  return array();
7184
}
7185

    
7186
/**
7187
 * Fills in required default values for table definitions from hook_schema().
7188
 *
7189
 * @param $schema
7190
 *   The schema definition array as it was returned by the module's
7191
 *   hook_schema().
7192
 * @param $module
7193
 *   The module for which hook_schema() was invoked.
7194
 * @param $remove_descriptions
7195
 *   (optional) Whether to additionally remove 'description' keys of all tables
7196
 *   and fields to improve performance of serialize() and unserialize().
7197
 *   Defaults to TRUE.
7198
 */
7199
function _drupal_schema_initialize(&$schema, $module, $remove_descriptions = TRUE) {
7200
  // Set the name and module key for all tables.
7201
  foreach ($schema as $name => &$table) {
7202
    if (empty($table['module'])) {
7203
      $table['module'] = $module;
7204
    }
7205
    if (!isset($table['name'])) {
7206
      $table['name'] = $name;
7207
    }
7208
    if ($remove_descriptions) {
7209
      unset($table['description']);
7210
      foreach ($table['fields'] as &$field) {
7211
        unset($field['description']);
7212
      }
7213
    }
7214
  }
7215
}
7216

    
7217
/**
7218
 * Retrieves the type for every field in a table schema.
7219
 *
7220
 * @param $table
7221
 *   The name of the table from which to retrieve type information.
7222
 *
7223
 * @return
7224
 *   An array of types, keyed by field name.
7225
 */
7226
function drupal_schema_field_types($table) {
7227
  $table_schema = drupal_get_schema($table);
7228
  $field_types = array();
7229
  foreach ($table_schema['fields'] as $field_name => $field_info) {
7230
    $field_types[$field_name] = isset($field_info['type']) ? $field_info['type'] : NULL;
7231
  }
7232
  return $field_types;
7233
}
7234

    
7235
/**
7236
 * Retrieves a list of fields from a table schema.
7237
 *
7238
 * The returned list is suitable for use in an SQL query.
7239
 *
7240
 * @param $table
7241
 *   The name of the table from which to retrieve fields.
7242
 * @param
7243
 *   An optional prefix to to all fields.
7244
 *
7245
 * @return An array of fields.
7246
 */
7247
function drupal_schema_fields_sql($table, $prefix = NULL) {
7248
  $schema = drupal_get_schema($table);
7249
  $fields = array_keys($schema['fields']);
7250
  if ($prefix) {
7251
    $columns = array();
7252
    foreach ($fields as $field) {
7253
      $columns[] = "$prefix.$field";
7254
    }
7255
    return $columns;
7256
  }
7257
  else {
7258
    return $fields;
7259
  }
7260
}
7261

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

    
7295
  $schema = drupal_get_schema($table);
7296
  if (empty($schema)) {
7297
    return FALSE;
7298
  }
7299

    
7300
  $object = (object) $record;
7301
  $fields = array();
7302

    
7303
  // Go through the schema to determine fields to write.
7304
  foreach ($schema['fields'] as $field => $info) {
7305
    if ($info['type'] == 'serial') {
7306
      // Skip serial types if we are updating.
7307
      if (!empty($primary_keys)) {
7308
        continue;
7309
      }
7310
      // Track serial field so we can helpfully populate them after the query.
7311
      // NOTE: Each table should come with one serial field only.
7312
      $serial = $field;
7313
    }
7314

    
7315
    // Skip field if it is in $primary_keys as it is unnecessary to update a
7316
    // field to the value it is already set to.
7317
    if (in_array($field, $primary_keys)) {
7318
      continue;
7319
    }
7320

    
7321
    if (!property_exists($object, $field)) {
7322
      // Skip fields that are not provided, default values are already known
7323
      // by the database.
7324
      continue;
7325
    }
7326

    
7327
    // Build array of fields to update or insert.
7328
    if (empty($info['serialize'])) {
7329
      $fields[$field] = $object->$field;
7330
    }
7331
    else {
7332
      $fields[$field] = serialize($object->$field);
7333
    }
7334

    
7335
    // Type cast to proper datatype, except when the value is NULL and the
7336
    // column allows this.
7337
    //
7338
    // MySQL PDO silently casts e.g. FALSE and '' to 0 when inserting the value
7339
    // into an integer column, but PostgreSQL PDO does not. Also type cast NULL
7340
    // when the column does not allow this.
7341
    if (isset($object->$field) || !empty($info['not null'])) {
7342
      if ($info['type'] == 'int' || $info['type'] == 'serial') {
7343
        $fields[$field] = (int) $fields[$field];
7344
      }
7345
      elseif ($info['type'] == 'float') {
7346
        $fields[$field] = (float) $fields[$field];
7347
      }
7348
      else {
7349
        $fields[$field] = (string) $fields[$field];
7350
      }
7351
    }
7352
  }
7353

    
7354
  if (empty($fields)) {
7355
    return;
7356
  }
7357

    
7358
  // Build the SQL.
7359
  if (empty($primary_keys)) {
7360
    // We are doing an insert.
7361
    $options = array('return' => Database::RETURN_INSERT_ID);
7362
    if (isset($serial) && isset($fields[$serial])) {
7363
      // If the serial column has been explicitly set with an ID, then we don't
7364
      // require the database to return the last insert id.
7365
      if ($fields[$serial]) {
7366
        $options['return'] = Database::RETURN_AFFECTED;
7367
      }
7368
      // If a serial column does exist with no value (i.e. 0) then remove it as
7369
      // the database will insert the correct value for us.
7370
      else {
7371
        unset($fields[$serial]);
7372
      }
7373
    }
7374
    $query = db_insert($table, $options)->fields($fields);
7375
    $return = SAVED_NEW;
7376
  }
7377
  else {
7378
    $query = db_update($table)->fields($fields);
7379
    foreach ($primary_keys as $key) {
7380
      $query->condition($key, $object->$key);
7381
    }
7382
    $return = SAVED_UPDATED;
7383
  }
7384

    
7385
  // Execute the SQL.
7386
  if ($query_return = $query->execute()) {
7387
    if (isset($serial)) {
7388
      // If the database was not told to return the last insert id, it will be
7389
      // because we already know it.
7390
      if (isset($options) && $options['return'] != Database::RETURN_INSERT_ID) {
7391
        $object->$serial = $fields[$serial];
7392
      }
7393
      else {
7394
        $object->$serial = $query_return;
7395
      }
7396
    }
7397
  }
7398
  // If we have a single-field primary key but got no insert ID, the
7399
  // query failed. Note that we explicitly check for FALSE, because
7400
  // a valid update query which doesn't change any values will return
7401
  // zero (0) affected rows.
7402
  elseif ($query_return === FALSE && count($primary_keys) == 1) {
7403
    $return = FALSE;
7404
  }
7405

    
7406
  // If we are inserting, populate empty fields with default values.
7407
  if (empty($primary_keys)) {
7408
    foreach ($schema['fields'] as $field => $info) {
7409
      if (isset($info['default']) && !property_exists($object, $field)) {
7410
        $object->$field = $info['default'];
7411
      }
7412
    }
7413
  }
7414

    
7415
  // If we began with an array, convert back.
7416
  if (is_array($record)) {
7417
    $record = (array) $object;
7418
  }
7419

    
7420
  return $return;
7421
}
7422

    
7423
/**
7424
 * @} End of "addtogroup schemaapi".
7425
 */
7426

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

    
7474
  if (!isset($info[$filename])) {
7475
    if (!file_exists($filename)) {
7476
      $info[$filename] = array();
7477
    }
7478
    else {
7479
      $data = file_get_contents($filename);
7480
      $info[$filename] = drupal_parse_info_format($data);
7481
    }
7482
  }
7483
  return $info[$filename];
7484
}
7485

    
7486
/**
7487
 * Parses data in Drupal's .info format.
7488
 *
7489
 * Data should be in an .ini-like format to specify values. White-space
7490
 * generally doesn't matter, except inside values:
7491
 * @code
7492
 *   key = value
7493
 *   key = "value"
7494
 *   key = 'value'
7495
 *   key = "multi-line
7496
 *   value"
7497
 *   key = 'multi-line
7498
 *   value'
7499
 *   key
7500
 *   =
7501
 *   'value'
7502
 * @endcode
7503
 *
7504
 * Arrays are created using a HTTP GET alike syntax:
7505
 * @code
7506
 *   key[] = "numeric array"
7507
 *   key[index] = "associative array"
7508
 *   key[index][] = "nested numeric array"
7509
 *   key[index][index] = "nested associative array"
7510
 * @endcode
7511
 *
7512
 * PHP constants are substituted in, but only when used as the entire value.
7513
 * Comments should start with a semi-colon at the beginning of a line.
7514
 *
7515
 * @param $data
7516
 *   A string to parse.
7517
 *
7518
 * @return
7519
 *   The info array.
7520
 *
7521
 * @see drupal_parse_info_file()
7522
 */
7523
function drupal_parse_info_format($data) {
7524
  $info = array();
7525

    
7526
  if (preg_match_all('
7527
    @^\s*                           # Start at the beginning of a line, ignoring leading whitespace
7528
    ((?:
7529
      [^=;\[\]]|                    # Key names cannot contain equal signs, semi-colons or square brackets,
7530
      \[[^\[\]]*\]                  # unless they are balanced and not nested
7531
    )+?)
7532
    \s*=\s*                         # Key/value pairs are separated by equal signs (ignoring white-space)
7533
    (?:
7534
      ("(?:[^"]|(?<=\\\\)")*")|     # Double-quoted string, which may contain slash-escaped quotes/slashes
7535
      (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
7536
      ([^\r\n]*?)                   # Non-quoted string
7537
    )\s*$                           # Stop at the next end of a line, ignoring trailing whitespace
7538
    @msx', $data, $matches, PREG_SET_ORDER)) {
7539
    foreach ($matches as $match) {
7540
      // Fetch the key and value string.
7541
      $i = 0;
7542
      foreach (array('key', 'value1', 'value2', 'value3') as $var) {
7543
        $$var = isset($match[++$i]) ? $match[$i] : '';
7544
      }
7545
      $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
7546

    
7547
      // Parse array syntax.
7548
      $keys = preg_split('/\]?\[/', rtrim($key, ']'));
7549
      $last = array_pop($keys);
7550
      $parent = &$info;
7551

    
7552
      // Create nested arrays.
7553
      foreach ($keys as $key) {
7554
        if ($key == '') {
7555
          $key = count($parent);
7556
        }
7557
        if (!isset($parent[$key]) || !is_array($parent[$key])) {
7558
          $parent[$key] = array();
7559
        }
7560
        $parent = &$parent[$key];
7561
      }
7562

    
7563
      // Handle PHP constants.
7564
      if (preg_match('/^\w+$/i', $value) && defined($value)) {
7565
        $value = constant($value);
7566
      }
7567

    
7568
      // Insert actual value.
7569
      if ($last == '') {
7570
        $last = count($parent);
7571
      }
7572
      $parent[$last] = $value;
7573
    }
7574
  }
7575

    
7576
  return $info;
7577
}
7578

    
7579
/**
7580
 * Returns a list of severity levels, as defined in RFC 3164.
7581
 *
7582
 * @return
7583
 *   Array of the possible severity levels for log messages.
7584
 *
7585
 * @see http://www.ietf.org/rfc/rfc3164.txt
7586
 * @see watchdog()
7587
 * @ingroup logging_severity_levels
7588
 */
7589
function watchdog_severity_levels() {
7590
  return array(
7591
    WATCHDOG_EMERGENCY => t('emergency'),
7592
    WATCHDOG_ALERT     => t('alert'),
7593
    WATCHDOG_CRITICAL  => t('critical'),
7594
    WATCHDOG_ERROR     => t('error'),
7595
    WATCHDOG_WARNING   => t('warning'),
7596
    WATCHDOG_NOTICE    => t('notice'),
7597
    WATCHDOG_INFO      => t('info'),
7598
    WATCHDOG_DEBUG     => t('debug'),
7599
  );
7600
}
7601

    
7602

    
7603
/**
7604
 * Explodes a string of tags into an array.
7605
 *
7606
 * @see drupal_implode_tags()
7607
 */
7608
function drupal_explode_tags($tags) {
7609
  // This regexp allows the following types of user input:
7610
  // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
7611
  $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
7612
  preg_match_all($regexp, $tags, $matches);
7613
  $typed_tags = array_unique($matches[1]);
7614

    
7615
  $tags = array();
7616
  foreach ($typed_tags as $tag) {
7617
    // If a user has escaped a term (to demonstrate that it is a group,
7618
    // or includes a comma or quote character), we remove the escape
7619
    // formatting so to save the term into the database as the user intends.
7620
    $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
7621
    if ($tag != "") {
7622
      $tags[] = $tag;
7623
    }
7624
  }
7625

    
7626
  return $tags;
7627
}
7628

    
7629
/**
7630
 * Implodes an array of tags into a string.
7631
 *
7632
 * @see drupal_explode_tags()
7633
 */
7634
function drupal_implode_tags($tags) {
7635
  $encoded_tags = array();
7636
  foreach ($tags as $tag) {
7637
    // Commas and quotes in tag names are special cases, so encode them.
7638
    if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
7639
      $tag = '"' . str_replace('"', '""', $tag) . '"';
7640
    }
7641

    
7642
    $encoded_tags[] = $tag;
7643
  }
7644
  return implode(', ', $encoded_tags);
7645
}
7646

    
7647
/**
7648
 * Flushes all cached data on the site.
7649
 *
7650
 * Empties cache tables, rebuilds the menu cache and theme registries, and
7651
 * invokes a hook so that other modules' cache data can be cleared as well.
7652
 */
7653
function drupal_flush_all_caches() {
7654
  // Change query-strings on css/js files to enforce reload for all users.
7655
  _drupal_flush_css_js();
7656

    
7657
  registry_rebuild();
7658
  drupal_clear_css_cache();
7659
  drupal_clear_js_cache();
7660

    
7661
  // Rebuild the theme data. Note that the module data is rebuilt above, as
7662
  // part of registry_rebuild().
7663
  system_rebuild_theme_data();
7664
  drupal_theme_rebuild();
7665

    
7666
  entity_info_cache_clear();
7667
  node_types_rebuild();
7668
  // node_menu() defines menu items based on node types so it needs to come
7669
  // after node types are rebuilt.
7670
  menu_rebuild();
7671

    
7672
  // Synchronize to catch any actions that were added or removed.
7673
  actions_synchronize();
7674

    
7675
  // Don't clear cache_form - in-progress form submissions may break.
7676
  // Ordered so clearing the page cache will always be the last action.
7677
  $core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
7678
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
7679
  foreach ($cache_tables as $table) {
7680
    cache_clear_all('*', $table, TRUE);
7681
  }
7682

    
7683
  // Rebuild the bootstrap module list. We do this here so that developers
7684
  // can get new hook_boot() implementations registered without having to
7685
  // write a hook_update_N() function.
7686
  _system_update_bootstrap_status();
7687
}
7688

    
7689
/**
7690
 * Changes the dummy query string added to all CSS and JavaScript files.
7691
 *
7692
 * Changing the dummy query string appended to CSS and JavaScript files forces
7693
 * all browsers to reload fresh files.
7694
 */
7695
function _drupal_flush_css_js() {
7696
  // The timestamp is converted to base 36 in order to make it more compact.
7697
  variable_set('css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
7698
}
7699

    
7700
/**
7701
 * Outputs debug information.
7702
 *
7703
 * The debug information is passed on to trigger_error() after being converted
7704
 * to a string using _drupal_debug_message().
7705
 *
7706
 * @param $data
7707
 *   Data to be output.
7708
 * @param $label
7709
 *   Label to prefix the data.
7710
 * @param $print_r
7711
 *   Flag to switch between print_r() and var_export() for data conversion to
7712
 *   string. Set $print_r to TRUE when dealing with a recursive data structure
7713
 *   as var_export() will generate an error.
7714
 */
7715
function debug($data, $label = NULL, $print_r = FALSE) {
7716
  // Print $data contents to string.
7717
  $string = check_plain($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
7718

    
7719
  // Display values with pre-formatting to increase readability.
7720
  $string = '<pre>' . $string . '</pre>';
7721

    
7722
  trigger_error(trim($label ? "$label: $string" : $string));
7723
}
7724

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

    
7793
/**
7794
 * Checks whether a version is compatible with a given dependency.
7795
 *
7796
 * @param $v
7797
 *   The parsed dependency structure from drupal_parse_dependency().
7798
 * @param $current_version
7799
 *   The version to check against (like 4.2).
7800
 *
7801
 * @return
7802
 *   NULL if compatible, otherwise the original dependency version string that
7803
 *   caused the incompatibility.
7804
 *
7805
 * @see drupal_parse_dependency()
7806
 */
7807
function drupal_check_incompatibility($v, $current_version) {
7808
  if (!empty($v['versions'])) {
7809
    foreach ($v['versions'] as $required_version) {
7810
      if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
7811
        return $v['original_version'];
7812
      }
7813
    }
7814
  }
7815
}
7816

    
7817
/**
7818
 * Get the entity info array of an entity type.
7819
 *
7820
 * @param $entity_type
7821
 *   The entity type, e.g. node, for which the info shall be returned, or NULL
7822
 *   to return an array with info about all types.
7823
 *
7824
 * @see hook_entity_info()
7825
 * @see hook_entity_info_alter()
7826
 */
7827
function entity_get_info($entity_type = NULL) {
7828
  global $language;
7829

    
7830
  // Use the advanced drupal_static() pattern, since this is called very often.
7831
  static $drupal_static_fast;
7832
  if (!isset($drupal_static_fast)) {
7833
    $drupal_static_fast['entity_info'] = &drupal_static(__FUNCTION__);
7834
  }
7835
  $entity_info = &$drupal_static_fast['entity_info'];
7836

    
7837
  // hook_entity_info() includes translated strings, so each language is cached
7838
  // separately.
7839
  $langcode = $language->language;
7840

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

    
7890
  if (empty($entity_type)) {
7891
    return $entity_info;
7892
  }
7893
  elseif (isset($entity_info[$entity_type])) {
7894
    return $entity_info[$entity_type];
7895
  }
7896
}
7897

    
7898
/**
7899
 * Resets the cached information about entity types.
7900
 */
7901
function entity_info_cache_clear() {
7902
  drupal_static_reset('entity_get_info');
7903
  // Clear all languages.
7904
  cache_clear_all('entity_info:', 'cache', TRUE);
7905
}
7906

    
7907
/**
7908
 * Helper function to extract id, vid, and bundle name from an entity.
7909
 *
7910
 * @param $entity_type
7911
 *   The entity type; e.g. 'node' or 'user'.
7912
 * @param $entity
7913
 *   The entity from which to extract values.
7914
 *
7915
 * @return
7916
 *   A numerically indexed array (not a hash table) containing these
7917
 *   elements:
7918
 *   - 0: Primary ID of the entity.
7919
 *   - 1: Revision ID of the entity, or NULL if $entity_type is not versioned.
7920
 *   - 2: Bundle name of the entity, or NULL if $entity_type has no bundles.
7921
 */
7922
function entity_extract_ids($entity_type, $entity) {
7923
  $info = entity_get_info($entity_type);
7924

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

    
7929
  if (!empty($info['entity keys']['bundle'])) {
7930
    // Explicitly fail for malformed entities missing the bundle property.
7931
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
7932
      throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
7933
    }
7934
    $bundle = $entity->{$info['entity keys']['bundle']};
7935
  }
7936
  else {
7937
    // The entity type provides no bundle key: assume a single bundle, named
7938
    // after the entity type.
7939
    $bundle = $entity_type;
7940
  }
7941

    
7942
  return array($id, $vid, $bundle);
7943
}
7944

    
7945
/**
7946
 * Helper function to assemble an object structure with initial ids.
7947
 *
7948
 * This function can be seen as reciprocal to entity_extract_ids().
7949
 *
7950
 * @param $entity_type
7951
 *   The entity type; e.g. 'node' or 'user'.
7952
 * @param $ids
7953
 *   A numerically indexed array, as returned by entity_extract_ids().
7954
 *
7955
 * @return
7956
 *   An entity structure, initialized with the ids provided.
7957
 *
7958
 * @see entity_extract_ids()
7959
 */
7960
function entity_create_stub_entity($entity_type, $ids) {
7961
  $entity = new stdClass();
7962
  $info = entity_get_info($entity_type);
7963
  $entity->{$info['entity keys']['id']} = $ids[0];
7964
  if (!empty($info['entity keys']['revision']) && isset($ids[1])) {
7965
    $entity->{$info['entity keys']['revision']} = $ids[1];
7966
  }
7967
  if (!empty($info['entity keys']['bundle']) && isset($ids[2])) {
7968
    $entity->{$info['entity keys']['bundle']} = $ids[2];
7969
  }
7970
  return $entity;
7971
}
7972

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

    
8018
/**
8019
 * Loads the unchanged, i.e. not modified, entity from the database.
8020
 *
8021
 * Unlike entity_load() this function ensures the entity is directly loaded from
8022
 * the database, thus bypassing any static cache. In particular, this function
8023
 * is useful to determine changes by comparing the entity being saved to the
8024
 * stored entity.
8025
 *
8026
 * @param $entity_type
8027
 *   The entity type to load, e.g. node or user.
8028
 * @param $id
8029
 *   The ID of the entity to load.
8030
 *
8031
 * @return
8032
 *   The unchanged entity, or FALSE if the entity cannot be loaded.
8033
 */
8034
function entity_load_unchanged($entity_type, $id) {
8035
  entity_get_controller($entity_type)->resetCache(array($id));
8036
  $result = entity_get_controller($entity_type)->load(array($id));
8037
  return reset($result);
8038
}
8039

    
8040
/**
8041
 * Gets the entity controller for an entity type.
8042
 *
8043
 * @return DrupalEntityControllerInterface
8044
 *   The entity controller object for the specified entity type.
8045
 */
8046
function entity_get_controller($entity_type) {
8047
  $controllers = &drupal_static(__FUNCTION__, array());
8048
  if (!isset($controllers[$entity_type])) {
8049
    $type_info = entity_get_info($entity_type);
8050
    $class = $type_info['controller class'];
8051
    $controllers[$entity_type] = new $class($entity_type);
8052
  }
8053
  return $controllers[$entity_type];
8054
}
8055

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

    
8085
  // To ensure hooks are only run once per entity, check for an
8086
  // entity_view_prepared flag and only process items without it.
8087
  // @todo: resolve this more generally for both entity and field level hooks.
8088
  $prepare = array();
8089
  foreach ($entities as $id => $entity) {
8090
    if (empty($entity->entity_view_prepared)) {
8091
      // Add this entity to the items to be prepared.
8092
      $prepare[$id] = $entity;
8093

    
8094
      // Mark this item as prepared.
8095
      $entity->entity_view_prepared = TRUE;
8096
    }
8097
  }
8098

    
8099
  if (!empty($prepare)) {
8100
    module_invoke_all('entity_prepare_view', $prepare, $entity_type, $langcode);
8101
  }
8102
}
8103

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

    
8132
  // To ensure hooks are never run after field_attach_prepare_view() only
8133
  // process items without the entity_view_prepared flag.
8134
  $entities_by_view_mode = array();
8135
  foreach ($entities as $id => $entity) {
8136
    $entity_view_mode = $view_mode;
8137
    if (empty($entity->entity_view_prepared)) {
8138

    
8139
      // Allow modules to change the view mode.
8140
      $context = array(
8141
        'entity_type' => $entity_type,
8142
        'entity' => $entity,
8143
        'langcode' => $langcode,
8144
      );
8145
      drupal_alter('entity_view_mode', $entity_view_mode, $context);
8146
    }
8147

    
8148
    $entities_by_view_mode[$entity_view_mode][$id] = $entity;
8149
  }
8150

    
8151
  return $entities_by_view_mode;
8152
}
8153

    
8154
/**
8155
 * Returns the URI elements of an entity.
8156
 *
8157
 * @param $entity_type
8158
 *   The entity type; e.g. 'node' or 'user'.
8159
 * @param $entity
8160
 *   The entity for which to generate a path.
8161
 * @return
8162
 *   An array containing the 'path' and 'options' keys used to build the URI of
8163
 *   the entity, and matching the signature of url(). NULL if the entity has no
8164
 *   URI of its own.
8165
 */
8166
function entity_uri($entity_type, $entity) {
8167
  $info = entity_get_info($entity_type);
8168
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
8169

    
8170
  // A bundle-specific callback takes precedence over the generic one for the
8171
  // entity type.
8172
  if (isset($info['bundles'][$bundle]['uri callback'])) {
8173
    $uri_callback = $info['bundles'][$bundle]['uri callback'];
8174
  }
8175
  elseif (isset($info['uri callback'])) {
8176
    $uri_callback = $info['uri callback'];
8177
  }
8178
  else {
8179
    return NULL;
8180
  }
8181

    
8182
  // Invoke the callback to get the URI. If there is no callback, return NULL.
8183
  if (isset($uri_callback) && function_exists($uri_callback)) {
8184
    $uri = $uri_callback($entity);
8185
    // Pass the entity data to url() so that alter functions do not need to
8186
    // lookup this entity again.
8187
    $uri['options']['entity_type'] = $entity_type;
8188
    $uri['options']['entity'] = $entity;
8189
    return $uri;
8190
  }
8191
}
8192

    
8193
/**
8194
 * Returns the label of an entity.
8195
 *
8196
 * See the 'label callback' component of the hook_entity_info() return value
8197
 * for more information.
8198
 *
8199
 * @param $entity_type
8200
 *   The entity type; e.g., 'node' or 'user'.
8201
 * @param $entity
8202
 *   The entity for which to generate the label.
8203
 *
8204
 * @return
8205
 *   The entity label, or FALSE if not found.
8206
 */
8207
function entity_label($entity_type, $entity) {
8208
  $label = FALSE;
8209
  $info = entity_get_info($entity_type);
8210
  if (isset($info['label callback']) && function_exists($info['label callback'])) {
8211
    $label = $info['label callback']($entity, $entity_type);
8212
  }
8213
  elseif (!empty($info['entity keys']['label']) && isset($entity->{$info['entity keys']['label']})) {
8214
    $label = $entity->{$info['entity keys']['label']};
8215
  }
8216

    
8217
  return $label;
8218
}
8219

    
8220
/**
8221
 * Returns the language of an entity.
8222
 *
8223
 * @param $entity_type
8224
 *   The entity type; e.g., 'node' or 'user'.
8225
 * @param $entity
8226
 *   The entity for which to get the language.
8227
 *
8228
 * @return
8229
 *   A valid language code or NULL if the entity has no language support.
8230
 */
8231
function entity_language($entity_type, $entity) {
8232
  $info = entity_get_info($entity_type);
8233

    
8234
  // Invoke the callback to get the language. If there is no callback, try to
8235
  // get it from a property of the entity, otherwise NULL.
8236
  if (isset($info['language callback']) && function_exists($info['language callback'])) {
8237
    $langcode = $info['language callback']($entity_type, $entity);
8238
  }
8239
  elseif (!empty($info['entity keys']['language']) && isset($entity->{$info['entity keys']['language']})) {
8240
    $langcode = $entity->{$info['entity keys']['language']};
8241
  }
8242
  else {
8243
    // The value returned in D8 would be LANGUAGE_NONE, we cannot use it here to
8244
    // preserve backward compatibility. In fact this function has been
8245
    // introduced very late in the D7 life cycle, mainly as the proper default
8246
    // for field_attach_form(). By returning LANGUAGE_NONE when no language
8247
    // information is available, we would introduce a potentially BC-breaking
8248
    // API change, since field_attach_form() defaults to the default language
8249
    // instead of LANGUAGE_NONE. Moreover this allows us to distinguish between
8250
    // entities that have no language specified from ones that do not have
8251
    // language support at all.
8252
    $langcode = NULL;
8253
  }
8254

    
8255
  return $langcode;
8256
}
8257

    
8258
/**
8259
 * Attaches field API validation to entity forms.
8260
 */
8261
function entity_form_field_validate($entity_type, $form, &$form_state) {
8262
  // All field attach API functions act on an entity object, but during form
8263
  // validation, we don't have one. $form_state contains the entity as it was
8264
  // prior to processing the current form submission, and we must not update it
8265
  // until we have fully validated the submitted input. Therefore, for
8266
  // validation, act on a pseudo entity created out of the form values.
8267
  $pseudo_entity = (object) $form_state['values'];
8268
  field_attach_form_validate($entity_type, $pseudo_entity, $form, $form_state);
8269
}
8270

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

    
8296
  // Copy top-level form values that are not for fields to entity properties,
8297
  // without changing existing entity properties that are not being edited by
8298
  // this form. Copying field values must be done using field_attach_submit().
8299
  $values_excluding_fields = $info['fieldable'] ? array_diff_key($form_state['values'], field_info_instances($entity_type, $bundle)) : $form_state['values'];
8300
  foreach ($values_excluding_fields as $key => $value) {
8301
    $entity->$key = $value;
8302
  }
8303

    
8304
  // Invoke all specified builders for copying form values to entity properties.
8305
  if (isset($form['#entity_builders'])) {
8306
    foreach ($form['#entity_builders'] as $function) {
8307
      $function($entity_type, $entity, $form, $form_state);
8308
    }
8309
  }
8310

    
8311
  // Copy field values to the entity.
8312
  if ($info['fieldable']) {
8313
    field_attach_submit($entity_type, $entity, $form, $form_state);
8314
  }
8315
}
8316

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

    
8350
/**
8351
 * Retrieves a list of all available archivers.
8352
 *
8353
 * @see hook_archiver_info()
8354
 * @see hook_archiver_info_alter()
8355
 */
8356
function archiver_get_info() {
8357
  $archiver_info = &drupal_static(__FUNCTION__, array());
8358

    
8359
  if (empty($archiver_info)) {
8360
    $cache = cache_get('archiver_info');
8361
    if ($cache === FALSE) {
8362
      // Rebuild the cache and save it.
8363
      $archiver_info = module_invoke_all('archiver_info');
8364
      drupal_alter('archiver_info', $archiver_info);
8365
      uasort($archiver_info, 'drupal_sort_weight');
8366
      cache_set('archiver_info', $archiver_info);
8367
    }
8368
    else {
8369
      $archiver_info = $cache->data;
8370
    }
8371
  }
8372

    
8373
  return $archiver_info;
8374
}
8375

    
8376
/**
8377
 * Returns a string of supported archive extensions.
8378
 *
8379
 * @return
8380
 *   A space-separated string of extensions suitable for use by the file
8381
 *   validation system.
8382
 */
8383
function archiver_get_extensions() {
8384
  $valid_extensions = array();
8385
  foreach (archiver_get_info() as $archive) {
8386
    foreach ($archive['extensions'] as $extension) {
8387
      foreach (explode('.', $extension) as $part) {
8388
        if (!in_array($part, $valid_extensions)) {
8389
          $valid_extensions[] = $part;
8390
        }
8391
      }
8392
    }
8393
  }
8394
  return implode(' ', $valid_extensions);
8395
}
8396

    
8397
/**
8398
 * Creates the appropriate archiver for the specified file.
8399
 *
8400
 * @param $file
8401
 *   The full path of the archive file. Note that stream wrapper paths are
8402
 *   supported, but not remote ones.
8403
 *
8404
 * @return
8405
 *   A newly created instance of the archiver class appropriate
8406
 *   for the specified file, already bound to that file.
8407
 *   If no appropriate archiver class was found, will return FALSE.
8408
 */
8409
function archiver_get_archiver($file) {
8410
  // Archivers can only work on local paths
8411
  $filepath = drupal_realpath($file);
8412
  if (!is_file($filepath)) {
8413
    throw new Exception(t('Archivers can only operate on local files: %file not supported', array('%file' => $file)));
8414
  }
8415
  $archiver_info = archiver_get_info();
8416

    
8417
  foreach ($archiver_info as $implementation) {
8418
    foreach ($implementation['extensions'] as $extension) {
8419
      // Because extensions may be multi-part, such as .tar.gz,
8420
      // we cannot use simpler approaches like substr() or pathinfo().
8421
      // This method isn't quite as clean but gets the job done.
8422
      // Also note that the file may not yet exist, so we cannot rely
8423
      // on fileinfo() or other disk-level utilities.
8424
      if (strrpos($filepath, '.' . $extension) === strlen($filepath) - strlen('.' . $extension)) {
8425
        return new $implementation['class']($filepath);
8426
      }
8427
    }
8428
  }
8429
}
8430

    
8431
/**
8432
 * Assembles the Drupal Updater registry.
8433
 *
8434
 * An Updater is a class that knows how to update various parts of the Drupal
8435
 * file system, for example to update modules that have newer releases, or to
8436
 * install a new theme.
8437
 *
8438
 * @return
8439
 *   The Drupal Updater class registry.
8440
 *
8441
 * @see hook_updater_info()
8442
 * @see hook_updater_info_alter()
8443
 */
8444
function drupal_get_updaters() {
8445
  $updaters = &drupal_static(__FUNCTION__);
8446
  if (!isset($updaters)) {
8447
    $updaters = module_invoke_all('updater_info');
8448
    drupal_alter('updater_info', $updaters);
8449
    uasort($updaters, 'drupal_sort_weight');
8450
  }
8451
  return $updaters;
8452
}
8453

    
8454
/**
8455
 * Assembles the Drupal FileTransfer registry.
8456
 *
8457
 * @return
8458
 *   The Drupal FileTransfer class registry.
8459
 *
8460
 * @see FileTransfer
8461
 * @see hook_filetransfer_info()
8462
 * @see hook_filetransfer_info_alter()
8463
 */
8464
function drupal_get_filetransfer_info() {
8465
  $info = &drupal_static(__FUNCTION__);
8466
  if (!isset($info)) {
8467
    // Since we have to manually set the 'file path' default for each
8468
    // module separately, we can't use module_invoke_all().
8469
    $info = array();
8470
    foreach (module_implements('filetransfer_info') as $module) {
8471
      $function = $module . '_filetransfer_info';
8472
      if (function_exists($function)) {
8473
        $result = $function();
8474
        if (isset($result) && is_array($result)) {
8475
          foreach ($result as &$values) {
8476
            if (empty($values['file path'])) {
8477
              $values['file path'] = drupal_get_path('module', $module);
8478
            }
8479
          }
8480
          $info = array_merge_recursive($info, $result);
8481
        }
8482
      }
8483
    }
8484
    drupal_alter('filetransfer_info', $info);
8485
    uasort($info, 'drupal_sort_weight');
8486
  }
8487
  return $info;
8488
}