Projet

Général

Profil

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

root / drupal7 / includes / common.inc @ 4444412d

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

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

    
625
  return $options;
626
}
627

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

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

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

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

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

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

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

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

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

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

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

    
795
  $result = new stdClass();
796

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

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

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

    
812
  timer_start(__FUNCTION__);
813

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

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

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

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

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

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

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

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

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

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

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

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

    
912
    return $result;
913
  }
914

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1089
  return $result;
1090
}
1091

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1368
  return $uri;
1369
}
1370

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

    
1391
/**
1392
 * Applies a very permissive XSS/HTML filter for admin-only use.
1393
 *
1394
 * Use only for fields where it is impractical to use the
1395
 * whole filter system, but where some (mainly inline) mark-up
1396
 * is desired (so check_plain() is not acceptable).
1397
 *
1398
 * Allows all tags that can be used inside an HTML body, save
1399
 * for scripts and styles.
1400
 */
1401
function filter_xss_admin($string) {
1402
  return filter_xss($string, array('a', 'abbr', 'acronym', 'address', 'article', 'aside', 'b', 'bdi', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'command', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'menu', 'meter', 'nav', 'ol', 'output', 'p', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'small', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time', 'tr', 'tt', 'u', 'ul', 'var', 'wbr'));
1403
}
1404

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

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

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

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

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

    
1487
  $string = $m[1];
1488

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1701
  return $output;
1702
}
1703

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

    
1717
  return $output;
1718
}
1719

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2690
  module_invoke_all('exit');
2691

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3019
  return $css;
3020
}
3021

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

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

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

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

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

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

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

    
3100
  return drupal_render($styles);
3101
}
3102

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

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

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

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

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

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

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

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

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

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

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

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

    
3518
  return $elements;
3519
}
3520

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3825
  return $identifier;
3826
}
3827

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

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

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

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

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

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

    
3954
  return $id;
3955
}
3956

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4533
  return $success;
4534
}
4535

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5104
function _drupal_bootstrap_full() {
5105
  static $called = FALSE;
5106

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

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

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

    
5147
  // Initialize $_GET['q'] prior to invoking hook_init().
5148
  drupal_path_initialize();
5149

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

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

    
5182
  if (drupal_page_is_cacheable()) {
5183

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

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

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

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

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

    
5235
  // Prevent session information from being saved while cron is running.
5236
  $original_session_saving = drupal_save_session();
5237
  drupal_save_session(FALSE);
5238

    
5239
  // Force the current user to anonymous to ensure consistent permissions on
5240
  // cron runs.
5241
  $original_user = $GLOBALS['user'];
5242
  $GLOBALS['user'] = drupal_anonymous_user();
5243

    
5244
  // Try to allocate enough time to run all the hook_cron implementations.
5245
  drupal_set_time_limit(240);
5246

    
5247
  $return = FALSE;
5248
  // Grab the defined cron queues.
5249
  $queues = module_invoke_all('cron_queue_info');
5250
  drupal_alter('cron_queue_info', $queues);
5251

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

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

    
5277
    // Record cron time.
5278
    variable_set('cron_last', REQUEST_TIME);
5279
    watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
5280

    
5281
    // Release cron lock.
5282
    lock_release('cron');
5283

    
5284
    // Return TRUE so other functions can check if it did run successfully
5285
    $return = TRUE;
5286
  }
5287

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

    
5312
  return $return;
5313
}
5314

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

    
5326
    // Release cron semaphore.
5327
    variable_del('cron_semaphore');
5328
  }
5329
}
5330

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

    
5382
  $searchdir = array($directory);
5383
  $files = array();
5384

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

    
5409
  // Always search sites/all/* as well as the global directories.
5410
  $searchdir[] = 'sites/all/' . $directory;
5411

    
5412
  if (file_exists("$config/$directory")) {
5413
    $searchdir[] = "$config/$directory";
5414
  }
5415

    
5416
  // Get current list of items.
5417
  if (!function_exists('file_scan_directory')) {
5418
    require_once DRUPAL_ROOT . '/includes/file.inc';
5419
  }
5420
  foreach ($searchdir as $dir) {
5421
    $files_to_add = file_scan_directory($dir, $mask, array('key' => $key, 'min_depth' => $min_depth));
5422

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

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

    
5448
  return $files;
5449
}
5450

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

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

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

    
5518
  // If rendering in all browsers, no need for conditional comments.
5519
  if ($browsers['IE'] === TRUE && $browsers['!IE']) {
5520
    return $elements;
5521
  }
5522

    
5523
  // Determine the conditional comment expression for Internet Explorer to
5524
  // evaluate.
5525
  if ($browsers['IE'] === TRUE) {
5526
    $expression = 'IE';
5527
  }
5528
  elseif ($browsers['IE'] === FALSE) {
5529
    $expression = '!IE';
5530
  }
5531
  else {
5532
    $expression = $browsers['IE'];
5533
  }
5534

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

    
5555
  return $elements;
5556
}
5557

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

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

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

    
5608
  $element['#markup'] = l($element['#title'], $element['#href'], $element['#options']);
5609
  return $element;
5610
}
5611

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

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

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

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

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

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

    
5765
  return drupal_render($page);
5766
}
5767

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

    
5851
  // Do not print elements twice.
5852
  if (!empty($elements['#printed'])) {
5853
    return '';
5854
  }
5855

    
5856
  // Try to fetch the element's markup from cache and return.
5857
  if (isset($elements['#cache'])) {
5858
    $cached_output = drupal_render_cache_get($elements);
5859
    if ($cached_output !== FALSE) {
5860
      return $cached_output;
5861
    }
5862
  }
5863

    
5864
  // If #markup is set, ensure #type is set. This allows to specify just #markup
5865
  // on an element without setting #type.
5866
  if (isset($elements['#markup']) && !isset($elements['#type'])) {
5867
    $elements['#type'] = 'markup';
5868
  }
5869

    
5870
  // If the default values for this element have not been loaded yet, populate
5871
  // them.
5872
  if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
5873
    $elements += element_info($elements['#type']);
5874
  }
5875

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

    
5887
  // Allow #pre_render to abort rendering.
5888
  if (!empty($elements['#printed'])) {
5889
    return '';
5890
  }
5891

    
5892
  // Get the children of the element, sorted by weight.
5893
  $children = element_children($elements, TRUE);
5894

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

    
5914
  // Let the theme functions in #theme_wrappers add markup around the rendered
5915
  // children.
5916
  if (isset($elements['#theme_wrappers'])) {
5917
    foreach ($elements['#theme_wrappers'] as $theme_wrapper) {
5918
      $elements['#children'] = theme($theme_wrapper, $elements);
5919
    }
5920
  }
5921

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

    
5933
  // Add any JavaScript state information associated with the element.
5934
  if (!empty($elements['#states'])) {
5935
    drupal_process_states($elements);
5936
  }
5937

    
5938
  // Add additional libraries, CSS, JavaScript an other custom
5939
  // attached data associated with this element.
5940
  if (!empty($elements['#attached'])) {
5941
    drupal_process_attached($elements);
5942
  }
5943

    
5944
  $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
5945
  $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
5946
  $output = $prefix . $elements['#children'] . $suffix;
5947

    
5948
  // Cache the processed element if #cache is set.
5949
  if (isset($elements['#cache'])) {
5950
    drupal_render_cache_set($output, $elements);
5951
  }
5952

    
5953
  $elements['#printed'] = TRUE;
5954
  return $output;
5955
}
5956

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

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

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

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

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

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

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

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

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

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

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

    
6169
  // If this was the first call to the function, return all attached elements
6170
  // and reset the static cache.
6171
  if ($return) {
6172
    $return = $attached;
6173
    $attached = array();
6174
    return $return;
6175
  }
6176
}
6177

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

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

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

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

    
6258
    if ($granularity & DRUPAL_CACHE_PER_PAGE) {
6259
      $cid_parts[] = $base_root . request_uri();
6260
    }
6261
  }
6262

    
6263
  return $cid_parts;
6264
}
6265

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

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

    
6304
/**
6305
 * Array sorting callback; sorts elements by title.
6306
 */
6307
function element_sort_by_title($a, $b) {
6308
  $a_title = (is_array($a) && isset($a['#title'])) ? $a['#title'] : '';
6309
  $b_title = (is_array($b) && isset($b['#title'])) ? $b['#title'] : '';
6310
  return strnatcasecmp($a_title, $b_title);
6311
}
6312

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

    
6327
  if (!isset($cache)) {
6328
    $cache = module_invoke_all('element_info');
6329
    foreach ($cache as $element_type => $info) {
6330
      $cache[$element_type]['#type'] = $element_type;
6331
    }
6332
    // Allow modules to alter the element type defaults.
6333
    drupal_alter('element_info', $cache);
6334
  }
6335

    
6336
  return isset($cache[$type]) ? $cache[$type] : array();
6337
}
6338

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

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

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

    
6391
/**
6392
 * Checks if the key is a property.
6393
 */
6394
function element_property($key) {
6395
  return $key[0] == '#';
6396
}
6397

    
6398
/**
6399
 * Gets properties of a structured array element (keys beginning with '#').
6400
 */
6401
function element_properties($element) {
6402
  return array_filter(array_keys((array) $element), 'element_property');
6403
}
6404

    
6405
/**
6406
 * Checks if the key is a child.
6407
 */
6408
function element_child($key) {
6409
  return !isset($key[0]) || $key[0] != '#';
6410
}
6411

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

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

    
6454
  return array_keys($children);
6455
}
6456

    
6457
/**
6458
 * Returns the visible children of an element.
6459
 *
6460
 * @param $elements
6461
 *   The parent element.
6462
 *
6463
 * @return
6464
 *   The array keys of the element's visible children.
6465
 */
6466
function element_get_visible_children(array $elements) {
6467
  $visible_children = array();
6468

    
6469
  foreach (element_children($elements) as $key) {
6470
    $child = $elements[$key];
6471

    
6472
    // Skip un-accessible children.
6473
    if (isset($child['#access']) && !$child['#access']) {
6474
      continue;
6475
    }
6476

    
6477
    // Skip value and hidden elements, since they are not rendered.
6478
    if (isset($child['#type']) && in_array($child['#type'], array('value', 'hidden'))) {
6479
      continue;
6480
    }
6481

    
6482
    $visible_children[$key] = $child;
6483
  }
6484

    
6485
  return array_keys($visible_children);
6486
}
6487

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

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

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

    
6548
  return $difference;
6549
}
6550

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

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

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

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

    
6937
/**
6938
 * @addtogroup schemaapi
6939
 * @{
6940
 */
6941

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

    
6956
  foreach ($schema as $name => $table) {
6957
    db_create_table($name, $table);
6958
  }
6959
}
6960

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

    
6980
  foreach ($schema as $table) {
6981
    if (db_table_exists($table['name'])) {
6982
      db_drop_table($table['name']);
6983
    }
6984
  }
6985
}
6986

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

    
7016
  if (isset($table) && isset($schema[$table])) {
7017
    return $schema[$table];
7018
  }
7019
  elseif (!empty($schema)) {
7020
    return $schema;
7021
  }
7022
  return array();
7023
}
7024

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

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

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

    
7116
  $schema = drupal_get_schema($table);
7117
  if (empty($schema)) {
7118
    return FALSE;
7119
  }
7120

    
7121
  $object = (object) $record;
7122
  $fields = array();
7123

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

    
7136
    // Skip field if it is in $primary_keys as it is unnecessary to update a
7137
    // field to the value it is already set to.
7138
    if (in_array($field, $primary_keys)) {
7139
      continue;
7140
    }
7141

    
7142
    if (!property_exists($object, $field)) {
7143
      // Skip fields that are not provided, default values are already known
7144
      // by the database.
7145
      continue;
7146
    }
7147

    
7148
    // Build array of fields to update or insert.
7149
    if (empty($info['serialize'])) {
7150
      $fields[$field] = $object->$field;
7151
    }
7152
    else {
7153
      $fields[$field] = serialize($object->$field);
7154
    }
7155

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

    
7175
  if (empty($fields)) {
7176
    return;
7177
  }
7178

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

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

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

    
7236
  // If we began with an array, convert back.
7237
  if (is_array($record)) {
7238
    $record = (array) $object;
7239
  }
7240

    
7241
  return $return;
7242
}
7243

    
7244
/**
7245
 * @} End of "addtogroup schemaapi".
7246
 */
7247

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

    
7286
  if (!isset($info[$filename])) {
7287
    if (!file_exists($filename)) {
7288
      $info[$filename] = array();
7289
    }
7290
    else {
7291
      $data = file_get_contents($filename);
7292
      $info[$filename] = drupal_parse_info_format($data);
7293
    }
7294
  }
7295
  return $info[$filename];
7296
}
7297

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

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

    
7360
      // Parse array syntax.
7361
      $keys = preg_split('/\]?\[/', rtrim($key, ']'));
7362
      $last = array_pop($keys);
7363
      $parent = &$info;
7364

    
7365
      // Create nested arrays.
7366
      foreach ($keys as $key) {
7367
        if ($key == '') {
7368
          $key = count($parent);
7369
        }
7370
        if (!isset($parent[$key]) || !is_array($parent[$key])) {
7371
          $parent[$key] = array();
7372
        }
7373
        $parent = &$parent[$key];
7374
      }
7375

    
7376
      // Handle PHP constants.
7377
      if (isset($constants[$value])) {
7378
        $value = $constants[$value];
7379
      }
7380

    
7381
      // Insert actual value.
7382
      if ($last == '') {
7383
        $last = count($parent);
7384
      }
7385
      $parent[$last] = $value;
7386
    }
7387
  }
7388

    
7389
  return $info;
7390
}
7391

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

    
7415

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

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

    
7439
  return $tags;
7440
}
7441

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

    
7455
    $encoded_tags[] = $tag;
7456
  }
7457
  return implode(', ', $encoded_tags);
7458
}
7459

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

    
7470
  registry_rebuild();
7471
  drupal_clear_css_cache();
7472
  drupal_clear_js_cache();
7473

    
7474
  // Rebuild the theme data. Note that the module data is rebuilt above, as
7475
  // part of registry_rebuild().
7476
  system_rebuild_theme_data();
7477
  drupal_theme_rebuild();
7478

    
7479
  entity_info_cache_clear();
7480
  node_types_rebuild();
7481
  // node_menu() defines menu items based on node types so it needs to come
7482
  // after node types are rebuilt.
7483
  menu_rebuild();
7484

    
7485
  // Synchronize to catch any actions that were added or removed.
7486
  actions_synchronize();
7487

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

    
7496
  // Rebuild the bootstrap module list. We do this here so that developers
7497
  // can get new hook_boot() implementations registered without having to
7498
  // write a hook_update_N() function.
7499
  _system_update_bootstrap_status();
7500
}
7501

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

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

    
7532
  // Display values with pre-formatting to increase readability.
7533
  $string = '<pre>' . $string . '</pre>';
7534

    
7535
  trigger_error(trim($label ? "$label: $string" : $string));
7536
}
7537

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

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

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

    
7633
  // Use the advanced drupal_static() pattern, since this is called very often.
7634
  static $drupal_static_fast;
7635
  if (!isset($drupal_static_fast)) {
7636
    $drupal_static_fast['entity_info'] = &drupal_static(__FUNCTION__);
7637
  }
7638
  $entity_info = &$drupal_static_fast['entity_info'];
7639

    
7640
  // hook_entity_info() includes translated strings, so each language is cached
7641
  // separately.
7642
  $langcode = $language->language;
7643

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

    
7692
  if (empty($entity_type)) {
7693
    return $entity_info;
7694
  }
7695
  elseif (isset($entity_info[$entity_type])) {
7696
    return $entity_info[$entity_type];
7697
  }
7698
}
7699

    
7700
/**
7701
 * Resets the cached information about entity types.
7702
 */
7703
function entity_info_cache_clear() {
7704
  drupal_static_reset('entity_get_info');
7705
  // Clear all languages.
7706
  cache_clear_all('entity_info:', 'cache', TRUE);
7707
}
7708

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

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

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

    
7744
  return array($id, $vid, $bundle);
7745
}
7746

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

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

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

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

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

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

    
7896
      // Mark this item as prepared.
7897
      $entity->entity_view_prepared = TRUE;
7898
    }
7899
  }
7900

    
7901
  if (!empty($prepare)) {
7902
    module_invoke_all('entity_prepare_view', $prepare, $entity_type, $langcode);
7903
  }
7904
}
7905

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

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

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

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

    
7969
  return $label;
7970
}
7971

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

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

    
8007
  return $langcode;
8008
}
8009

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

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

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

    
8056
  // Invoke all specified builders for copying form values to entity properties.
8057
  if (isset($form['#entity_builders'])) {
8058
    foreach ($form['#entity_builders'] as $function) {
8059
      $function($entity_type, $entity, $form, $form_state);
8060
    }
8061
  }
8062

    
8063
  // Copy field values to the entity.
8064
  if ($info['fieldable']) {
8065
    field_attach_submit($entity_type, $entity, $form, $form_state);
8066
  }
8067
}
8068

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

    
8102
/**
8103
 * Retrieves a list of all available archivers.
8104
 *
8105
 * @see hook_archiver_info()
8106
 * @see hook_archiver_info_alter()
8107
 */
8108
function archiver_get_info() {
8109
  $archiver_info = &drupal_static(__FUNCTION__, array());
8110

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

    
8125
  return $archiver_info;
8126
}
8127

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

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

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

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

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