1
|
<?php
|
2
|
|
3
|
/**
|
4
|
* @file
|
5
|
* Common functions that many Drupal modules will need to reference.
|
6
|
*
|
7
|
* The functions that are critical and need to be available even when serving
|
8
|
* a cached page are instead located in bootstrap.inc.
|
9
|
*/
|
10
|
|
11
|
/**
|
12
|
* @defgroup php_wrappers PHP wrapper functions
|
13
|
* @{
|
14
|
* Functions that are wrappers or custom implementations of PHP functions.
|
15
|
*
|
16
|
* Certain PHP functions should not be used in Drupal. Instead, Drupal's
|
17
|
* replacement functions should be used.
|
18
|
*
|
19
|
* For example, for improved or more secure UTF8-handling, or RFC-compliant
|
20
|
* handling of URLs in Drupal.
|
21
|
*
|
22
|
* For ease of use and memorizing, all these wrapper functions use the same name
|
23
|
* as the original PHP function, but prefixed with "drupal_". Beware, however,
|
24
|
* that not all wrapper functions support the same arguments as the original
|
25
|
* functions.
|
26
|
*
|
27
|
* You should always use these wrapper functions in your code.
|
28
|
*
|
29
|
* Wrong:
|
30
|
* @code
|
31
|
* $my_substring = substr($original_string, 0, 5);
|
32
|
* @endcode
|
33
|
*
|
34
|
* Correct:
|
35
|
* @code
|
36
|
* $my_substring = drupal_substr($original_string, 0, 5);
|
37
|
* @endcode
|
38
|
*
|
39
|
* @}
|
40
|
*/
|
41
|
|
42
|
/**
|
43
|
* Return status for saving which involved creating a new item.
|
44
|
*/
|
45
|
define('SAVED_NEW', 1);
|
46
|
|
47
|
/**
|
48
|
* Return status for saving which involved an update to an existing item.
|
49
|
*/
|
50
|
define('SAVED_UPDATED', 2);
|
51
|
|
52
|
/**
|
53
|
* Return status for saving which deleted an existing item.
|
54
|
*/
|
55
|
define('SAVED_DELETED', 3);
|
56
|
|
57
|
/**
|
58
|
* The default group for system CSS files added to the page.
|
59
|
*/
|
60
|
define('CSS_SYSTEM', -100);
|
61
|
|
62
|
/**
|
63
|
* The default group for module CSS files added to the page.
|
64
|
*/
|
65
|
define('CSS_DEFAULT', 0);
|
66
|
|
67
|
/**
|
68
|
* The default group for theme CSS files added to the page.
|
69
|
*/
|
70
|
define('CSS_THEME', 100);
|
71
|
|
72
|
/**
|
73
|
* The default group for JavaScript and jQuery libraries added to the page.
|
74
|
*/
|
75
|
define('JS_LIBRARY', -100);
|
76
|
|
77
|
/**
|
78
|
* The default group for module JavaScript code added to the page.
|
79
|
*/
|
80
|
define('JS_DEFAULT', 0);
|
81
|
|
82
|
/**
|
83
|
* The default group for theme JavaScript code added to the page.
|
84
|
*/
|
85
|
define('JS_THEME', 100);
|
86
|
|
87
|
/**
|
88
|
* Error code indicating that the request exceeded the specified timeout.
|
89
|
*
|
90
|
* @see drupal_http_request()
|
91
|
*/
|
92
|
define('HTTP_REQUEST_TIMEOUT', -1);
|
93
|
|
94
|
/**
|
95
|
* @defgroup block_caching Block Caching
|
96
|
* @{
|
97
|
* Constants that define each block's caching state.
|
98
|
*
|
99
|
* Modules specify how their blocks can be cached in their hook_block_info()
|
100
|
* implementations. Caching can be turned off (DRUPAL_NO_CACHE), managed by the
|
101
|
* module declaring the block (DRUPAL_CACHE_CUSTOM), or managed by the core
|
102
|
* Block module. If the Block module is managing the cache, you can specify that
|
103
|
* the block is the same for every page and user (DRUPAL_CACHE_GLOBAL), or that
|
104
|
* it can change depending on the page (DRUPAL_CACHE_PER_PAGE) or by user
|
105
|
* (DRUPAL_CACHE_PER_ROLE or DRUPAL_CACHE_PER_USER). Page and user settings can
|
106
|
* be combined with a bitwise-binary or operator; for example,
|
107
|
* DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE means that the block can change
|
108
|
* depending on the user role or page it is on.
|
109
|
*
|
110
|
* The block cache is cleared in cache_clear_all(), and uses the same clearing
|
111
|
* policy than page cache (node, comment, user, taxonomy added or updated...).
|
112
|
* Blocks requiring more fine-grained clearing might consider disabling the
|
113
|
* built-in block cache (DRUPAL_NO_CACHE) and roll their own.
|
114
|
*
|
115
|
* Note that user 1 is excluded from block caching.
|
116
|
*/
|
117
|
|
118
|
/**
|
119
|
* The block should not get cached.
|
120
|
*
|
121
|
* This setting should be used:
|
122
|
* - For simple blocks (notably those that do not perform any db query), where
|
123
|
* querying the db cache would be more expensive than directly generating the
|
124
|
* content.
|
125
|
* - For blocks that change too frequently.
|
126
|
*/
|
127
|
define('DRUPAL_NO_CACHE', -1);
|
128
|
|
129
|
/**
|
130
|
* The block is handling its own caching in its hook_block_view().
|
131
|
*
|
132
|
* This setting is useful when time based expiration is needed or a site uses a
|
133
|
* node access which invalidates standard block cache.
|
134
|
*/
|
135
|
define('DRUPAL_CACHE_CUSTOM', -2);
|
136
|
|
137
|
/**
|
138
|
* The block or element can change depending on the user's roles.
|
139
|
*
|
140
|
* This is the default setting for blocks, used when the block does not specify
|
141
|
* anything.
|
142
|
*/
|
143
|
define('DRUPAL_CACHE_PER_ROLE', 0x0001);
|
144
|
|
145
|
/**
|
146
|
* The block or element can change depending on the user.
|
147
|
*
|
148
|
* This setting can be resource-consuming for sites with large number of users,
|
149
|
* and thus should only be used when DRUPAL_CACHE_PER_ROLE is not sufficient.
|
150
|
*/
|
151
|
define('DRUPAL_CACHE_PER_USER', 0x0002);
|
152
|
|
153
|
/**
|
154
|
* The block or element can change depending on the page being viewed.
|
155
|
*/
|
156
|
define('DRUPAL_CACHE_PER_PAGE', 0x0004);
|
157
|
|
158
|
/**
|
159
|
* The block or element is the same for every user and page that it is visible.
|
160
|
*/
|
161
|
define('DRUPAL_CACHE_GLOBAL', 0x0008);
|
162
|
|
163
|
/**
|
164
|
* @} End of "defgroup block_caching".
|
165
|
*/
|
166
|
|
167
|
/**
|
168
|
* Adds content to a specified region.
|
169
|
*
|
170
|
* @param $region
|
171
|
* Page region the content is added to.
|
172
|
* @param $data
|
173
|
* Content to be added.
|
174
|
*/
|
175
|
function drupal_add_region_content($region = NULL, $data = NULL) {
|
176
|
static $content = array();
|
177
|
|
178
|
if (isset($region) && isset($data)) {
|
179
|
$content[$region][] = $data;
|
180
|
}
|
181
|
return $content;
|
182
|
}
|
183
|
|
184
|
/**
|
185
|
* Gets assigned content for a given region.
|
186
|
*
|
187
|
* @param $region
|
188
|
* A specified region to fetch content for. If NULL, all regions will be
|
189
|
* returned.
|
190
|
* @param $delimiter
|
191
|
* Content to be inserted between imploded array elements.
|
192
|
*/
|
193
|
function drupal_get_region_content($region = NULL, $delimiter = ' ') {
|
194
|
$content = drupal_add_region_content();
|
195
|
if (isset($region)) {
|
196
|
if (isset($content[$region]) && is_array($content[$region])) {
|
197
|
return implode($delimiter, $content[$region]);
|
198
|
}
|
199
|
}
|
200
|
else {
|
201
|
foreach (array_keys($content) as $region) {
|
202
|
if (is_array($content[$region])) {
|
203
|
$content[$region] = implode($delimiter, $content[$region]);
|
204
|
}
|
205
|
}
|
206
|
return $content;
|
207
|
}
|
208
|
}
|
209
|
|
210
|
/**
|
211
|
* Gets the name of the currently active installation profile.
|
212
|
*
|
213
|
* When this function is called during Drupal's initial installation process,
|
214
|
* the name of the profile that's about to be installed is stored in the global
|
215
|
* installation state. At all other times, the standard Drupal systems variable
|
216
|
* table contains the name of the current profile, and we can call
|
217
|
* variable_get() to determine what one is active.
|
218
|
*
|
219
|
* @return $profile
|
220
|
* The name of the installation profile.
|
221
|
*/
|
222
|
function drupal_get_profile() {
|
223
|
global $install_state;
|
224
|
|
225
|
if (isset($install_state['parameters']['profile'])) {
|
226
|
$profile = $install_state['parameters']['profile'];
|
227
|
}
|
228
|
else {
|
229
|
$profile = variable_get('install_profile', 'standard');
|
230
|
}
|
231
|
|
232
|
return $profile;
|
233
|
}
|
234
|
|
235
|
|
236
|
/**
|
237
|
* Sets the breadcrumb trail for the current page.
|
238
|
*
|
239
|
* @param $breadcrumb
|
240
|
* Array of links, starting with "home" and proceeding up to but not including
|
241
|
* the current page.
|
242
|
*/
|
243
|
function drupal_set_breadcrumb($breadcrumb = NULL) {
|
244
|
$stored_breadcrumb = &drupal_static(__FUNCTION__);
|
245
|
|
246
|
if (isset($breadcrumb)) {
|
247
|
$stored_breadcrumb = $breadcrumb;
|
248
|
}
|
249
|
return $stored_breadcrumb;
|
250
|
}
|
251
|
|
252
|
/**
|
253
|
* Gets the breadcrumb trail for the current page.
|
254
|
*/
|
255
|
function drupal_get_breadcrumb() {
|
256
|
$breadcrumb = drupal_set_breadcrumb();
|
257
|
|
258
|
if (!isset($breadcrumb)) {
|
259
|
$breadcrumb = menu_get_active_breadcrumb();
|
260
|
}
|
261
|
|
262
|
return $breadcrumb;
|
263
|
}
|
264
|
|
265
|
/**
|
266
|
* Returns a string containing RDF namespace declarations for use in XML and
|
267
|
* XHTML output.
|
268
|
*/
|
269
|
function drupal_get_rdf_namespaces() {
|
270
|
$xml_rdf_namespaces = array();
|
271
|
|
272
|
// Serializes the RDF namespaces in XML namespace syntax.
|
273
|
if (function_exists('rdf_get_namespaces')) {
|
274
|
foreach (rdf_get_namespaces() as $prefix => $uri) {
|
275
|
$xml_rdf_namespaces[] = 'xmlns:' . $prefix . '="' . $uri . '"';
|
276
|
}
|
277
|
}
|
278
|
return count($xml_rdf_namespaces) ? "\n " . implode("\n ", $xml_rdf_namespaces) : '';
|
279
|
}
|
280
|
|
281
|
/**
|
282
|
* Adds output to the HEAD tag of the HTML page.
|
283
|
*
|
284
|
* This function can be called as long as the headers aren't sent. Pass no
|
285
|
* arguments (or NULL for both) to retrieve the currently stored elements.
|
286
|
*
|
287
|
* @param $data
|
288
|
* A renderable array. If the '#type' key is not set then 'html_tag' will be
|
289
|
* added as the default '#type'.
|
290
|
* @param $key
|
291
|
* A unique string key to allow implementations of hook_html_head_alter() to
|
292
|
* identify the element in $data. Required if $data is not NULL.
|
293
|
*
|
294
|
* @return
|
295
|
* An array of all stored HEAD elements.
|
296
|
*
|
297
|
* @see theme_html_tag()
|
298
|
*/
|
299
|
function drupal_add_html_head($data = NULL, $key = NULL) {
|
300
|
$stored_head = &drupal_static(__FUNCTION__);
|
301
|
|
302
|
if (!isset($stored_head)) {
|
303
|
// Make sure the defaults, including Content-Type, come first.
|
304
|
$stored_head = _drupal_default_html_head();
|
305
|
}
|
306
|
|
307
|
if (isset($data) && isset($key)) {
|
308
|
if (!isset($data['#type'])) {
|
309
|
$data['#type'] = 'html_tag';
|
310
|
}
|
311
|
$stored_head[$key] = $data;
|
312
|
}
|
313
|
return $stored_head;
|
314
|
}
|
315
|
|
316
|
/**
|
317
|
* Returns elements that are always displayed in the HEAD tag of the HTML page.
|
318
|
*/
|
319
|
function _drupal_default_html_head() {
|
320
|
// Add default elements. Make sure the Content-Type comes first because the
|
321
|
// IE browser may be vulnerable to XSS via encoding attacks from any content
|
322
|
// that comes before this META tag, such as a TITLE tag.
|
323
|
$elements['system_meta_content_type'] = array(
|
324
|
'#type' => 'html_tag',
|
325
|
'#tag' => 'meta',
|
326
|
'#attributes' => array(
|
327
|
'http-equiv' => 'Content-Type',
|
328
|
'content' => 'text/html; charset=utf-8',
|
329
|
),
|
330
|
// Security: This always has to be output first.
|
331
|
'#weight' => -1000,
|
332
|
);
|
333
|
// Show Drupal and the major version number in the META GENERATOR tag.
|
334
|
// Get the major version.
|
335
|
list($version, ) = explode('.', VERSION);
|
336
|
$elements['system_meta_generator'] = array(
|
337
|
'#type' => 'html_tag',
|
338
|
'#tag' => 'meta',
|
339
|
'#attributes' => array(
|
340
|
'name' => 'Generator',
|
341
|
'content' => 'Drupal ' . $version . ' (http://drupal.org)',
|
342
|
),
|
343
|
);
|
344
|
// Also send the generator in the HTTP header.
|
345
|
$elements['system_meta_generator']['#attached']['drupal_add_http_header'][] = array('X-Generator', $elements['system_meta_generator']['#attributes']['content']);
|
346
|
return $elements;
|
347
|
}
|
348
|
|
349
|
/**
|
350
|
* Retrieves output to be displayed in the HEAD tag of the HTML page.
|
351
|
*/
|
352
|
function drupal_get_html_head() {
|
353
|
$elements = drupal_add_html_head();
|
354
|
drupal_alter('html_head', $elements);
|
355
|
return drupal_render($elements);
|
356
|
}
|
357
|
|
358
|
/**
|
359
|
* Adds a feed URL for the current page.
|
360
|
*
|
361
|
* This function can be called as long the HTML header hasn't been sent.
|
362
|
*
|
363
|
* @param $url
|
364
|
* An internal system path or a fully qualified external URL of the feed.
|
365
|
* @param $title
|
366
|
* The title of the feed.
|
367
|
*/
|
368
|
function drupal_add_feed($url = NULL, $title = '') {
|
369
|
$stored_feed_links = &drupal_static(__FUNCTION__, array());
|
370
|
|
371
|
if (isset($url)) {
|
372
|
$stored_feed_links[$url] = theme('feed_icon', array('url' => $url, 'title' => $title));
|
373
|
|
374
|
drupal_add_html_head_link(array(
|
375
|
'rel' => 'alternate',
|
376
|
'type' => 'application/rss+xml',
|
377
|
'title' => $title,
|
378
|
// Force the URL to be absolute, for consistency with other <link> tags
|
379
|
// output by Drupal.
|
380
|
'href' => url($url, array('absolute' => TRUE)),
|
381
|
));
|
382
|
}
|
383
|
return $stored_feed_links;
|
384
|
}
|
385
|
|
386
|
/**
|
387
|
* Gets the feed URLs for the current page.
|
388
|
*
|
389
|
* @param $delimiter
|
390
|
* A delimiter to split feeds by.
|
391
|
*/
|
392
|
function drupal_get_feeds($delimiter = "\n") {
|
393
|
$feeds = drupal_add_feed();
|
394
|
return implode($feeds, $delimiter);
|
395
|
}
|
396
|
|
397
|
/**
|
398
|
* @defgroup http_handling HTTP handling
|
399
|
* @{
|
400
|
* Functions to properly handle HTTP responses.
|
401
|
*/
|
402
|
|
403
|
/**
|
404
|
* Processes a URL query parameter array to remove unwanted elements.
|
405
|
*
|
406
|
* @param $query
|
407
|
* (optional) An array to be processed. Defaults to $_GET.
|
408
|
* @param $exclude
|
409
|
* (optional) A list of $query array keys to remove. Use "parent[child]" to
|
410
|
* exclude nested items. Defaults to array('q').
|
411
|
* @param $parent
|
412
|
* Internal use only. Used to build the $query array key for nested items.
|
413
|
*
|
414
|
* @return
|
415
|
* An array containing query parameters, which can be used for url().
|
416
|
*/
|
417
|
function drupal_get_query_parameters(array $query = NULL, array $exclude = array('q'), $parent = '') {
|
418
|
// Set defaults, if none given.
|
419
|
if (!isset($query)) {
|
420
|
$query = $_GET;
|
421
|
}
|
422
|
// If $exclude is empty, there is nothing to filter.
|
423
|
if (empty($exclude)) {
|
424
|
return $query;
|
425
|
}
|
426
|
elseif (!$parent) {
|
427
|
$exclude = array_flip($exclude);
|
428
|
}
|
429
|
|
430
|
$params = array();
|
431
|
foreach ($query as $key => $value) {
|
432
|
$string_key = ($parent ? $parent . '[' . $key . ']' : $key);
|
433
|
if (isset($exclude[$string_key])) {
|
434
|
continue;
|
435
|
}
|
436
|
|
437
|
if (is_array($value)) {
|
438
|
$params[$key] = drupal_get_query_parameters($value, $exclude, $string_key);
|
439
|
}
|
440
|
else {
|
441
|
$params[$key] = $value;
|
442
|
}
|
443
|
}
|
444
|
|
445
|
return $params;
|
446
|
}
|
447
|
|
448
|
/**
|
449
|
* Splits a URL-encoded query string into an array.
|
450
|
*
|
451
|
* @param $query
|
452
|
* The query string to split.
|
453
|
*
|
454
|
* @return
|
455
|
* An array of URL decoded couples $param_name => $value.
|
456
|
*/
|
457
|
function drupal_get_query_array($query) {
|
458
|
$result = array();
|
459
|
if (!empty($query)) {
|
460
|
foreach (explode('&', $query) as $param) {
|
461
|
$param = explode('=', $param, 2);
|
462
|
$result[$param[0]] = isset($param[1]) ? rawurldecode($param[1]) : '';
|
463
|
}
|
464
|
}
|
465
|
return $result;
|
466
|
}
|
467
|
|
468
|
/**
|
469
|
* Parses an array into a valid, rawurlencoded query string.
|
470
|
*
|
471
|
* This differs from http_build_query() as we need to rawurlencode() (instead of
|
472
|
* urlencode()) all query parameters.
|
473
|
*
|
474
|
* @param $query
|
475
|
* The query parameter array to be processed, e.g. $_GET.
|
476
|
* @param $parent
|
477
|
* Internal use only. Used to build the $query array key for nested items.
|
478
|
*
|
479
|
* @return
|
480
|
* A rawurlencoded string which can be used as or appended to the URL query
|
481
|
* string.
|
482
|
*
|
483
|
* @see drupal_get_query_parameters()
|
484
|
* @ingroup php_wrappers
|
485
|
*/
|
486
|
function drupal_http_build_query(array $query, $parent = '') {
|
487
|
$params = array();
|
488
|
|
489
|
foreach ($query as $key => $value) {
|
490
|
$key = ($parent ? $parent . '[' . rawurlencode($key) . ']' : rawurlencode($key));
|
491
|
|
492
|
// Recurse into children.
|
493
|
if (is_array($value)) {
|
494
|
$params[] = drupal_http_build_query($value, $key);
|
495
|
}
|
496
|
// If a query parameter value is NULL, only append its key.
|
497
|
elseif (!isset($value)) {
|
498
|
$params[] = $key;
|
499
|
}
|
500
|
else {
|
501
|
// For better readability of paths in query strings, we decode slashes.
|
502
|
$params[] = $key . '=' . str_replace('%2F', '/', rawurlencode($value));
|
503
|
}
|
504
|
}
|
505
|
|
506
|
return implode('&', $params);
|
507
|
}
|
508
|
|
509
|
/**
|
510
|
* Prepares a 'destination' URL query parameter for use with drupal_goto().
|
511
|
*
|
512
|
* Used to direct the user back to the referring page after completing a form.
|
513
|
* By default the current URL is returned. If a destination exists in the
|
514
|
* previous request, that destination is returned. As such, a destination can
|
515
|
* persist across multiple pages.
|
516
|
*
|
517
|
* @return
|
518
|
* An associative array containing the key:
|
519
|
* - destination: The path provided via the destination query string or, if
|
520
|
* not available, the current path.
|
521
|
*
|
522
|
* @see current_path()
|
523
|
* @see drupal_goto()
|
524
|
*/
|
525
|
function drupal_get_destination() {
|
526
|
$destination = &drupal_static(__FUNCTION__);
|
527
|
|
528
|
if (isset($destination)) {
|
529
|
return $destination;
|
530
|
}
|
531
|
|
532
|
if (isset($_GET['destination'])) {
|
533
|
$destination = array('destination' => $_GET['destination']);
|
534
|
}
|
535
|
else {
|
536
|
$path = $_GET['q'];
|
537
|
$query = drupal_http_build_query(drupal_get_query_parameters());
|
538
|
if ($query != '') {
|
539
|
$path .= '?' . $query;
|
540
|
}
|
541
|
$destination = array('destination' => $path);
|
542
|
}
|
543
|
return $destination;
|
544
|
}
|
545
|
|
546
|
/**
|
547
|
* Parses a URL string into its path, query, and fragment components.
|
548
|
*
|
549
|
* This function splits both internal paths like @code node?b=c#d @endcode and
|
550
|
* external URLs like @code https://example.com/a?b=c#d @endcode into their
|
551
|
* component parts. See
|
552
|
* @link http://tools.ietf.org/html/rfc3986#section-3 RFC 3986 @endlink for an
|
553
|
* explanation of what the component parts are.
|
554
|
*
|
555
|
* Note that, unlike the RFC, when passed an external URL, this function
|
556
|
* groups the scheme, authority, and path together into the path component.
|
557
|
*
|
558
|
* @param string $url
|
559
|
* The internal path or external URL string to parse.
|
560
|
*
|
561
|
* @return array
|
562
|
* An associative array containing:
|
563
|
* - path: The path component of $url. If $url is an external URL, this
|
564
|
* includes the scheme, authority, and path.
|
565
|
* - query: An array of query parameters from $url, if they exist.
|
566
|
* - fragment: The fragment component from $url, if it exists.
|
567
|
*
|
568
|
* @see drupal_goto()
|
569
|
* @see l()
|
570
|
* @see url()
|
571
|
* @see http://tools.ietf.org/html/rfc3986
|
572
|
*
|
573
|
* @ingroup php_wrappers
|
574
|
*/
|
575
|
function drupal_parse_url($url) {
|
576
|
$options = array(
|
577
|
'path' => NULL,
|
578
|
'query' => array(),
|
579
|
'fragment' => '',
|
580
|
);
|
581
|
|
582
|
// External URLs: not using parse_url() here, so we do not have to rebuild
|
583
|
// the scheme, host, and path without having any use for it.
|
584
|
if (strpos($url, '://') !== FALSE) {
|
585
|
// Split off everything before the query string into 'path'.
|
586
|
$parts = explode('?', $url);
|
587
|
$options['path'] = $parts[0];
|
588
|
// If there is a query string, transform it into keyed query parameters.
|
589
|
if (isset($parts[1])) {
|
590
|
$query_parts = explode('#', $parts[1]);
|
591
|
parse_str($query_parts[0], $options['query']);
|
592
|
// Take over the fragment, if there is any.
|
593
|
if (isset($query_parts[1])) {
|
594
|
$options['fragment'] = $query_parts[1];
|
595
|
}
|
596
|
}
|
597
|
}
|
598
|
// Internal URLs.
|
599
|
else {
|
600
|
// parse_url() does not support relative URLs, so make it absolute. E.g. the
|
601
|
// relative URL "foo/bar:1" isn't properly parsed.
|
602
|
$parts = parse_url('http://example.com/' . $url);
|
603
|
// Strip the leading slash that was just added.
|
604
|
$options['path'] = substr($parts['path'], 1);
|
605
|
if (isset($parts['query'])) {
|
606
|
parse_str($parts['query'], $options['query']);
|
607
|
}
|
608
|
if (isset($parts['fragment'])) {
|
609
|
$options['fragment'] = $parts['fragment'];
|
610
|
}
|
611
|
}
|
612
|
// The 'q' parameter contains the path of the current page if clean URLs are
|
613
|
// disabled. It overrides the 'path' of the URL when present, even if clean
|
614
|
// URLs are enabled, due to how Apache rewriting rules work.
|
615
|
if (isset($options['query']['q'])) {
|
616
|
$options['path'] = $options['query']['q'];
|
617
|
unset($options['query']['q']);
|
618
|
}
|
619
|
|
620
|
return $options;
|
621
|
}
|
622
|
|
623
|
/**
|
624
|
* Encodes a Drupal path for use in a URL.
|
625
|
*
|
626
|
* For aesthetic reasons slashes are not escaped.
|
627
|
*
|
628
|
* Note that url() takes care of calling this function, so a path passed to that
|
629
|
* function should not be encoded in advance.
|
630
|
*
|
631
|
* @param $path
|
632
|
* The Drupal path to encode.
|
633
|
*/
|
634
|
function drupal_encode_path($path) {
|
635
|
return str_replace('%2F', '/', rawurlencode($path));
|
636
|
}
|
637
|
|
638
|
/**
|
639
|
* Sends the user to a different page.
|
640
|
*
|
641
|
* This issues an on-site HTTP redirect. The function makes sure the redirected
|
642
|
* URL is formatted correctly.
|
643
|
*
|
644
|
* Usually the redirected URL is constructed from this function's input
|
645
|
* parameters. However you may override that behavior by setting a
|
646
|
* destination in either the $_REQUEST-array (i.e. by using
|
647
|
* the query string of an URI) This is used to direct the user back to
|
648
|
* the proper page after completing a form. For example, after editing
|
649
|
* a post on the 'admin/content'-page or after having logged on using the
|
650
|
* 'user login'-block in a sidebar. The function drupal_get_destination()
|
651
|
* can be used to help set the destination URL.
|
652
|
*
|
653
|
* Drupal will ensure that messages set by drupal_set_message() and other
|
654
|
* session data are written to the database before the user is redirected.
|
655
|
*
|
656
|
* This function ends the request; use it instead of a return in your menu
|
657
|
* callback.
|
658
|
*
|
659
|
* @param $path
|
660
|
* (optional) A Drupal path or a full URL, which will be passed to url() to
|
661
|
* compute the redirect for the URL.
|
662
|
* @param $options
|
663
|
* (optional) An associative array of additional URL options to pass to url().
|
664
|
* @param $http_response_code
|
665
|
* (optional) The HTTP status code to use for the redirection, defaults to
|
666
|
* 302. The valid values for 3xx redirection status codes are defined in
|
667
|
* @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3 RFC 2616 @endlink
|
668
|
* and the
|
669
|
* @link http://tools.ietf.org/html/draft-reschke-http-status-308-07 draft for the new HTTP status codes: @endlink
|
670
|
* - 301: Moved Permanently (the recommended value for most redirects).
|
671
|
* - 302: Found (default in Drupal and PHP, sometimes used for spamming search
|
672
|
* engines).
|
673
|
* - 303: See Other.
|
674
|
* - 304: Not Modified.
|
675
|
* - 305: Use Proxy.
|
676
|
* - 307: Temporary Redirect.
|
677
|
*
|
678
|
* @see drupal_get_destination()
|
679
|
* @see url()
|
680
|
*/
|
681
|
function drupal_goto($path = '', array $options = array(), $http_response_code = 302) {
|
682
|
// A destination in $_GET always overrides the function arguments.
|
683
|
// We do not allow absolute URLs to be passed via $_GET, as this can be an attack vector.
|
684
|
if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
|
685
|
$destination = drupal_parse_url($_GET['destination']);
|
686
|
$path = $destination['path'];
|
687
|
$options['query'] = $destination['query'];
|
688
|
$options['fragment'] = $destination['fragment'];
|
689
|
}
|
690
|
|
691
|
drupal_alter('drupal_goto', $path, $options, $http_response_code);
|
692
|
|
693
|
// The 'Location' HTTP header must be absolute.
|
694
|
$options['absolute'] = TRUE;
|
695
|
|
696
|
$url = url($path, $options);
|
697
|
|
698
|
header('Location: ' . $url, TRUE, $http_response_code);
|
699
|
|
700
|
// The "Location" header sends a redirect status code to the HTTP daemon. In
|
701
|
// some cases this can be wrong, so we make sure none of the code below the
|
702
|
// drupal_goto() call gets executed upon redirection.
|
703
|
drupal_exit($url);
|
704
|
}
|
705
|
|
706
|
/**
|
707
|
* Delivers a "site is under maintenance" message to the browser.
|
708
|
*
|
709
|
* Page callback functions wanting to report a "site offline" message should
|
710
|
* return MENU_SITE_OFFLINE instead of calling drupal_site_offline(). However,
|
711
|
* functions that are invoked in contexts where that return value might not
|
712
|
* bubble up to menu_execute_active_handler() should call drupal_site_offline().
|
713
|
*/
|
714
|
function drupal_site_offline() {
|
715
|
drupal_deliver_page(MENU_SITE_OFFLINE);
|
716
|
}
|
717
|
|
718
|
/**
|
719
|
* Delivers a "page not found" error to the browser.
|
720
|
*
|
721
|
* Page callback functions wanting to report a "page not found" message should
|
722
|
* return MENU_NOT_FOUND instead of calling drupal_not_found(). However,
|
723
|
* functions that are invoked in contexts where that return value might not
|
724
|
* bubble up to menu_execute_active_handler() should call drupal_not_found().
|
725
|
*/
|
726
|
function drupal_not_found() {
|
727
|
drupal_deliver_page(MENU_NOT_FOUND);
|
728
|
}
|
729
|
|
730
|
/**
|
731
|
* Delivers an "access denied" error to the browser.
|
732
|
*
|
733
|
* Page callback functions wanting to report an "access denied" message should
|
734
|
* return MENU_ACCESS_DENIED instead of calling drupal_access_denied(). However,
|
735
|
* functions that are invoked in contexts where that return value might not
|
736
|
* bubble up to menu_execute_active_handler() should call
|
737
|
* drupal_access_denied().
|
738
|
*/
|
739
|
function drupal_access_denied() {
|
740
|
drupal_deliver_page(MENU_ACCESS_DENIED);
|
741
|
}
|
742
|
|
743
|
/**
|
744
|
* Performs an HTTP request.
|
745
|
*
|
746
|
* This is a flexible and powerful HTTP client implementation. Correctly
|
747
|
* handles GET, POST, PUT or any other HTTP requests. Handles redirects.
|
748
|
*
|
749
|
* @param $url
|
750
|
* A string containing a fully qualified URI.
|
751
|
* @param array $options
|
752
|
* (optional) An array that can have one or more of the following elements:
|
753
|
* - headers: An array containing request headers to send as name/value pairs.
|
754
|
* - method: A string containing the request method. Defaults to 'GET'.
|
755
|
* - data: A string containing the request body, formatted as
|
756
|
* 'param=value¶m=value&...'. Defaults to NULL.
|
757
|
* - max_redirects: An integer representing how many times a redirect
|
758
|
* may be followed. Defaults to 3.
|
759
|
* - timeout: A float representing the maximum number of seconds the function
|
760
|
* call may take. The default is 30 seconds. If a timeout occurs, the error
|
761
|
* code is set to the HTTP_REQUEST_TIMEOUT constant.
|
762
|
* - context: A context resource created with stream_context_create().
|
763
|
*
|
764
|
* @return object
|
765
|
* An object that can have one or more of the following components:
|
766
|
* - request: A string containing the request body that was sent.
|
767
|
* - code: An integer containing the response status code, or the error code
|
768
|
* if an error occurred.
|
769
|
* - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
|
770
|
* - status_message: The status message from the response, if a response was
|
771
|
* received.
|
772
|
* - redirect_code: If redirected, an integer containing the initial response
|
773
|
* status code.
|
774
|
* - redirect_url: If redirected, a string containing the URL of the redirect
|
775
|
* target.
|
776
|
* - error: If an error occurred, the error message. Otherwise not set.
|
777
|
* - headers: An array containing the response headers as name/value pairs.
|
778
|
* HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
|
779
|
* easy access the array keys are returned in lower case.
|
780
|
* - data: A string containing the response body that was received.
|
781
|
*/
|
782
|
function drupal_http_request($url, array $options = array()) {
|
783
|
// Allow an alternate HTTP client library to replace Drupal's default
|
784
|
// implementation.
|
785
|
$override_function = variable_get('drupal_http_request_function', FALSE);
|
786
|
if (!empty($override_function) && function_exists($override_function)) {
|
787
|
return $override_function($url, $options);
|
788
|
}
|
789
|
|
790
|
$result = new stdClass();
|
791
|
|
792
|
// Parse the URL and make sure we can handle the schema.
|
793
|
$uri = @parse_url($url);
|
794
|
|
795
|
if ($uri == FALSE) {
|
796
|
$result->error = 'unable to parse URL';
|
797
|
$result->code = -1001;
|
798
|
return $result;
|
799
|
}
|
800
|
|
801
|
if (!isset($uri['scheme'])) {
|
802
|
$result->error = 'missing schema';
|
803
|
$result->code = -1002;
|
804
|
return $result;
|
805
|
}
|
806
|
|
807
|
timer_start(__FUNCTION__);
|
808
|
|
809
|
// Merge the default options.
|
810
|
$options += array(
|
811
|
'headers' => array(),
|
812
|
'method' => 'GET',
|
813
|
'data' => NULL,
|
814
|
'max_redirects' => 3,
|
815
|
'timeout' => 30.0,
|
816
|
'context' => NULL,
|
817
|
);
|
818
|
|
819
|
// Merge the default headers.
|
820
|
$options['headers'] += array(
|
821
|
'User-Agent' => 'Drupal (+http://drupal.org/)',
|
822
|
);
|
823
|
|
824
|
// stream_socket_client() requires timeout to be a float.
|
825
|
$options['timeout'] = (float) $options['timeout'];
|
826
|
|
827
|
// Use a proxy if one is defined and the host is not on the excluded list.
|
828
|
$proxy_server = variable_get('proxy_server', '');
|
829
|
if ($proxy_server && _drupal_http_use_proxy($uri['host'])) {
|
830
|
// Set the scheme so we open a socket to the proxy server.
|
831
|
$uri['scheme'] = 'proxy';
|
832
|
// Set the path to be the full URL.
|
833
|
$uri['path'] = $url;
|
834
|
// Since the URL is passed as the path, we won't use the parsed query.
|
835
|
unset($uri['query']);
|
836
|
|
837
|
// Add in username and password to Proxy-Authorization header if needed.
|
838
|
if ($proxy_username = variable_get('proxy_username', '')) {
|
839
|
$proxy_password = variable_get('proxy_password', '');
|
840
|
$options['headers']['Proxy-Authorization'] = 'Basic ' . base64_encode($proxy_username . (!empty($proxy_password) ? ":" . $proxy_password : ''));
|
841
|
}
|
842
|
// Some proxies reject requests with any User-Agent headers, while others
|
843
|
// require a specific one.
|
844
|
$proxy_user_agent = variable_get('proxy_user_agent', '');
|
845
|
// The default value matches neither condition.
|
846
|
if ($proxy_user_agent === NULL) {
|
847
|
unset($options['headers']['User-Agent']);
|
848
|
}
|
849
|
elseif ($proxy_user_agent) {
|
850
|
$options['headers']['User-Agent'] = $proxy_user_agent;
|
851
|
}
|
852
|
}
|
853
|
|
854
|
switch ($uri['scheme']) {
|
855
|
case 'proxy':
|
856
|
// Make the socket connection to a proxy server.
|
857
|
$socket = 'tcp://' . $proxy_server . ':' . variable_get('proxy_port', 8080);
|
858
|
// The Host header still needs to match the real request.
|
859
|
$options['headers']['Host'] = $uri['host'];
|
860
|
$options['headers']['Host'] .= isset($uri['port']) && $uri['port'] != 80 ? ':' . $uri['port'] : '';
|
861
|
break;
|
862
|
|
863
|
case 'http':
|
864
|
case 'feed':
|
865
|
$port = isset($uri['port']) ? $uri['port'] : 80;
|
866
|
$socket = 'tcp://' . $uri['host'] . ':' . $port;
|
867
|
// RFC 2616: "non-standard ports MUST, default ports MAY be included".
|
868
|
// We don't add the standard port to prevent from breaking rewrite rules
|
869
|
// checking the host that do not take into account the port number.
|
870
|
$options['headers']['Host'] = $uri['host'] . ($port != 80 ? ':' . $port : '');
|
871
|
break;
|
872
|
|
873
|
case 'https':
|
874
|
// Note: Only works when PHP is compiled with OpenSSL support.
|
875
|
$port = isset($uri['port']) ? $uri['port'] : 443;
|
876
|
$socket = 'ssl://' . $uri['host'] . ':' . $port;
|
877
|
$options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
|
878
|
break;
|
879
|
|
880
|
default:
|
881
|
$result->error = 'invalid schema ' . $uri['scheme'];
|
882
|
$result->code = -1003;
|
883
|
return $result;
|
884
|
}
|
885
|
|
886
|
if (empty($options['context'])) {
|
887
|
$fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout']);
|
888
|
}
|
889
|
else {
|
890
|
// Create a stream with context. Allows verification of a SSL certificate.
|
891
|
$fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
|
892
|
}
|
893
|
|
894
|
// Make sure the socket opened properly.
|
895
|
if (!$fp) {
|
896
|
// When a network error occurs, we use a negative number so it does not
|
897
|
// clash with the HTTP status codes.
|
898
|
$result->code = -$errno;
|
899
|
$result->error = trim($errstr) ? trim($errstr) : t('Error opening socket @socket', array('@socket' => $socket));
|
900
|
|
901
|
// Mark that this request failed. This will trigger a check of the web
|
902
|
// server's ability to make outgoing HTTP requests the next time that
|
903
|
// requirements checking is performed.
|
904
|
// See system_requirements().
|
905
|
variable_set('drupal_http_request_fails', TRUE);
|
906
|
|
907
|
return $result;
|
908
|
}
|
909
|
|
910
|
// Construct the path to act on.
|
911
|
$path = isset($uri['path']) ? $uri['path'] : '/';
|
912
|
if (isset($uri['query'])) {
|
913
|
$path .= '?' . $uri['query'];
|
914
|
}
|
915
|
|
916
|
// Only add Content-Length if we actually have any content or if it is a POST
|
917
|
// or PUT request. Some non-standard servers get confused by Content-Length in
|
918
|
// at least HEAD/GET requests, and Squid always requires Content-Length in
|
919
|
// POST/PUT requests.
|
920
|
$content_length = strlen($options['data']);
|
921
|
if ($content_length > 0 || $options['method'] == 'POST' || $options['method'] == 'PUT') {
|
922
|
$options['headers']['Content-Length'] = $content_length;
|
923
|
}
|
924
|
|
925
|
// If the server URL has a user then attempt to use basic authentication.
|
926
|
if (isset($uri['user'])) {
|
927
|
$options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ':'));
|
928
|
}
|
929
|
|
930
|
// If the database prefix is being used by SimpleTest to run the tests in a copied
|
931
|
// database then set the user-agent header to the database prefix so that any
|
932
|
// calls to other Drupal pages will run the SimpleTest prefixed database. The
|
933
|
// user-agent is used to ensure that multiple testing sessions running at the
|
934
|
// same time won't interfere with each other as they would if the database
|
935
|
// prefix were stored statically in a file or database variable.
|
936
|
$test_info = &$GLOBALS['drupal_test_info'];
|
937
|
if (!empty($test_info['test_run_id'])) {
|
938
|
$options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
|
939
|
}
|
940
|
|
941
|
$request = $options['method'] . ' ' . $path . " HTTP/1.0\r\n";
|
942
|
foreach ($options['headers'] as $name => $value) {
|
943
|
$request .= $name . ': ' . trim($value) . "\r\n";
|
944
|
}
|
945
|
$request .= "\r\n" . $options['data'];
|
946
|
$result->request = $request;
|
947
|
// Calculate how much time is left of the original timeout value.
|
948
|
$timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
|
949
|
if ($timeout > 0) {
|
950
|
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
|
951
|
fwrite($fp, $request);
|
952
|
}
|
953
|
|
954
|
// Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
|
955
|
// and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
|
956
|
// instead must invoke stream_get_meta_data() each iteration.
|
957
|
$info = stream_get_meta_data($fp);
|
958
|
$alive = !$info['eof'] && !$info['timed_out'];
|
959
|
$response = '';
|
960
|
|
961
|
while ($alive) {
|
962
|
// Calculate how much time is left of the original timeout value.
|
963
|
$timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
|
964
|
if ($timeout <= 0) {
|
965
|
$info['timed_out'] = TRUE;
|
966
|
break;
|
967
|
}
|
968
|
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
|
969
|
$chunk = fread($fp, 1024);
|
970
|
$response .= $chunk;
|
971
|
$info = stream_get_meta_data($fp);
|
972
|
$alive = !$info['eof'] && !$info['timed_out'] && $chunk;
|
973
|
}
|
974
|
fclose($fp);
|
975
|
|
976
|
if ($info['timed_out']) {
|
977
|
$result->code = HTTP_REQUEST_TIMEOUT;
|
978
|
$result->error = 'request timed out';
|
979
|
return $result;
|
980
|
}
|
981
|
// Parse response headers from the response body.
|
982
|
// Be tolerant of malformed HTTP responses that separate header and body with
|
983
|
// \n\n or \r\r instead of \r\n\r\n.
|
984
|
list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
|
985
|
$response = preg_split("/\r\n|\n|\r/", $response);
|
986
|
|
987
|
// Parse the response status line.
|
988
|
$response_status_array = _drupal_parse_response_status(trim(array_shift($response)));
|
989
|
$result->protocol = $response_status_array['http_version'];
|
990
|
$result->status_message = $response_status_array['reason_phrase'];
|
991
|
$code = $response_status_array['response_code'];
|
992
|
|
993
|
$result->headers = array();
|
994
|
|
995
|
// Parse the response headers.
|
996
|
while ($line = trim(array_shift($response))) {
|
997
|
list($name, $value) = explode(':', $line, 2);
|
998
|
$name = strtolower($name);
|
999
|
if (isset($result->headers[$name]) && $name == 'set-cookie') {
|
1000
|
// RFC 2109: the Set-Cookie response header comprises the token Set-
|
1001
|
// Cookie:, followed by a comma-separated list of one or more cookies.
|
1002
|
$result->headers[$name] .= ',' . trim($value);
|
1003
|
}
|
1004
|
else {
|
1005
|
$result->headers[$name] = trim($value);
|
1006
|
}
|
1007
|
}
|
1008
|
|
1009
|
$responses = array(
|
1010
|
100 => 'Continue',
|
1011
|
101 => 'Switching Protocols',
|
1012
|
200 => 'OK',
|
1013
|
201 => 'Created',
|
1014
|
202 => 'Accepted',
|
1015
|
203 => 'Non-Authoritative Information',
|
1016
|
204 => 'No Content',
|
1017
|
205 => 'Reset Content',
|
1018
|
206 => 'Partial Content',
|
1019
|
300 => 'Multiple Choices',
|
1020
|
301 => 'Moved Permanently',
|
1021
|
302 => 'Found',
|
1022
|
303 => 'See Other',
|
1023
|
304 => 'Not Modified',
|
1024
|
305 => 'Use Proxy',
|
1025
|
307 => 'Temporary Redirect',
|
1026
|
400 => 'Bad Request',
|
1027
|
401 => 'Unauthorized',
|
1028
|
402 => 'Payment Required',
|
1029
|
403 => 'Forbidden',
|
1030
|
404 => 'Not Found',
|
1031
|
405 => 'Method Not Allowed',
|
1032
|
406 => 'Not Acceptable',
|
1033
|
407 => 'Proxy Authentication Required',
|
1034
|
408 => 'Request Time-out',
|
1035
|
409 => 'Conflict',
|
1036
|
410 => 'Gone',
|
1037
|
411 => 'Length Required',
|
1038
|
412 => 'Precondition Failed',
|
1039
|
413 => 'Request Entity Too Large',
|
1040
|
414 => 'Request-URI Too Large',
|
1041
|
415 => 'Unsupported Media Type',
|
1042
|
416 => 'Requested range not satisfiable',
|
1043
|
417 => 'Expectation Failed',
|
1044
|
500 => 'Internal Server Error',
|
1045
|
501 => 'Not Implemented',
|
1046
|
502 => 'Bad Gateway',
|
1047
|
503 => 'Service Unavailable',
|
1048
|
504 => 'Gateway Time-out',
|
1049
|
505 => 'HTTP Version not supported',
|
1050
|
);
|
1051
|
// RFC 2616 states that all unknown HTTP codes must be treated the same as the
|
1052
|
// base code in their class.
|
1053
|
if (!isset($responses[$code])) {
|
1054
|
$code = floor($code / 100) * 100;
|
1055
|
}
|
1056
|
$result->code = $code;
|
1057
|
|
1058
|
switch ($code) {
|
1059
|
case 200: // OK
|
1060
|
case 304: // Not modified
|
1061
|
break;
|
1062
|
case 301: // Moved permanently
|
1063
|
case 302: // Moved temporarily
|
1064
|
case 307: // Moved temporarily
|
1065
|
$location = $result->headers['location'];
|
1066
|
$options['timeout'] -= timer_read(__FUNCTION__) / 1000;
|
1067
|
if ($options['timeout'] <= 0) {
|
1068
|
$result->code = HTTP_REQUEST_TIMEOUT;
|
1069
|
$result->error = 'request timed out';
|
1070
|
}
|
1071
|
elseif ($options['max_redirects']) {
|
1072
|
// Redirect to the new location.
|
1073
|
$options['max_redirects']--;
|
1074
|
$result = drupal_http_request($location, $options);
|
1075
|
$result->redirect_code = $code;
|
1076
|
}
|
1077
|
if (!isset($result->redirect_url)) {
|
1078
|
$result->redirect_url = $location;
|
1079
|
}
|
1080
|
break;
|
1081
|
default:
|
1082
|
$result->error = $result->status_message;
|
1083
|
}
|
1084
|
|
1085
|
return $result;
|
1086
|
}
|
1087
|
|
1088
|
/**
|
1089
|
* Splits an HTTP response status line into components.
|
1090
|
*
|
1091
|
* See the @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html status line definition @endlink
|
1092
|
* in RFC 2616.
|
1093
|
*
|
1094
|
* @param string $respone
|
1095
|
* The response status line, for example 'HTTP/1.1 500 Internal Server Error'.
|
1096
|
*
|
1097
|
* @return array
|
1098
|
* Keyed array containing the component parts. If the response is malformed,
|
1099
|
* all possible parts will be extracted. 'reason_phrase' could be empty.
|
1100
|
* Possible keys:
|
1101
|
* - 'http_version'
|
1102
|
* - 'response_code'
|
1103
|
* - 'reason_phrase'
|
1104
|
*/
|
1105
|
function _drupal_parse_response_status($response) {
|
1106
|
$response_array = explode(' ', trim($response), 3);
|
1107
|
// Set up empty values.
|
1108
|
$result = array(
|
1109
|
'reason_phrase' => '',
|
1110
|
);
|
1111
|
$result['http_version'] = $response_array[0];
|
1112
|
$result['response_code'] = $response_array[1];
|
1113
|
if (isset($response_array[2])) {
|
1114
|
$result['reason_phrase'] = $response_array[2];
|
1115
|
}
|
1116
|
return $result;
|
1117
|
}
|
1118
|
|
1119
|
/**
|
1120
|
* Helper function for determining hosts excluded from needing a proxy.
|
1121
|
*
|
1122
|
* @return
|
1123
|
* TRUE if a proxy should be used for this host.
|
1124
|
*/
|
1125
|
function _drupal_http_use_proxy($host) {
|
1126
|
$proxy_exceptions = variable_get('proxy_exceptions', array('localhost', '127.0.0.1'));
|
1127
|
return !in_array(strtolower($host), $proxy_exceptions, TRUE);
|
1128
|
}
|
1129
|
|
1130
|
/**
|
1131
|
* @} End of "HTTP handling".
|
1132
|
*/
|
1133
|
|
1134
|
/**
|
1135
|
* Strips slashes from a string or array of strings.
|
1136
|
*
|
1137
|
* Callback for array_walk() within fix_gpx_magic().
|
1138
|
*
|
1139
|
* @param $item
|
1140
|
* An individual string or array of strings from superglobals.
|
1141
|
*/
|
1142
|
function _fix_gpc_magic(&$item) {
|
1143
|
if (is_array($item)) {
|
1144
|
array_walk($item, '_fix_gpc_magic');
|
1145
|
}
|
1146
|
else {
|
1147
|
$item = stripslashes($item);
|
1148
|
}
|
1149
|
}
|
1150
|
|
1151
|
/**
|
1152
|
* Strips slashes from $_FILES items.
|
1153
|
*
|
1154
|
* Callback for array_walk() within fix_gpc_magic().
|
1155
|
*
|
1156
|
* The tmp_name key is skipped keys since PHP generates single backslashes for
|
1157
|
* file paths on Windows systems.
|
1158
|
*
|
1159
|
* @param $item
|
1160
|
* An item from $_FILES.
|
1161
|
* @param $key
|
1162
|
* The key for the item within $_FILES.
|
1163
|
*
|
1164
|
* @see http://php.net/manual/features.file-upload.php#42280
|
1165
|
*/
|
1166
|
function _fix_gpc_magic_files(&$item, $key) {
|
1167
|
if ($key != 'tmp_name') {
|
1168
|
if (is_array($item)) {
|
1169
|
array_walk($item, '_fix_gpc_magic_files');
|
1170
|
}
|
1171
|
else {
|
1172
|
$item = stripslashes($item);
|
1173
|
}
|
1174
|
}
|
1175
|
}
|
1176
|
|
1177
|
/**
|
1178
|
* Fixes double-escaping caused by "magic quotes" in some PHP installations.
|
1179
|
*
|
1180
|
* @see _fix_gpc_magic()
|
1181
|
* @see _fix_gpc_magic_files()
|
1182
|
*/
|
1183
|
function fix_gpc_magic() {
|
1184
|
static $fixed = FALSE;
|
1185
|
if (!$fixed && ini_get('magic_quotes_gpc')) {
|
1186
|
array_walk($_GET, '_fix_gpc_magic');
|
1187
|
array_walk($_POST, '_fix_gpc_magic');
|
1188
|
array_walk($_COOKIE, '_fix_gpc_magic');
|
1189
|
array_walk($_REQUEST, '_fix_gpc_magic');
|
1190
|
array_walk($_FILES, '_fix_gpc_magic_files');
|
1191
|
}
|
1192
|
$fixed = TRUE;
|
1193
|
}
|
1194
|
|
1195
|
/**
|
1196
|
* @defgroup validation Input validation
|
1197
|
* @{
|
1198
|
* Functions to validate user input.
|
1199
|
*/
|
1200
|
|
1201
|
/**
|
1202
|
* Verifies the syntax of the given e-mail address.
|
1203
|
*
|
1204
|
* This uses the
|
1205
|
* @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
|
1206
|
*
|
1207
|
* @param $mail
|
1208
|
* A string containing an e-mail address.
|
1209
|
*
|
1210
|
* @return
|
1211
|
* TRUE if the address is in a valid format.
|
1212
|
*/
|
1213
|
function valid_email_address($mail) {
|
1214
|
return (bool)filter_var($mail, FILTER_VALIDATE_EMAIL);
|
1215
|
}
|
1216
|
|
1217
|
/**
|
1218
|
* Verifies the syntax of the given URL.
|
1219
|
*
|
1220
|
* This function should only be used on actual URLs. It should not be used for
|
1221
|
* Drupal menu paths, which can contain arbitrary characters.
|
1222
|
* Valid values per RFC 3986.
|
1223
|
* @param $url
|
1224
|
* The URL to verify.
|
1225
|
* @param $absolute
|
1226
|
* Whether the URL is absolute (beginning with a scheme such as "http:").
|
1227
|
*
|
1228
|
* @return
|
1229
|
* TRUE if the URL is in a valid format.
|
1230
|
*/
|
1231
|
function valid_url($url, $absolute = FALSE) {
|
1232
|
if ($absolute) {
|
1233
|
return (bool)preg_match("
|
1234
|
/^ # Start at the beginning of the text
|
1235
|
(?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
|
1236
|
(?: # Userinfo (optional) which is typically
|
1237
|
(?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
|
1238
|
(?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
|
1239
|
)?
|
1240
|
(?:
|
1241
|
(?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
|
1242
|
|(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
|
1243
|
)
|
1244
|
(?::[0-9]+)? # Server port number (optional)
|
1245
|
(?:[\/|\?]
|
1246
|
(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
|
1247
|
*)?
|
1248
|
$/xi", $url);
|
1249
|
}
|
1250
|
else {
|
1251
|
return (bool)preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url);
|
1252
|
}
|
1253
|
}
|
1254
|
|
1255
|
/**
|
1256
|
* @} End of "defgroup validation".
|
1257
|
*/
|
1258
|
|
1259
|
/**
|
1260
|
* Registers an event for the current visitor to the flood control mechanism.
|
1261
|
*
|
1262
|
* @param $name
|
1263
|
* The name of an event.
|
1264
|
* @param $window
|
1265
|
* Optional number of seconds before this event expires. Defaults to 3600 (1
|
1266
|
* hour). Typically uses the same value as the flood_is_allowed() $window
|
1267
|
* parameter. Expired events are purged on cron run to prevent the flood table
|
1268
|
* from growing indefinitely.
|
1269
|
* @param $identifier
|
1270
|
* Optional identifier (defaults to the current user's IP address).
|
1271
|
*/
|
1272
|
function flood_register_event($name, $window = 3600, $identifier = NULL) {
|
1273
|
if (!isset($identifier)) {
|
1274
|
$identifier = ip_address();
|
1275
|
}
|
1276
|
db_insert('flood')
|
1277
|
->fields(array(
|
1278
|
'event' => $name,
|
1279
|
'identifier' => $identifier,
|
1280
|
'timestamp' => REQUEST_TIME,
|
1281
|
'expiration' => REQUEST_TIME + $window,
|
1282
|
))
|
1283
|
->execute();
|
1284
|
}
|
1285
|
|
1286
|
/**
|
1287
|
* Makes the flood control mechanism forget an event for the current visitor.
|
1288
|
*
|
1289
|
* @param $name
|
1290
|
* The name of an event.
|
1291
|
* @param $identifier
|
1292
|
* Optional identifier (defaults to the current user's IP address).
|
1293
|
*/
|
1294
|
function flood_clear_event($name, $identifier = NULL) {
|
1295
|
if (!isset($identifier)) {
|
1296
|
$identifier = ip_address();
|
1297
|
}
|
1298
|
db_delete('flood')
|
1299
|
->condition('event', $name)
|
1300
|
->condition('identifier', $identifier)
|
1301
|
->execute();
|
1302
|
}
|
1303
|
|
1304
|
/**
|
1305
|
* Checks whether a user is allowed to proceed with the specified event.
|
1306
|
*
|
1307
|
* Events can have thresholds saying that each user can only do that event
|
1308
|
* a certain number of times in a time window. This function verifies that the
|
1309
|
* current user has not exceeded this threshold.
|
1310
|
*
|
1311
|
* @param $name
|
1312
|
* The unique name of the event.
|
1313
|
* @param $threshold
|
1314
|
* The maximum number of times each user can do this event per time window.
|
1315
|
* @param $window
|
1316
|
* Number of seconds in the time window for this event (default is 3600
|
1317
|
* seconds, or 1 hour).
|
1318
|
* @param $identifier
|
1319
|
* Unique identifier of the current user. Defaults to their IP address.
|
1320
|
*
|
1321
|
* @return
|
1322
|
* TRUE if the user is allowed to proceed. FALSE if they have exceeded the
|
1323
|
* threshold and should not be allowed to proceed.
|
1324
|
*/
|
1325
|
function flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) {
|
1326
|
if (!isset($identifier)) {
|
1327
|
$identifier = ip_address();
|
1328
|
}
|
1329
|
$number = db_query("SELECT COUNT(*) FROM {flood} WHERE event = :event AND identifier = :identifier AND timestamp > :timestamp", array(
|
1330
|
':event' => $name,
|
1331
|
':identifier' => $identifier,
|
1332
|
':timestamp' => REQUEST_TIME - $window))
|
1333
|
->fetchField();
|
1334
|
return ($number < $threshold);
|
1335
|
}
|
1336
|
|
1337
|
/**
|
1338
|
* @defgroup sanitization Sanitization functions
|
1339
|
* @{
|
1340
|
* Functions to sanitize values.
|
1341
|
*
|
1342
|
* See http://drupal.org/writing-secure-code for information
|
1343
|
* on writing secure code.
|
1344
|
*/
|
1345
|
|
1346
|
/**
|
1347
|
* Strips dangerous protocols (e.g. 'javascript:') from a URI.
|
1348
|
*
|
1349
|
* This function must be called for all URIs within user-entered input prior
|
1350
|
* to being output to an HTML attribute value. It is often called as part of
|
1351
|
* check_url() or filter_xss(), but those functions return an HTML-encoded
|
1352
|
* string, so this function can be called independently when the output needs to
|
1353
|
* be a plain-text string for passing to t(), l(), drupal_attributes(), or
|
1354
|
* another function that will call check_plain() separately.
|
1355
|
*
|
1356
|
* @param $uri
|
1357
|
* A plain-text URI that might contain dangerous protocols.
|
1358
|
*
|
1359
|
* @return
|
1360
|
* A plain-text URI stripped of dangerous protocols. As with all plain-text
|
1361
|
* strings, this return value must not be output to an HTML page without
|
1362
|
* check_plain() being called on it. However, it can be passed to functions
|
1363
|
* expecting plain-text strings.
|
1364
|
*
|
1365
|
* @see check_url()
|
1366
|
*/
|
1367
|
function drupal_strip_dangerous_protocols($uri) {
|
1368
|
static $allowed_protocols;
|
1369
|
|
1370
|
if (!isset($allowed_protocols)) {
|
1371
|
$allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal')));
|
1372
|
}
|
1373
|
|
1374
|
// Iteratively remove any invalid protocol found.
|
1375
|
do {
|
1376
|
$before = $uri;
|
1377
|
$colonpos = strpos($uri, ':');
|
1378
|
if ($colonpos > 0) {
|
1379
|
// We found a colon, possibly a protocol. Verify.
|
1380
|
$protocol = substr($uri, 0, $colonpos);
|
1381
|
// If a colon is preceded by a slash, question mark or hash, it cannot
|
1382
|
// possibly be part of the URL scheme. This must be a relative URL, which
|
1383
|
// inherits the (safe) protocol of the base document.
|
1384
|
if (preg_match('![/?#]!', $protocol)) {
|
1385
|
break;
|
1386
|
}
|
1387
|
// Check if this is a disallowed protocol. Per RFC2616, section 3.2.3
|
1388
|
// (URI Comparison) scheme comparison must be case-insensitive.
|
1389
|
if (!isset($allowed_protocols[strtolower($protocol)])) {
|
1390
|
$uri = substr($uri, $colonpos + 1);
|
1391
|
}
|
1392
|
}
|
1393
|
} while ($before != $uri);
|
1394
|
|
1395
|
return $uri;
|
1396
|
}
|
1397
|
|
1398
|
/**
|
1399
|
* Strips dangerous protocols from a URI and encodes it for output to HTML.
|
1400
|
*
|
1401
|
* @param $uri
|
1402
|
* A plain-text URI that might contain dangerous protocols.
|
1403
|
*
|
1404
|
* @return
|
1405
|
* A URI stripped of dangerous protocols and encoded for output to an HTML
|
1406
|
* attribute value. Because it is already encoded, it should not be set as a
|
1407
|
* value within a $attributes array passed to drupal_attributes(), because
|
1408
|
* drupal_attributes() expects those values to be plain-text strings. To pass
|
1409
|
* a filtered URI to drupal_attributes(), call
|
1410
|
* drupal_strip_dangerous_protocols() instead.
|
1411
|
*
|
1412
|
* @see drupal_strip_dangerous_protocols()
|
1413
|
*/
|
1414
|
function check_url($uri) {
|
1415
|
return check_plain(drupal_strip_dangerous_protocols($uri));
|
1416
|
}
|
1417
|
|
1418
|
/**
|
1419
|
* Applies a very permissive XSS/HTML filter for admin-only use.
|
1420
|
*
|
1421
|
* Use only for fields where it is impractical to use the
|
1422
|
* whole filter system, but where some (mainly inline) mark-up
|
1423
|
* is desired (so check_plain() is not acceptable).
|
1424
|
*
|
1425
|
* Allows all tags that can be used inside an HTML body, save
|
1426
|
* for scripts and styles.
|
1427
|
*/
|
1428
|
function filter_xss_admin($string) {
|
1429
|
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'));
|
1430
|
}
|
1431
|
|
1432
|
/**
|
1433
|
* Filters HTML to prevent cross-site-scripting (XSS) vulnerabilities.
|
1434
|
*
|
1435
|
* Based on kses by Ulf Harnhammar, see http://sourceforge.net/projects/kses.
|
1436
|
* For examples of various XSS attacks, see: http://ha.ckers.org/xss.html.
|
1437
|
*
|
1438
|
* This code does four things:
|
1439
|
* - Removes characters and constructs that can trick browsers.
|
1440
|
* - Makes sure all HTML entities are well-formed.
|
1441
|
* - Makes sure all HTML tags and attributes are well-formed.
|
1442
|
* - Makes sure no HTML tags contain URLs with a disallowed protocol (e.g.
|
1443
|
* javascript:).
|
1444
|
*
|
1445
|
* @param $string
|
1446
|
* The string with raw HTML in it. It will be stripped of everything that can
|
1447
|
* cause an XSS attack.
|
1448
|
* @param $allowed_tags
|
1449
|
* An array of allowed tags.
|
1450
|
*
|
1451
|
* @return
|
1452
|
* An XSS safe version of $string, or an empty string if $string is not
|
1453
|
* valid UTF-8.
|
1454
|
*
|
1455
|
* @see drupal_validate_utf8()
|
1456
|
*/
|
1457
|
function filter_xss($string, $allowed_tags = array('a', 'em', 'strong', 'cite', 'blockquote', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd')) {
|
1458
|
// Only operate on valid UTF-8 strings. This is necessary to prevent cross
|
1459
|
// site scripting issues on Internet Explorer 6.
|
1460
|
if (!drupal_validate_utf8($string)) {
|
1461
|
return '';
|
1462
|
}
|
1463
|
// Store the text format.
|
1464
|
_filter_xss_split($allowed_tags, TRUE);
|
1465
|
// Remove NULL characters (ignored by some browsers).
|
1466
|
$string = str_replace(chr(0), '', $string);
|
1467
|
// Remove Netscape 4 JS entities.
|
1468
|
$string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
|
1469
|
|
1470
|
// Defuse all HTML entities.
|
1471
|
$string = str_replace('&', '&', $string);
|
1472
|
// Change back only well-formed entities in our whitelist:
|
1473
|
// Decimal numeric entities.
|
1474
|
$string = preg_replace('/&#([0-9]+;)/', '&#\1', $string);
|
1475
|
// Hexadecimal numeric entities.
|
1476
|
$string = preg_replace('/&#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\1', $string);
|
1477
|
// Named entities.
|
1478
|
$string = preg_replace('/&([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string);
|
1479
|
|
1480
|
return preg_replace_callback('%
|
1481
|
(
|
1482
|
<(?=[^a-zA-Z!/]) # a lone <
|
1483
|
| # or
|
1484
|
<!--.*?--> # a comment
|
1485
|
| # or
|
1486
|
<[^>]*(>|$) # a string that starts with a <, up until the > or the end of the string
|
1487
|
| # or
|
1488
|
> # just a >
|
1489
|
)%x', '_filter_xss_split', $string);
|
1490
|
}
|
1491
|
|
1492
|
/**
|
1493
|
* Processes an HTML tag.
|
1494
|
*
|
1495
|
* @param $m
|
1496
|
* An array with various meaning depending on the value of $store.
|
1497
|
* If $store is TRUE then the array contains the allowed tags.
|
1498
|
* If $store is FALSE then the array has one element, the HTML tag to process.
|
1499
|
* @param $store
|
1500
|
* Whether to store $m.
|
1501
|
*
|
1502
|
* @return
|
1503
|
* If the element isn't allowed, an empty string. Otherwise, the cleaned up
|
1504
|
* version of the HTML element.
|
1505
|
*/
|
1506
|
function _filter_xss_split($m, $store = FALSE) {
|
1507
|
static $allowed_html;
|
1508
|
|
1509
|
if ($store) {
|
1510
|
$allowed_html = array_flip($m);
|
1511
|
return;
|
1512
|
}
|
1513
|
|
1514
|
$string = $m[1];
|
1515
|
|
1516
|
if (substr($string, 0, 1) != '<') {
|
1517
|
// We matched a lone ">" character.
|
1518
|
return '>';
|
1519
|
}
|
1520
|
elseif (strlen($string) == 1) {
|
1521
|
// We matched a lone "<" character.
|
1522
|
return '<';
|
1523
|
}
|
1524
|
|
1525
|
if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
|
1526
|
// Seriously malformed.
|
1527
|
return '';
|
1528
|
}
|
1529
|
|
1530
|
$slash = trim($matches[1]);
|
1531
|
$elem = &$matches[2];
|
1532
|
$attrlist = &$matches[3];
|
1533
|
$comment = &$matches[4];
|
1534
|
|
1535
|
if ($comment) {
|
1536
|
$elem = '!--';
|
1537
|
}
|
1538
|
|
1539
|
if (!isset($allowed_html[strtolower($elem)])) {
|
1540
|
// Disallowed HTML element.
|
1541
|
return '';
|
1542
|
}
|
1543
|
|
1544
|
if ($comment) {
|
1545
|
return $comment;
|
1546
|
}
|
1547
|
|
1548
|
if ($slash != '') {
|
1549
|
return "</$elem>";
|
1550
|
}
|
1551
|
|
1552
|
// Is there a closing XHTML slash at the end of the attributes?
|
1553
|
$attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
|
1554
|
$xhtml_slash = $count ? ' /' : '';
|
1555
|
|
1556
|
// Clean up attributes.
|
1557
|
$attr2 = implode(' ', _filter_xss_attributes($attrlist));
|
1558
|
$attr2 = preg_replace('/[<>]/', '', $attr2);
|
1559
|
$attr2 = strlen($attr2) ? ' ' . $attr2 : '';
|
1560
|
|
1561
|
return "<$elem$attr2$xhtml_slash>";
|
1562
|
}
|
1563
|
|
1564
|
/**
|
1565
|
* Processes a string of HTML attributes.
|
1566
|
*
|
1567
|
* @return
|
1568
|
* Cleaned up version of the HTML attributes.
|
1569
|
*/
|
1570
|
function _filter_xss_attributes($attr) {
|
1571
|
$attrarr = array();
|
1572
|
$mode = 0;
|
1573
|
$attrname = '';
|
1574
|
|
1575
|
while (strlen($attr) != 0) {
|
1576
|
// Was the last operation successful?
|
1577
|
$working = 0;
|
1578
|
|
1579
|
switch ($mode) {
|
1580
|
case 0:
|
1581
|
// Attribute name, href for instance.
|
1582
|
if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
|
1583
|
$attrname = strtolower($match[1]);
|
1584
|
$skip = ($attrname == 'style' || substr($attrname, 0, 2) == 'on');
|
1585
|
$working = $mode = 1;
|
1586
|
$attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
|
1587
|
}
|
1588
|
break;
|
1589
|
|
1590
|
case 1:
|
1591
|
// Equals sign or valueless ("selected").
|
1592
|
if (preg_match('/^\s*=\s*/', $attr)) {
|
1593
|
$working = 1; $mode = 2;
|
1594
|
$attr = preg_replace('/^\s*=\s*/', '', $attr);
|
1595
|
break;
|
1596
|
}
|
1597
|
|
1598
|
if (preg_match('/^\s+/', $attr)) {
|
1599
|
$working = 1; $mode = 0;
|
1600
|
if (!$skip) {
|
1601
|
$attrarr[] = $attrname;
|
1602
|
}
|
1603
|
$attr = preg_replace('/^\s+/', '', $attr);
|
1604
|
}
|
1605
|
break;
|
1606
|
|
1607
|
case 2:
|
1608
|
// Attribute value, a URL after href= for instance.
|
1609
|
if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
|
1610
|
$thisval = filter_xss_bad_protocol($match[1]);
|
1611
|
|
1612
|
if (!$skip) {
|
1613
|
$attrarr[] = "$attrname=\"$thisval\"";
|
1614
|
}
|
1615
|
$working = 1;
|
1616
|
$mode = 0;
|
1617
|
$attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
|
1618
|
break;
|
1619
|
}
|
1620
|
|
1621
|
if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match)) {
|
1622
|
$thisval = filter_xss_bad_protocol($match[1]);
|
1623
|
|
1624
|
if (!$skip) {
|
1625
|
$attrarr[] = "$attrname='$thisval'";
|
1626
|
}
|
1627
|
$working = 1; $mode = 0;
|
1628
|
$attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
|
1629
|
break;
|
1630
|
}
|
1631
|
|
1632
|
if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match)) {
|
1633
|
$thisval = filter_xss_bad_protocol($match[1]);
|
1634
|
|
1635
|
if (!$skip) {
|
1636
|
$attrarr[] = "$attrname=\"$thisval\"";
|
1637
|
}
|
1638
|
$working = 1; $mode = 0;
|
1639
|
$attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
|
1640
|
}
|
1641
|
break;
|
1642
|
}
|
1643
|
|
1644
|
if ($working == 0) {
|
1645
|
// Not well formed; remove and try again.
|
1646
|
$attr = preg_replace('/
|
1647
|
^
|
1648
|
(
|
1649
|
"[^"]*("|$) # - a string that starts with a double quote, up until the next double quote or the end of the string
|
1650
|
| # or
|
1651
|
\'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
|
1652
|
| # or
|
1653
|
\S # - a non-whitespace character
|
1654
|
)* # any number of the above three
|
1655
|
\s* # any number of whitespaces
|
1656
|
/x', '', $attr);
|
1657
|
$mode = 0;
|
1658
|
}
|
1659
|
}
|
1660
|
|
1661
|
// The attribute list ends with a valueless attribute like "selected".
|
1662
|
if ($mode == 1 && !$skip) {
|
1663
|
$attrarr[] = $attrname;
|
1664
|
}
|
1665
|
return $attrarr;
|
1666
|
}
|
1667
|
|
1668
|
/**
|
1669
|
* Processes an HTML attribute value and strips dangerous protocols from URLs.
|
1670
|
*
|
1671
|
* @param $string
|
1672
|
* The string with the attribute value.
|
1673
|
* @param $decode
|
1674
|
* (deprecated) Whether to decode entities in the $string. Set to FALSE if the
|
1675
|
* $string is in plain text, TRUE otherwise. Defaults to TRUE. This parameter
|
1676
|
* is deprecated and will be removed in Drupal 8. To process a plain-text URI,
|
1677
|
* call drupal_strip_dangerous_protocols() or check_url() instead.
|
1678
|
*
|
1679
|
* @return
|
1680
|
* Cleaned up and HTML-escaped version of $string.
|
1681
|
*/
|
1682
|
function filter_xss_bad_protocol($string, $decode = TRUE) {
|
1683
|
// Get the plain text representation of the attribute value (i.e. its meaning).
|
1684
|
// @todo Remove the $decode parameter in Drupal 8, and always assume an HTML
|
1685
|
// string that needs decoding.
|
1686
|
if ($decode) {
|
1687
|
if (!function_exists('decode_entities')) {
|
1688
|
require_once DRUPAL_ROOT . '/includes/unicode.inc';
|
1689
|
}
|
1690
|
|
1691
|
$string = decode_entities($string);
|
1692
|
}
|
1693
|
return check_plain(drupal_strip_dangerous_protocols($string));
|
1694
|
}
|
1695
|
|
1696
|
/**
|
1697
|
* @} End of "defgroup sanitization".
|
1698
|
*/
|
1699
|
|
1700
|
/**
|
1701
|
* @defgroup format Formatting
|
1702
|
* @{
|
1703
|
* Functions to format numbers, strings, dates, etc.
|
1704
|
*/
|
1705
|
|
1706
|
/**
|
1707
|
* Formats an RSS channel.
|
1708
|
*
|
1709
|
* Arbitrary elements may be added using the $args associative array.
|
1710
|
*/
|
1711
|
function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
|
1712
|
global $language_content;
|
1713
|
$langcode = $langcode ? $langcode : $language_content->language;
|
1714
|
|
1715
|
$output = "<channel>\n";
|
1716
|
$output .= ' <title>' . check_plain($title) . "</title>\n";
|
1717
|
$output .= ' <link>' . check_url($link) . "</link>\n";
|
1718
|
|
1719
|
// The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
|
1720
|
// We strip all HTML tags, but need to prevent double encoding from properly
|
1721
|
// escaped source data (such as & becoming &amp;).
|
1722
|
$output .= ' <description>' . check_plain(decode_entities(strip_tags($description))) . "</description>\n";
|
1723
|
$output .= ' <language>' . check_plain($langcode) . "</language>\n";
|
1724
|
$output .= format_xml_elements($args);
|
1725
|
$output .= $items;
|
1726
|
$output .= "</channel>\n";
|
1727
|
|
1728
|
return $output;
|
1729
|
}
|
1730
|
|
1731
|
/**
|
1732
|
* Formats a single RSS item.
|
1733
|
*
|
1734
|
* Arbitrary elements may be added using the $args associative array.
|
1735
|
*/
|
1736
|
function format_rss_item($title, $link, $description, $args = array()) {
|
1737
|
$output = "<item>\n";
|
1738
|
$output .= ' <title>' . check_plain($title) . "</title>\n";
|
1739
|
$output .= ' <link>' . check_url($link) . "</link>\n";
|
1740
|
$output .= ' <description>' . check_plain($description) . "</description>\n";
|
1741
|
$output .= format_xml_elements($args);
|
1742
|
$output .= "</item>\n";
|
1743
|
|
1744
|
return $output;
|
1745
|
}
|
1746
|
|
1747
|
/**
|
1748
|
* Formats XML elements.
|
1749
|
*
|
1750
|
* @param $array
|
1751
|
* An array where each item represents an element and is either a:
|
1752
|
* - (key => value) pair (<key>value</key>)
|
1753
|
* - Associative array with fields:
|
1754
|
* - 'key': element name
|
1755
|
* - 'value': element contents
|
1756
|
* - 'attributes': associative array of element attributes
|
1757
|
*
|
1758
|
* In both cases, 'value' can be a simple string, or it can be another array
|
1759
|
* with the same format as $array itself for nesting.
|
1760
|
*/
|
1761
|
function format_xml_elements($array) {
|
1762
|
$output = '';
|
1763
|
foreach ($array as $key => $value) {
|
1764
|
if (is_numeric($key)) {
|
1765
|
if ($value['key']) {
|
1766
|
$output .= ' <' . $value['key'];
|
1767
|
if (isset($value['attributes']) && is_array($value['attributes'])) {
|
1768
|
$output .= drupal_attributes($value['attributes']);
|
1769
|
}
|
1770
|
|
1771
|
if (isset($value['value']) && $value['value'] != '') {
|
1772
|
$output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) . '</' . $value['key'] . ">\n";
|
1773
|
}
|
1774
|
else {
|
1775
|
$output .= " />\n";
|
1776
|
}
|
1777
|
}
|
1778
|
}
|
1779
|
else {
|
1780
|
$output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</$key>\n";
|
1781
|
}
|
1782
|
}
|
1783
|
return $output;
|
1784
|
}
|
1785
|
|
1786
|
/**
|
1787
|
* Formats a string containing a count of items.
|
1788
|
*
|
1789
|
* This function ensures that the string is pluralized correctly. Since t() is
|
1790
|
* called by this function, make sure not to pass already-localized strings to
|
1791
|
* it.
|
1792
|
*
|
1793
|
* For example:
|
1794
|
* @code
|
1795
|
* $output = format_plural($node->comment_count, '1 comment', '@count comments');
|
1796
|
* @endcode
|
1797
|
*
|
1798
|
* Example with additional replacements:
|
1799
|
* @code
|
1800
|
* $output = format_plural($update_count,
|
1801
|
* 'Changed the content type of 1 post from %old-type to %new-type.',
|
1802
|
* 'Changed the content type of @count posts from %old-type to %new-type.',
|
1803
|
* array('%old-type' => $info->old_type, '%new-type' => $info->new_type));
|
1804
|
* @endcode
|
1805
|
*
|
1806
|
* @param $count
|
1807
|
* The item count to display.
|
1808
|
* @param $singular
|
1809
|
* The string for the singular case. Make sure it is clear this is singular,
|
1810
|
* to ease translation (e.g. use "1 new comment" instead of "1 new"). Do not
|
1811
|
* use @count in the singular string.
|
1812
|
* @param $plural
|
1813
|
* The string for the plural case. Make sure it is clear this is plural, to
|
1814
|
* ease translation. Use @count in place of the item count, as in
|
1815
|
* "@count new comments".
|
1816
|
* @param $args
|
1817
|
* An associative array of replacements to make after translation. Instances
|
1818
|
* of any key in this array are replaced with the corresponding value.
|
1819
|
* Based on the first character of the key, the value is escaped and/or
|
1820
|
* themed. See format_string(). Note that you do not need to include @count
|
1821
|
* in this array; this replacement is done automatically for the plural case.
|
1822
|
* @param $options
|
1823
|
* An associative array of additional options. See t() for allowed keys.
|
1824
|
*
|
1825
|
* @return
|
1826
|
* A translated string.
|
1827
|
*
|
1828
|
* @see t()
|
1829
|
* @see format_string()
|
1830
|
*/
|
1831
|
function format_plural($count, $singular, $plural, array $args = array(), array $options = array()) {
|
1832
|
$args['@count'] = $count;
|
1833
|
if ($count == 1) {
|
1834
|
return t($singular, $args, $options);
|
1835
|
}
|
1836
|
|
1837
|
// Get the plural index through the gettext formula.
|
1838
|
$index = (function_exists('locale_get_plural')) ? locale_get_plural($count, isset($options['langcode']) ? $options['langcode'] : NULL) : -1;
|
1839
|
// If the index cannot be computed, use the plural as a fallback (which
|
1840
|
// allows for most flexiblity with the replaceable @count value).
|
1841
|
if ($index < 0) {
|
1842
|
return t($plural, $args, $options);
|
1843
|
}
|
1844
|
else {
|
1845
|
switch ($index) {
|
1846
|
case "0":
|
1847
|
return t($singular, $args, $options);
|
1848
|
case "1":
|
1849
|
return t($plural, $args, $options);
|
1850
|
default:
|
1851
|
unset($args['@count']);
|
1852
|
$args['@count[' . $index . ']'] = $count;
|
1853
|
return t(strtr($plural, array('@count' => '@count[' . $index . ']')), $args, $options);
|
1854
|
}
|
1855
|
}
|
1856
|
}
|
1857
|
|
1858
|
/**
|
1859
|
* Parses a given byte count.
|
1860
|
*
|
1861
|
* @param $size
|
1862
|
* A size expressed as a number of bytes with optional SI or IEC binary unit
|
1863
|
* prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).
|
1864
|
*
|
1865
|
* @return
|
1866
|
* An integer representation of the size in bytes.
|
1867
|
*/
|
1868
|
function parse_size($size) {
|
1869
|
$unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size.
|
1870
|
$size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size.
|
1871
|
if ($unit) {
|
1872
|
// Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by.
|
1873
|
return round($size * pow(DRUPAL_KILOBYTE, stripos('bkmgtpezy', $unit[0])));
|
1874
|
}
|
1875
|
else {
|
1876
|
return round($size);
|
1877
|
}
|
1878
|
}
|
1879
|
|
1880
|
/**
|
1881
|
* Generates a string representation for the given byte count.
|
1882
|
*
|
1883
|
* @param $size
|
1884
|
* A size in bytes.
|
1885
|
* @param $langcode
|
1886
|
* Optional language code to translate to a language other than what is used
|
1887
|
* to display the page.
|
1888
|
*
|
1889
|
* @return
|
1890
|
* A translated string representation of the size.
|
1891
|
*/
|
1892
|
function format_size($size, $langcode = NULL) {
|
1893
|
if ($size < DRUPAL_KILOBYTE) {
|
1894
|
return format_plural($size, '1 byte', '@count bytes', array(), array('langcode' => $langcode));
|
1895
|
}
|
1896
|
else {
|
1897
|
$size = $size / DRUPAL_KILOBYTE; // Convert bytes to kilobytes.
|
1898
|
$units = array(
|
1899
|
t('@size KB', array(), array('langcode' => $langcode)),
|
1900
|
t('@size MB', array(), array('langcode' => $langcode)),
|
1901
|
t('@size GB', array(), array('langcode' => $langcode)),
|
1902
|
t('@size TB', array(), array('langcode' => $langcode)),
|
1903
|
t('@size PB', array(), array('langcode' => $langcode)),
|
1904
|
t('@size EB', array(), array('langcode' => $langcode)),
|
1905
|
t('@size ZB', array(), array('langcode' => $langcode)),
|
1906
|
t('@size YB', array(), array('langcode' => $langcode)),
|
1907
|
);
|
1908
|
foreach ($units as $unit) {
|
1909
|
if (round($size, 2) >= DRUPAL_KILOBYTE) {
|
1910
|
$size = $size / DRUPAL_KILOBYTE;
|
1911
|
}
|
1912
|
else {
|
1913
|
break;
|
1914
|
}
|
1915
|
}
|
1916
|
return str_replace('@size', round($size, 2), $unit);
|
1917
|
}
|
1918
|
}
|
1919
|
|
1920
|
/**
|
1921
|
* Formats a time interval with the requested granularity.
|
1922
|
*
|
1923
|
* @param $interval
|
1924
|
* The length of the interval in seconds.
|
1925
|
* @param $granularity
|
1926
|
* How many different units to display in the string.
|
1927
|
* @param $langcode
|
1928
|
* Optional language code to translate to a language other than
|
1929
|
* what is used to display the page.
|
1930
|
*
|
1931
|
* @return
|
1932
|
* A translated string representation of the interval.
|
1933
|
*/
|
1934
|
function format_interval($interval, $granularity = 2, $langcode = NULL) {
|
1935
|
$units = array(
|
1936
|
'1 year|@count years' => 31536000,
|
1937
|
'1 month|@count months' => 2592000,
|
1938
|
'1 week|@count weeks' => 604800,
|
1939
|
'1 day|@count days' => 86400,
|
1940
|
'1 hour|@count hours' => 3600,
|
1941
|
'1 min|@count min' => 60,
|
1942
|
'1 sec|@count sec' => 1
|
1943
|
);
|
1944
|
$output = '';
|
1945
|
foreach ($units as $key => $value) {
|
1946
|
$key = explode('|', $key);
|
1947
|
if ($interval >= $value) {
|
1948
|
$output .= ($output ? ' ' : '') . format_plural(floor($interval / $value), $key[0], $key[1], array(), array('langcode' => $langcode));
|
1949
|
$interval %= $value;
|
1950
|
$granularity--;
|
1951
|
}
|
1952
|
|
1953
|
if ($granularity == 0) {
|
1954
|
break;
|
1955
|
}
|
1956
|
}
|
1957
|
return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
|
1958
|
}
|
1959
|
|
1960
|
/**
|
1961
|
* Formats a date, using a date type or a custom date format string.
|
1962
|
*
|
1963
|
* @param $timestamp
|
1964
|
* A UNIX timestamp to format.
|
1965
|
* @param $type
|
1966
|
* (optional) The format to use, one of:
|
1967
|
* - 'short', 'medium', or 'long' (the corresponding built-in date formats).
|
1968
|
* - The name of a date type defined by a module in hook_date_format_types(),
|
1969
|
* if it's been assigned a format.
|
1970
|
* - The machine name of an administrator-defined date format.
|
1971
|
* - 'custom', to use $format.
|
1972
|
* Defaults to 'medium'.
|
1973
|
* @param $format
|
1974
|
* (optional) If $type is 'custom', a PHP date format string suitable for
|
1975
|
* input to date(). Use a backslash to escape ordinary text, so it does not
|
1976
|
* get interpreted as date format characters.
|
1977
|
* @param $timezone
|
1978
|
* (optional) Time zone identifier, as described at
|
1979
|
* http://php.net/manual/timezones.php Defaults to the time zone used to
|
1980
|
* display the page.
|
1981
|
* @param $langcode
|
1982
|
* (optional) Language code to translate to. Defaults to the language used to
|
1983
|
* display the page.
|
1984
|
*
|
1985
|
* @return
|
1986
|
* A translated date string in the requested format.
|
1987
|
*/
|
1988
|
function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
|
1989
|
// Use the advanced drupal_static() pattern, since this is called very often.
|
1990
|
static $drupal_static_fast;
|
1991
|
if (!isset($drupal_static_fast)) {
|
1992
|
$drupal_static_fast['timezones'] = &drupal_static(__FUNCTION__);
|
1993
|
}
|
1994
|
$timezones = &$drupal_static_fast['timezones'];
|
1995
|
|
1996
|
if (!isset($timezone)) {
|
1997
|
$timezone = date_default_timezone_get();
|
1998
|
}
|
1999
|
// Store DateTimeZone objects in an array rather than repeatedly
|
2000
|
// constructing identical objects over the life of a request.
|
2001
|
if (!isset($timezones[$timezone])) {
|
2002
|
$timezones[$timezone] = timezone_open($timezone);
|
2003
|
}
|
2004
|
|
2005
|
// Use the default langcode if none is set.
|
2006
|
global $language;
|
2007
|
if (empty($langcode)) {
|
2008
|
$langcode = isset($language->language) ? $language->language : 'en';
|
2009
|
}
|
2010
|
|
2011
|
switch ($type) {
|
2012
|
case 'short':
|
2013
|
$format = variable_get('date_format_short', 'm/d/Y - H:i');
|
2014
|
break;
|
2015
|
|
2016
|
case 'long':
|
2017
|
$format = variable_get('date_format_long', 'l, F j, Y - H:i');
|
2018
|
break;
|
2019
|
|
2020
|
case 'custom':
|
2021
|
// No change to format.
|
2022
|
break;
|
2023
|
|
2024
|
case 'medium':
|
2025
|
default:
|
2026
|
// Retrieve the format of the custom $type passed.
|
2027
|
if ($type != 'medium') {
|
2028
|
$format = variable_get('date_format_' . $type, '');
|
2029
|
}
|
2030
|
// Fall back to 'medium'.
|
2031
|
if ($format === '') {
|
2032
|
$format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
|
2033
|
}
|
2034
|
break;
|
2035
|
}
|
2036
|
|
2037
|
// Create a DateTime object from the timestamp.
|
2038
|
$date_time = date_create('@' . $timestamp);
|
2039
|
// Set the time zone for the DateTime object.
|
2040
|
date_timezone_set($date_time, $timezones[$timezone]);
|
2041
|
|
2042
|
// Encode markers that should be translated. 'A' becomes '\xEF\AA\xFF'.
|
2043
|
// xEF and xFF are invalid UTF-8 sequences, and we assume they are not in the
|
2044
|
// input string.
|
2045
|
// Paired backslashes are isolated to prevent errors in read-ahead evaluation.
|
2046
|
// The read-ahead expression ensures that A matches, but not \A.
|
2047
|
$format = preg_replace(array('/\\\\\\\\/', '/(?<!\\\\)([AaeDlMTF])/'), array("\xEF\\\\\\\\\xFF", "\xEF\\\\\$1\$1\xFF"), $format);
|
2048
|
|
2049
|
// Call date_format().
|
2050
|
$format = date_format($date_time, $format);
|
2051
|
|
2052
|
// Pass the langcode to _format_date_callback().
|
2053
|
_format_date_callback(NULL, $langcode);
|
2054
|
|
2055
|
// Translate the marked sequences.
|
2056
|
return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);
|
2057
|
}
|
2058
|
|
2059
|
/**
|
2060
|
* Returns an ISO8601 formatted date based on the given date.
|
2061
|
*
|
2062
|
* Callback for use within hook_rdf_mapping() implementations.
|
2063
|
*
|
2064
|
* @param $date
|
2065
|
* A UNIX timestamp.
|
2066
|
*
|
2067
|
* @return string
|
2068
|
* An ISO8601 formatted date.
|
2069
|
*/
|
2070
|
function date_iso8601($date) {
|
2071
|
// The DATE_ISO8601 constant cannot be used here because it does not match
|
2072
|
// date('c') and produces invalid RDF markup.
|
2073
|
return date('c', $date);
|
2074
|
}
|
2075
|
|
2076
|
/**
|
2077
|
* Translates a formatted date string.
|
2078
|
*
|
2079
|
* Callback for preg_replace_callback() within format_date().
|
2080
|
*/
|
2081
|
function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
|
2082
|
// We cache translations to avoid redundant and rather costly calls to t().
|
2083
|
static $cache, $langcode;
|
2084
|
|
2085
|
if (!isset($matches)) {
|
2086
|
$langcode = $new_langcode;
|
2087
|
return;
|
2088
|
}
|
2089
|
|
2090
|
$code = $matches[1];
|
2091
|
$string = $matches[2];
|
2092
|
|
2093
|
if (!isset($cache[$langcode][$code][$string])) {
|
2094
|
$options = array(
|
2095
|
'langcode' => $langcode,
|
2096
|
);
|
2097
|
|
2098
|
if ($code == 'F') {
|
2099
|
$options['context'] = 'Long month name';
|
2100
|
}
|
2101
|
|
2102
|
if ($code == '') {
|
2103
|
$cache[$langcode][$code][$string] = $string;
|
2104
|
}
|
2105
|
else {
|
2106
|
$cache[$langcode][$code][$string] = t($string, array(), $options);
|
2107
|
}
|
2108
|
}
|
2109
|
return $cache[$langcode][$code][$string];
|
2110
|
}
|
2111
|
|
2112
|
/**
|
2113
|
* Format a username.
|
2114
|
*
|
2115
|
* This is also the label callback implementation of
|
2116
|
* callback_entity_info_label() for user_entity_info().
|
2117
|
*
|
2118
|
* By default, the passed-in object's 'name' property is used if it exists, or
|
2119
|
* else, the site-defined value for the 'anonymous' variable. However, a module
|
2120
|
* may override this by implementing hook_username_alter(&$name, $account).
|
2121
|
*
|
2122
|
* @see hook_username_alter()
|
2123
|
*
|
2124
|
* @param $account
|
2125
|
* The account object for the user whose name is to be formatted.
|
2126
|
*
|
2127
|
* @return
|
2128
|
* An unsanitized string with the username to display. The code receiving
|
2129
|
* this result must ensure that check_plain() is called on it before it is
|
2130
|
* printed to the page.
|
2131
|
*/
|
2132
|
function format_username($account) {
|
2133
|
$name = !empty($account->name) ? $account->name : variable_get('anonymous', t('Anonymous'));
|
2134
|
drupal_alter('username', $name, $account);
|
2135
|
return $name;
|
2136
|
}
|
2137
|
|
2138
|
/**
|
2139
|
* @} End of "defgroup format".
|
2140
|
*/
|
2141
|
|
2142
|
/**
|
2143
|
* Generates an internal or external URL.
|
2144
|
*
|
2145
|
* When creating links in modules, consider whether l() could be a better
|
2146
|
* alternative than url().
|
2147
|
*
|
2148
|
* @param $path
|
2149
|
* (optional) The internal path or external URL being linked to, such as
|
2150
|
* "node/34" or "http://example.com/foo". The default value is equivalent to
|
2151
|
* passing in '<front>'. A few notes:
|
2152
|
* - If you provide a full URL, it will be considered an external URL.
|
2153
|
* - If you provide only the path (e.g. "node/34"), it will be
|
2154
|
* considered an internal link. In this case, it should be a system URL,
|
2155
|
* and it will be replaced with the alias, if one exists. Additional query
|
2156
|
* arguments for internal paths must be supplied in $options['query'], not
|
2157
|
* included in $path.
|
2158
|
* - If you provide an internal path and $options['alias'] is set to TRUE, the
|
2159
|
* path is assumed already to be the correct path alias, and the alias is
|
2160
|
* not looked up.
|
2161
|
* - The special string '<front>' generates a link to the site's base URL.
|
2162
|
* - If your external URL contains a query (e.g. http://example.com/foo?a=b),
|
2163
|
* then you can either URL encode the query keys and values yourself and
|
2164
|
* include them in $path, or use $options['query'] to let this function
|
2165
|
* URL encode them.
|
2166
|
* @param $options
|
2167
|
* (optional) An associative array of additional options, with the following
|
2168
|
* elements:
|
2169
|
* - 'query': An array of query key/value-pairs (without any URL-encoding) to
|
2170
|
* append to the URL.
|
2171
|
* - 'fragment': A fragment identifier (named anchor) to append to the URL.
|
2172
|
* Do not include the leading '#' character.
|
2173
|
* - 'absolute': Defaults to FALSE. Whether to force the output to be an
|
2174
|
* absolute link (beginning with http:). Useful for links that will be
|
2175
|
* displayed outside the site, such as in an RSS feed.
|
2176
|
* - 'alias': Defaults to FALSE. Whether the given path is a URL alias
|
2177
|
* already.
|
2178
|
* - 'external': Whether the given path is an external URL.
|
2179
|
* - 'language': An optional language object. If the path being linked to is
|
2180
|
* internal to the site, $options['language'] is used to look up the alias
|
2181
|
* for the URL. If $options['language'] is omitted, the global $language_url
|
2182
|
* will be used.
|
2183
|
* - 'https': Whether this URL should point to a secure location. If not
|
2184
|
* defined, the current scheme is used, so the user stays on HTTP or HTTPS
|
2185
|
* respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but HTTPS can
|
2186
|
* only be enforced when the variable 'https' is set to TRUE.
|
2187
|
* - 'base_url': Only used internally, to modify the base URL when a language
|
2188
|
* dependent URL requires so.
|
2189
|
* - 'prefix': Only used internally, to modify the path when a language
|
2190
|
* dependent URL requires so.
|
2191
|
* - 'script': The script filename in Drupal's root directory to use when
|
2192
|
* clean URLs are disabled, such as 'index.php'. Defaults to an empty
|
2193
|
* string, as most modern web servers automatically find 'index.php'. If
|
2194
|
* clean URLs are disabled, the value of $path is appended as query
|
2195
|
* parameter 'q' to $options['script'] in the returned URL. When deploying
|
2196
|
* Drupal on a web server that cannot be configured to automatically find
|
2197
|
* index.php, then hook_url_outbound_alter() can be implemented to force
|
2198
|
* this value to 'index.php'.
|
2199
|
* - 'entity_type': The entity type of the object that called url(). Only
|
2200
|
* set if url() is invoked by entity_uri().
|
2201
|
* - 'entity': The entity object (such as a node) for which the URL is being
|
2202
|
* generated. Only set if url() is invoked by entity_uri().
|
2203
|
*
|
2204
|
* @return
|
2205
|
* A string containing a URL to the given path.
|
2206
|
*/
|
2207
|
function url($path = NULL, array $options = array()) {
|
2208
|
// Merge in defaults.
|
2209
|
$options += array(
|
2210
|
'fragment' => '',
|
2211
|
'query' => array(),
|
2212
|
'absolute' => FALSE,
|
2213
|
'alias' => FALSE,
|
2214
|
'prefix' => ''
|
2215
|
);
|
2216
|
|
2217
|
// A duplicate of the code from url_is_external() to avoid needing another
|
2218
|
// function call, since performance inside url() is critical.
|
2219
|
if (!isset($options['external'])) {
|
2220
|
// Return an external link if $path contains an allowed absolute URL. Avoid
|
2221
|
// calling drupal_strip_dangerous_protocols() if there is any slash (/),
|
2222
|
// hash (#) or question_mark (?) before the colon (:) occurrence - if any -
|
2223
|
// as this would clearly mean it is not a URL. If the path starts with 2
|
2224
|
// slashes then it is always considered an external URL without an explicit
|
2225
|
// protocol part.
|
2226
|
$colonpos = strpos($path, ':');
|
2227
|
$options['external'] = (strpos($path, '//') === 0)
|
2228
|
|| ($colonpos !== FALSE
|
2229
|
&& !preg_match('![/?#]!', substr($path, 0, $colonpos))
|
2230
|
&& drupal_strip_dangerous_protocols($path) == $path);
|
2231
|
}
|
2232
|
|
2233
|
// Preserve the original path before altering or aliasing.
|
2234
|
$original_path = $path;
|
2235
|
|
2236
|
// Allow other modules to alter the outbound URL and options.
|
2237
|
drupal_alter('url_outbound', $path, $options, $original_path);
|
2238
|
|
2239
|
if (isset($options['fragment']) && $options['fragment'] !== '') {
|
2240
|
$options['fragment'] = '#' . $options['fragment'];
|
2241
|
}
|
2242
|
|
2243
|
if ($options['external']) {
|
2244
|
// Split off the fragment.
|
2245
|
if (strpos($path, '#') !== FALSE) {
|
2246
|
list($path, $old_fragment) = explode('#', $path, 2);
|
2247
|
// If $options contains no fragment, take it over from the path.
|
2248
|
if (isset($old_fragment) && !$options['fragment']) {
|
2249
|
$options['fragment'] = '#' . $old_fragment;
|
2250
|
}
|
2251
|
}
|
2252
|
// Append the query.
|
2253
|
if ($options['query']) {
|
2254
|
$path .= (strpos($path, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($options['query']);
|
2255
|
}
|
2256
|
if (isset($options['https']) && variable_get('https', FALSE)) {
|
2257
|
if ($options['https'] === TRUE) {
|
2258
|
$path = str_replace('http://', 'https://', $path);
|
2259
|
}
|
2260
|
elseif ($options['https'] === FALSE) {
|
2261
|
$path = str_replace('https://', 'http://', $path);
|
2262
|
}
|
2263
|
}
|
2264
|
// Reassemble.
|
2265
|
return $path . $options['fragment'];
|
2266
|
}
|
2267
|
|
2268
|
// Strip leading slashes from internal paths to prevent them becoming external
|
2269
|
// URLs without protocol. /example.com should not be turned into
|
2270
|
// //example.com.
|
2271
|
$path = ltrim($path, '/');
|
2272
|
|
2273
|
global $base_url, $base_secure_url, $base_insecure_url;
|
2274
|
|
2275
|
// The base_url might be rewritten from the language rewrite in domain mode.
|
2276
|
if (!isset($options['base_url'])) {
|
2277
|
if (isset($options['https']) && variable_get('https', FALSE)) {
|
2278
|
if ($options['https'] === TRUE) {
|
2279
|
$options['base_url'] = $base_secure_url;
|
2280
|
$options['absolute'] = TRUE;
|
2281
|
}
|
2282
|
elseif ($options['https'] === FALSE) {
|
2283
|
$options['base_url'] = $base_insecure_url;
|
2284
|
$options['absolute'] = TRUE;
|
2285
|
}
|
2286
|
}
|
2287
|
else {
|
2288
|
$options['base_url'] = $base_url;
|
2289
|
}
|
2290
|
}
|
2291
|
|
2292
|
// The special path '<front>' links to the default front page.
|
2293
|
if ($path == '<front>') {
|
2294
|
$path = '';
|
2295
|
}
|
2296
|
elseif (!empty($path) && !$options['alias']) {
|
2297
|
$language = isset($options['language']) && isset($options['language']->language) ? $options['language']->language : '';
|
2298
|
$alias = drupal_get_path_alias($original_path, $language);
|
2299
|
if ($alias != $original_path) {
|
2300
|
$path = $alias;
|
2301
|
}
|
2302
|
}
|
2303
|
|
2304
|
$base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
|
2305
|
$prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
|
2306
|
|
2307
|
// With Clean URLs.
|
2308
|
if (!empty($GLOBALS['conf']['clean_url'])) {
|
2309
|
$path = drupal_encode_path($prefix . $path);
|
2310
|
if ($options['query']) {
|
2311
|
return $base . $path . '?' . drupal_http_build_query($options['query']) . $options['fragment'];
|
2312
|
}
|
2313
|
else {
|
2314
|
return $base . $path . $options['fragment'];
|
2315
|
}
|
2316
|
}
|
2317
|
// Without Clean URLs.
|
2318
|
else {
|
2319
|
$path = $prefix . $path;
|
2320
|
$query = array();
|
2321
|
if (!empty($path)) {
|
2322
|
$query['q'] = $path;
|
2323
|
}
|
2324
|
if ($options['query']) {
|
2325
|
// We do not use array_merge() here to prevent overriding $path via query
|
2326
|
// parameters.
|
2327
|
$query += $options['query'];
|
2328
|
}
|
2329
|
$query = $query ? ('?' . drupal_http_build_query($query)) : '';
|
2330
|
$script = isset($options['script']) ? $options['script'] : '';
|
2331
|
return $base . $script . $query . $options['fragment'];
|
2332
|
}
|
2333
|
}
|
2334
|
|
2335
|
/**
|
2336
|
* Returns TRUE if a path is external to Drupal (e.g. http://example.com).
|
2337
|
*
|
2338
|
* If a path cannot be assessed by Drupal's menu handler, then we must
|
2339
|
* treat it as potentially insecure.
|
2340
|
*
|
2341
|
* @param $path
|
2342
|
* The internal path or external URL being linked to, such as "node/34" or
|
2343
|
* "http://example.com/foo".
|
2344
|
*
|
2345
|
* @return
|
2346
|
* Boolean TRUE or FALSE, where TRUE indicates an external path.
|
2347
|
*/
|
2348
|
function url_is_external($path) {
|
2349
|
$colonpos = strpos($path, ':');
|
2350
|
// Avoid calling drupal_strip_dangerous_protocols() if there is any slash (/),
|
2351
|
// hash (#) or question_mark (?) before the colon (:) occurrence - if any - as
|
2352
|
// this would clearly mean it is not a URL. If the path starts with 2 slashes
|
2353
|
// then it is always considered an external URL without an explicit protocol
|
2354
|
// part.
|
2355
|
return (strpos($path, '//') === 0)
|
2356
|
|| ($colonpos !== FALSE
|
2357
|
&& !preg_match('![/?#]!', substr($path, 0, $colonpos))
|
2358
|
&& drupal_strip_dangerous_protocols($path) == $path);
|
2359
|
}
|
2360
|
|
2361
|
/**
|
2362
|
* Formats an attribute string for an HTTP header.
|
2363
|
*
|
2364
|
* @param $attributes
|
2365
|
* An associative array of attributes such as 'rel'.
|
2366
|
*
|
2367
|
* @return
|
2368
|
* A ; separated string ready for insertion in a HTTP header. No escaping is
|
2369
|
* performed for HTML entities, so this string is not safe to be printed.
|
2370
|
*
|
2371
|
* @see drupal_add_http_header()
|
2372
|
*/
|
2373
|
function drupal_http_header_attributes(array $attributes = array()) {
|
2374
|
foreach ($attributes as $attribute => &$data) {
|
2375
|
if (is_array($data)) {
|
2376
|
$data = implode(' ', $data);
|
2377
|
}
|
2378
|
$data = $attribute . '="' . $data . '"';
|
2379
|
}
|
2380
|
return $attributes ? ' ' . implode('; ', $attributes) : '';
|
2381
|
}
|
2382
|
|
2383
|
/**
|
2384
|
* Converts an associative array to an XML/HTML tag attribute string.
|
2385
|
*
|
2386
|
* Each array key and its value will be formatted into an attribute string.
|
2387
|
* If a value is itself an array, then its elements are concatenated to a single
|
2388
|
* space-delimited string (for example, a class attribute with multiple values).
|
2389
|
*
|
2390
|
* Attribute values are sanitized by running them through check_plain().
|
2391
|
* Attribute names are not automatically sanitized. When using user-supplied
|
2392
|
* attribute names, it is strongly recommended to allow only white-listed names,
|
2393
|
* since certain attributes carry security risks and can be abused.
|
2394
|
*
|
2395
|
* Examples of security aspects when using drupal_attributes:
|
2396
|
* @code
|
2397
|
* // By running the value in the following statement through check_plain,
|
2398
|
* // the malicious script is neutralized.
|
2399
|
* drupal_attributes(array('title' => t('<script>steal_cookie();</script>')));
|
2400
|
*
|
2401
|
* // The statement below demonstrates dangerous use of drupal_attributes, and
|
2402
|
* // will return an onmouseout attribute with JavaScript code that, when used
|
2403
|
* // as attribute in a tag, will cause users to be redirected to another site.
|
2404
|
* //
|
2405
|
* // In this case, the 'onmouseout' attribute should not be whitelisted --
|
2406
|
* // you don't want users to have the ability to add this attribute or others
|
2407
|
* // that take JavaScript commands.
|
2408
|
* drupal_attributes(array('onmouseout' => 'window.location="http://malicious.com/";')));
|
2409
|
* @endcode
|
2410
|
*
|
2411
|
* @param $attributes
|
2412
|
* An associative array of key-value pairs to be converted to attributes.
|
2413
|
*
|
2414
|
* @return
|
2415
|
* A string ready for insertion in a tag (starts with a space).
|
2416
|
*
|
2417
|
* @ingroup sanitization
|
2418
|
*/
|
2419
|
function drupal_attributes(array $attributes = array()) {
|
2420
|
foreach ($attributes as $attribute => &$data) {
|
2421
|
$data = implode(' ', (array) $data);
|
2422
|
$data = $attribute . '="' . check_plain($data) . '"';
|
2423
|
}
|
2424
|
return $attributes ? ' ' . implode(' ', $attributes) : '';
|
2425
|
}
|
2426
|
|
2427
|
/**
|
2428
|
* Formats an internal or external URL link as an HTML anchor tag.
|
2429
|
*
|
2430
|
* This function correctly handles aliased paths and adds an 'active' class
|
2431
|
* attribute to links that point to the current page (for theming), so all
|
2432
|
* internal links output by modules should be generated by this function if
|
2433
|
* possible.
|
2434
|
*
|
2435
|
* However, for links enclosed in translatable text you should use t() and
|
2436
|
* embed the HTML anchor tag directly in the translated string. For example:
|
2437
|
* @code
|
2438
|
* t('Visit the <a href="@url">settings</a> page', array('@url' => url('admin')));
|
2439
|
* @endcode
|
2440
|
* This keeps the context of the link title ('settings' in the example) for
|
2441
|
* translators.
|
2442
|
*
|
2443
|
* @param string $text
|
2444
|
* The translated link text for the anchor tag.
|
2445
|
* @param string $path
|
2446
|
* The internal path or external URL being linked to, such as "node/34" or
|
2447
|
* "http://example.com/foo". After the url() function is called to construct
|
2448
|
* the URL from $path and $options, the resulting URL is passed through
|
2449
|
* check_plain() before it is inserted into the HTML anchor tag, to ensure
|
2450
|
* well-formed HTML. See url() for more information and notes.
|
2451
|
* @param array $options
|
2452
|
* An associative array of additional options. Defaults to an empty array. It
|
2453
|
* may contain the following elements.
|
2454
|
* - 'attributes': An associative array of HTML attributes to apply to the
|
2455
|
* anchor tag. If element 'class' is included, it must be an array; 'title'
|
2456
|
* must be a string; other elements are more flexible, as they just need
|
2457
|
* to work in a call to drupal_attributes($options['attributes']).
|
2458
|
* - 'html' (default FALSE): Whether $text is HTML or just plain-text. For
|
2459
|
* example, to make an image tag into a link, this must be set to TRUE, or
|
2460
|
* you will see the escaped HTML image tag. $text is not sanitized if
|
2461
|
* 'html' is TRUE. The calling function must ensure that $text is already
|
2462
|
* safe.
|
2463
|
* - 'language': An optional language object. If the path being linked to is
|
2464
|
* internal to the site, $options['language'] is used to determine whether
|
2465
|
* the link is "active", or pointing to the current page (the language as
|
2466
|
* well as the path must match). This element is also used by url().
|
2467
|
* - Additional $options elements used by the url() function.
|
2468
|
*
|
2469
|
* @return string
|
2470
|
* An HTML string containing a link to the given path.
|
2471
|
*
|
2472
|
* @see url()
|
2473
|
*/
|
2474
|
function l($text, $path, array $options = array()) {
|
2475
|
global $language_url;
|
2476
|
static $use_theme = NULL;
|
2477
|
|
2478
|
// Merge in defaults.
|
2479
|
$options += array(
|
2480
|
'attributes' => array(),
|
2481
|
'html' => FALSE,
|
2482
|
);
|
2483
|
|
2484
|
// Append active class.
|
2485
|
if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
|
2486
|
(empty($options['language']) || $options['language']->language == $language_url->language)) {
|
2487
|
$options['attributes']['class'][] = 'active';
|
2488
|
}
|
2489
|
|
2490
|
// Remove all HTML and PHP tags from a tooltip. For best performance, we act only
|
2491
|
// if a quick strpos() pre-check gave a suspicion (because strip_tags() is expensive).
|
2492
|
if (isset($options['attributes']['title']) && strpos($options['attributes']['title'], '<') !== FALSE) {
|
2493
|
$options['attributes']['title'] = strip_tags($options['attributes']['title']);
|
2494
|
}
|
2495
|
|
2496
|
// Determine if rendering of the link is to be done with a theme function
|
2497
|
// or the inline default. Inline is faster, but if the theme system has been
|
2498
|
// loaded and a module or theme implements a preprocess or process function
|
2499
|
// or overrides the theme_link() function, then invoke theme(). Preliminary
|
2500
|
// benchmarks indicate that invoking theme() can slow down the l() function
|
2501
|
// by 20% or more, and that some of the link-heavy Drupal pages spend more
|
2502
|
// than 10% of the total page request time in the l() function.
|
2503
|
if (!isset($use_theme) && function_exists('theme')) {
|
2504
|
// Allow edge cases to prevent theme initialization and force inline link
|
2505
|
// rendering.
|
2506
|
if (variable_get('theme_link', TRUE)) {
|
2507
|
drupal_theme_initialize();
|
2508
|
$registry = theme_get_registry(FALSE);
|
2509
|
// We don't want to duplicate functionality that's in theme(), so any
|
2510
|
// hint of a module or theme doing anything at all special with the 'link'
|
2511
|
// theme hook should simply result in theme() being called. This includes
|
2512
|
// the overriding of theme_link() with an alternate function or template,
|
2513
|
// the presence of preprocess or process functions, or the presence of
|
2514
|
// include files.
|
2515
|
$use_theme = !isset($registry['link']['function']) || ($registry['link']['function'] != 'theme_link');
|
2516
|
$use_theme = $use_theme || !empty($registry['link']['preprocess functions']) || !empty($registry['link']['process functions']) || !empty($registry['link']['includes']);
|
2517
|
}
|
2518
|
else {
|
2519
|
$use_theme = FALSE;
|
2520
|
}
|
2521
|
}
|
2522
|
if ($use_theme) {
|
2523
|
return theme('link', array('text' => $text, 'path' => $path, 'options' => $options));
|
2524
|
}
|
2525
|
// The result of url() is a plain-text URL. Because we are using it here
|
2526
|
// in an HTML argument context, we need to encode it properly.
|
2527
|
return '<a href="' . check_plain(url($path, $options)) . '"' . drupal_attributes($options['attributes']) . '>' . ($options['html'] ? $text : check_plain($text)) . '</a>';
|
2528
|
}
|
2529
|
|
2530
|
/**
|
2531
|
* Delivers a page callback result to the browser in the appropriate format.
|
2532
|
*
|
2533
|
* This function is most commonly called by menu_execute_active_handler(), but
|
2534
|
* can also be called by error conditions such as drupal_not_found(),
|
2535
|
* drupal_access_denied(), and drupal_site_offline().
|
2536
|
*
|
2537
|
* When a user requests a page, index.php calls menu_execute_active_handler(),
|
2538
|
* which calls the 'page callback' function registered in hook_menu(). The page
|
2539
|
* callback function can return one of:
|
2540
|
* - NULL: to indicate no content.
|
2541
|
* - An integer menu status constant: to indicate an error condition.
|
2542
|
* - A string of HTML content.
|
2543
|
* - A renderable array of content.
|
2544
|
* Returning a renderable array rather than a string of HTML is preferred,
|
2545
|
* because that provides modules with more flexibility in customizing the final
|
2546
|
* result.
|
2547
|
*
|
2548
|
* When the page callback returns its constructed content to
|
2549
|
* menu_execute_active_handler(), this function gets called. The purpose of
|
2550
|
* this function is to determine the most appropriate 'delivery callback'
|
2551
|
* function to route the content to. The delivery callback function then
|
2552
|
* sends the content to the browser in the needed format. The default delivery
|
2553
|
* callback is drupal_deliver_html_page(), which delivers the content as an HTML
|
2554
|
* page, complete with blocks in addition to the content. This default can be
|
2555
|
* overridden on a per menu router item basis by setting 'delivery callback' in
|
2556
|
* hook_menu() or hook_menu_alter(), and can also be overridden on a per request
|
2557
|
* basis in hook_page_delivery_callback_alter().
|
2558
|
*
|
2559
|
* For example, the same page callback function can be used for an HTML
|
2560
|
* version of the page and an Ajax version of the page. The page callback
|
2561
|
* function just needs to decide what content is to be returned and the
|
2562
|
* delivery callback function will send it as an HTML page or an Ajax
|
2563
|
* response, as appropriate.
|
2564
|
*
|
2565
|
* In order for page callbacks to be reusable in different delivery formats,
|
2566
|
* they should not issue any "print" or "echo" statements, but instead just
|
2567
|
* return content.
|
2568
|
*
|
2569
|
* Also note that this function does not perform access checks. The delivery
|
2570
|
* callback function specified in hook_menu(), hook_menu_alter(), or
|
2571
|
* hook_page_delivery_callback_alter() will be called even if the router item
|
2572
|
* access checks fail. This is intentional (it is needed for JSON and other
|
2573
|
* purposes), but it has security implications. Do not call this function
|
2574
|
* directly unless you understand the security implications, and be careful in
|
2575
|
* writing delivery callbacks, so that they do not violate security. See
|
2576
|
* drupal_deliver_html_page() for an example of a delivery callback that
|
2577
|
* respects security.
|
2578
|
*
|
2579
|
* @param $page_callback_result
|
2580
|
* The result of a page callback. Can be one of:
|
2581
|
* - NULL: to indicate no content.
|
2582
|
* - An integer menu status constant: to indicate an error condition.
|
2583
|
* - A string of HTML content.
|
2584
|
* - A renderable array of content.
|
2585
|
* @param $default_delivery_callback
|
2586
|
* (Optional) If given, it is the name of a delivery function most likely
|
2587
|
* to be appropriate for the page request as determined by the calling
|
2588
|
* function (e.g., menu_execute_active_handler()). If not given, it is
|
2589
|
* determined from the menu router information of the current page.
|
2590
|
*
|
2591
|
* @see menu_execute_active_handler()
|
2592
|
* @see hook_menu()
|
2593
|
* @see hook_menu_alter()
|
2594
|
* @see hook_page_delivery_callback_alter()
|
2595
|
*/
|
2596
|
function drupal_deliver_page($page_callback_result, $default_delivery_callback = NULL) {
|
2597
|
if (!isset($default_delivery_callback) && ($router_item = menu_get_item())) {
|
2598
|
$default_delivery_callback = $router_item['delivery_callback'];
|
2599
|
}
|
2600
|
$delivery_callback = !empty($default_delivery_callback) ? $default_delivery_callback : 'drupal_deliver_html_page';
|
2601
|
// Give modules a chance to alter the delivery callback used, based on
|
2602
|
// request-time context (e.g., HTTP request headers).
|
2603
|
drupal_alter('page_delivery_callback', $delivery_callback);
|
2604
|
if (function_exists($delivery_callback)) {
|
2605
|
$delivery_callback($page_callback_result);
|
2606
|
}
|
2607
|
else {
|
2608
|
// If a delivery callback is specified, but doesn't exist as a function,
|
2609
|
// something is wrong, but don't print anything, since it's not known
|
2610
|
// what format the response needs to be in.
|
2611
|
watchdog('delivery callback not found', 'callback %callback not found: %q.', array('%callback' => $delivery_callback, '%q' => $_GET['q']), WATCHDOG_ERROR);
|
2612
|
}
|
2613
|
}
|
2614
|
|
2615
|
/**
|
2616
|
* Packages and sends the result of a page callback to the browser as HTML.
|
2617
|
*
|
2618
|
* @param $page_callback_result
|
2619
|
* The result of a page callback. Can be one of:
|
2620
|
* - NULL: to indicate no content.
|
2621
|
* - An integer menu status constant: to indicate an error condition.
|
2622
|
* - A string of HTML content.
|
2623
|
* - A renderable array of content.
|
2624
|
*
|
2625
|
* @see drupal_deliver_page()
|
2626
|
*/
|
2627
|
function drupal_deliver_html_page($page_callback_result) {
|
2628
|
// Emit the correct charset HTTP header, but not if the page callback
|
2629
|
// result is NULL, since that likely indicates that it printed something
|
2630
|
// in which case, no further headers may be sent, and not if code running
|
2631
|
// for this page request has already set the content type header.
|
2632
|
if (isset($page_callback_result) && is_null(drupal_get_http_header('Content-Type'))) {
|
2633
|
drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
|
2634
|
}
|
2635
|
|
2636
|
// Send appropriate HTTP-Header for browsers and search engines.
|
2637
|
global $language;
|
2638
|
drupal_add_http_header('Content-Language', $language->language);
|
2639
|
|
2640
|
// Menu status constants are integers; page content is a string or array.
|
2641
|
if (is_int($page_callback_result)) {
|
2642
|
// @todo: Break these up into separate functions?
|
2643
|
switch ($page_callback_result) {
|
2644
|
case MENU_NOT_FOUND:
|
2645
|
// Print a 404 page.
|
2646
|
drupal_add_http_header('Status', '404 Not Found');
|
2647
|
|
2648
|
watchdog('page not found', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
|
2649
|
|
2650
|
// Check for and return a fast 404 page if configured.
|
2651
|
drupal_fast_404();
|
2652
|
|
2653
|
// Keep old path for reference, and to allow forms to redirect to it.
|
2654
|
if (!isset($_GET['destination'])) {
|
2655
|
// Make sure that the current path is not interpreted as external URL.
|
2656
|
if (!url_is_external($_GET['q'])) {
|
2657
|
$_GET['destination'] = $_GET['q'];
|
2658
|
}
|
2659
|
}
|
2660
|
|
2661
|
$path = drupal_get_normal_path(variable_get('site_404', ''));
|
2662
|
if ($path && $path != $_GET['q']) {
|
2663
|
// Custom 404 handler. Set the active item in case there are tabs to
|
2664
|
// display, or other dependencies on the path.
|
2665
|
menu_set_active_item($path);
|
2666
|
$return = menu_execute_active_handler($path, FALSE);
|
2667
|
}
|
2668
|
|
2669
|
if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
|
2670
|
// Standard 404 handler.
|
2671
|
drupal_set_title(t('Page not found'));
|
2672
|
$return = t('The requested page "@path" could not be found.', array('@path' => request_uri()));
|
2673
|
}
|
2674
|
|
2675
|
drupal_set_page_content($return);
|
2676
|
$page = element_info('page');
|
2677
|
print drupal_render_page($page);
|
2678
|
break;
|
2679
|
|
2680
|
case MENU_ACCESS_DENIED:
|
2681
|
// Print a 403 page.
|
2682
|
drupal_add_http_header('Status', '403 Forbidden');
|
2683
|
watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
|
2684
|
|
2685
|
// Keep old path for reference, and to allow forms to redirect to it.
|
2686
|
if (!isset($_GET['destination'])) {
|
2687
|
// Make sure that the current path is not interpreted as external URL.
|
2688
|
if (!url_is_external($_GET['q'])) {
|
2689
|
$_GET['destination'] = $_GET['q'];
|
2690
|
}
|
2691
|
}
|
2692
|
|
2693
|
$path = drupal_get_normal_path(variable_get('site_403', ''));
|
2694
|
if ($path && $path != $_GET['q']) {
|
2695
|
// Custom 403 handler. Set the active item in case there are tabs to
|
2696
|
// display or other dependencies on the path.
|
2697
|
menu_set_active_item($path);
|
2698
|
$return = menu_execute_active_handler($path, FALSE);
|
2699
|
}
|
2700
|
|
2701
|
if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
|
2702
|
// Standard 403 handler.
|
2703
|
drupal_set_title(t('Access denied'));
|
2704
|
$return = t('You are not authorized to access this page.');
|
2705
|
}
|
2706
|
|
2707
|
print drupal_render_page($return);
|
2708
|
break;
|
2709
|
|
2710
|
case MENU_SITE_OFFLINE:
|
2711
|
// Print a 503 page.
|
2712
|
drupal_maintenance_theme();
|
2713
|
drupal_add_http_header('Status', '503 Service unavailable');
|
2714
|
drupal_set_title(t('Site under maintenance'));
|
2715
|
print theme('maintenance_page', array('content' => filter_xss_admin(variable_get('maintenance_mode_message',
|
2716
|
t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))))));
|
2717
|
break;
|
2718
|
}
|
2719
|
}
|
2720
|
elseif (isset($page_callback_result)) {
|
2721
|
// Print anything besides a menu constant, assuming it's not NULL or
|
2722
|
// undefined.
|
2723
|
print drupal_render_page($page_callback_result);
|
2724
|
}
|
2725
|
|
2726
|
// Perform end-of-request tasks.
|
2727
|
drupal_page_footer();
|
2728
|
}
|
2729
|
|
2730
|
/**
|
2731
|
* Performs end-of-request tasks.
|
2732
|
*
|
2733
|
* This function sets the page cache if appropriate, and allows modules to
|
2734
|
* react to the closing of the page by calling hook_exit().
|
2735
|
*/
|
2736
|
function drupal_page_footer() {
|
2737
|
global $user;
|
2738
|
|
2739
|
module_invoke_all('exit');
|
2740
|
|
2741
|
// Commit the user session, if needed.
|
2742
|
drupal_session_commit();
|
2743
|
|
2744
|
if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
|
2745
|
drupal_serve_page_from_cache($cache);
|
2746
|
}
|
2747
|
else {
|
2748
|
ob_flush();
|
2749
|
}
|
2750
|
|
2751
|
_registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
|
2752
|
drupal_cache_system_paths();
|
2753
|
module_implements_write_cache();
|
2754
|
system_run_automated_cron();
|
2755
|
}
|
2756
|
|
2757
|
/**
|
2758
|
* Performs end-of-request tasks.
|
2759
|
*
|
2760
|
* In some cases page requests need to end without calling drupal_page_footer().
|
2761
|
* In these cases, call drupal_exit() instead. There should rarely be a reason
|
2762
|
* to call exit instead of drupal_exit();
|
2763
|
*
|
2764
|
* @param $destination
|
2765
|
* If this function is called from drupal_goto(), then this argument
|
2766
|
* will be a fully-qualified URL that is the destination of the redirect.
|
2767
|
* This should be passed along to hook_exit() implementations.
|
2768
|
*/
|
2769
|
function drupal_exit($destination = NULL) {
|
2770
|
if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL) {
|
2771
|
if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
|
2772
|
module_invoke_all('exit', $destination);
|
2773
|
}
|
2774
|
drupal_session_commit();
|
2775
|
}
|
2776
|
exit;
|
2777
|
}
|
2778
|
|
2779
|
/**
|
2780
|
* Forms an associative array from a linear array.
|
2781
|
*
|
2782
|
* This function walks through the provided array and constructs an associative
|
2783
|
* array out of it. The keys of the resulting array will be the values of the
|
2784
|
* input array. The values will be the same as the keys unless a function is
|
2785
|
* specified, in which case the output of the function is used for the values
|
2786
|
* instead.
|
2787
|
*
|
2788
|
* @param $array
|
2789
|
* A linear array.
|
2790
|
* @param $function
|
2791
|
* A name of a function to apply to all values before output.
|
2792
|
*
|
2793
|
* @return
|
2794
|
* An associative array.
|
2795
|
*/
|
2796
|
function drupal_map_assoc($array, $function = NULL) {
|
2797
|
// array_combine() fails with empty arrays:
|
2798
|
// http://bugs.php.net/bug.php?id=34857.
|
2799
|
$array = !empty($array) ? array_combine($array, $array) : array();
|
2800
|
if (is_callable($function)) {
|
2801
|
$array = array_map($function, $array);
|
2802
|
}
|
2803
|
return $array;
|
2804
|
}
|
2805
|
|
2806
|
/**
|
2807
|
* Attempts to set the PHP maximum execution time.
|
2808
|
*
|
2809
|
* This function is a wrapper around the PHP function set_time_limit().
|
2810
|
* When called, set_time_limit() restarts the timeout counter from zero.
|
2811
|
* In other words, if the timeout is the default 30 seconds, and 25 seconds
|
2812
|
* into script execution a call such as set_time_limit(20) is made, the
|
2813
|
* script will run for a total of 45 seconds before timing out.
|
2814
|
*
|
2815
|
* It also means that it is possible to decrease the total time limit if
|
2816
|
* the sum of the new time limit and the current time spent running the
|
2817
|
* script is inferior to the original time limit. It is inherent to the way
|
2818
|
* set_time_limit() works, it should rather be called with an appropriate
|
2819
|
* value every time you need to allocate a certain amount of time
|
2820
|
* to execute a task than only once at the beginning of the script.
|
2821
|
*
|
2822
|
* Before calling set_time_limit(), we check if this function is available
|
2823
|
* because it could be disabled by the server administrator. We also hide all
|
2824
|
* the errors that could occur when calling set_time_limit(), because it is
|
2825
|
* not possible to reliably ensure that PHP or a security extension will
|
2826
|
* not issue a warning/error if they prevent the use of this function.
|
2827
|
*
|
2828
|
* @param $time_limit
|
2829
|
* An integer specifying the new time limit, in seconds. A value of 0
|
2830
|
* indicates unlimited execution time.
|
2831
|
*
|
2832
|
* @ingroup php_wrappers
|
2833
|
*/
|
2834
|
function drupal_set_time_limit($time_limit) {
|
2835
|
if (function_exists('set_time_limit')) {
|
2836
|
@set_time_limit($time_limit);
|
2837
|
}
|
2838
|
}
|
2839
|
|
2840
|
/**
|
2841
|
* Returns the path to a system item (module, theme, etc.).
|
2842
|
*
|
2843
|
* @param $type
|
2844
|
* The type of the item (i.e. theme, theme_engine, module, profile).
|
2845
|
* @param $name
|
2846
|
* The name of the item for which the path is requested.
|
2847
|
*
|
2848
|
* @return
|
2849
|
* The path to the requested item or an empty string if the item is not found.
|
2850
|
*/
|
2851
|
function drupal_get_path($type, $name) {
|
2852
|
return dirname(drupal_get_filename($type, $name));
|
2853
|
}
|
2854
|
|
2855
|
/**
|
2856
|
* Returns the base URL path (i.e., directory) of the Drupal installation.
|
2857
|
*
|
2858
|
* base_path() adds a "/" to the beginning and end of the returned path if the
|
2859
|
* path is not empty. At the very least, this will return "/".
|
2860
|
*
|
2861
|
* Examples:
|
2862
|
* - http://example.com returns "/" because the path is empty.
|
2863
|
* - http://example.com/drupal/folder returns "/drupal/folder/".
|
2864
|
*/
|
2865
|
function base_path() {
|
2866
|
return $GLOBALS['base_path'];
|
2867
|
}
|
2868
|
|
2869
|
/**
|
2870
|
* Adds a LINK tag with a distinct 'rel' attribute to the page's HEAD.
|
2871
|
*
|
2872
|
* This function can be called as long the HTML header hasn't been sent, which
|
2873
|
* on normal pages is up through the preprocess step of theme('html'). Adding
|
2874
|
* a link will overwrite a prior link with the exact same 'rel' and 'href'
|
2875
|
* attributes.
|
2876
|
*
|
2877
|
* @param $attributes
|
2878
|
* Associative array of element attributes including 'href' and 'rel'.
|
2879
|
* @param $header
|
2880
|
* Optional flag to determine if a HTTP 'Link:' header should be sent.
|
2881
|
*/
|
2882
|
function drupal_add_html_head_link($attributes, $header = FALSE) {
|
2883
|
$element = array(
|
2884
|
'#tag' => 'link',
|
2885
|
'#attributes' => $attributes,
|
2886
|
);
|
2887
|
$href = $attributes['href'];
|
2888
|
|
2889
|
if ($header) {
|
2890
|
// Also add a HTTP header "Link:".
|
2891
|
$href = '<' . check_plain($attributes['href']) . '>;';
|
2892
|
unset($attributes['href']);
|
2893
|
$element['#attached']['drupal_add_http_header'][] = array('Link', $href . drupal_http_header_attributes($attributes), TRUE);
|
2894
|
}
|
2895
|
|
2896
|
drupal_add_html_head($element, 'drupal_add_html_head_link:' . $attributes['rel'] . ':' . $href);
|
2897
|
}
|
2898
|
|
2899
|
/**
|
2900
|
* Adds a cascading stylesheet to the stylesheet queue.
|
2901
|
*
|
2902
|
* Calling drupal_static_reset('drupal_add_css') will clear all cascading
|
2903
|
* stylesheets added so far.
|
2904
|
*
|
2905
|
* If CSS aggregation/compression is enabled, all cascading style sheets added
|
2906
|
* with $options['preprocess'] set to TRUE will be merged into one aggregate
|
2907
|
* file and compressed by removing all extraneous white space.
|
2908
|
* Preprocessed inline stylesheets will not be aggregated into this single file;
|
2909
|
* instead, they are just compressed upon output on the page. Externally hosted
|
2910
|
* stylesheets are never aggregated or compressed.
|
2911
|
*
|
2912
|
* The reason for aggregating the files is outlined quite thoroughly here:
|
2913
|
* http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
|
2914
|
* to request overhead, one bigger file just loads faster than two smaller ones
|
2915
|
* half its size."
|
2916
|
*
|
2917
|
* $options['preprocess'] should be only set to TRUE when a file is required for
|
2918
|
* all typical visitors and most pages of a site. It is critical that all
|
2919
|
* preprocessed files are added unconditionally on every page, even if the
|
2920
|
* files do not happen to be needed on a page. This is normally done by calling
|
2921
|
* drupal_add_css() in a hook_init() implementation.
|
2922
|
*
|
2923
|
* Non-preprocessed files should only be added to the page when they are
|
2924
|
* actually needed.
|
2925
|
*
|
2926
|
* @param $data
|
2927
|
* (optional) The stylesheet data to be added, depending on what is passed
|
2928
|
* through to the $options['type'] parameter:
|
2929
|
* - 'file': The path to the CSS file relative to the base_path(), or a
|
2930
|
* stream wrapper URI. For example: "modules/devel/devel.css" or
|
2931
|
* "public://generated_css/stylesheet_1.css". Note that Modules should
|
2932
|
* always prefix the names of their CSS files with the module name; for
|
2933
|
* example, system-menus.css rather than simply menus.css. Themes can
|
2934
|
* override module-supplied CSS files based on their filenames, and this
|
2935
|
* prefixing helps prevent confusing name collisions for theme developers.
|
2936
|
* See drupal_get_css() where the overrides are performed. Also, if the
|
2937
|
* direction of the current language is right-to-left (Hebrew, Arabic,
|
2938
|
* etc.), the function will also look for an RTL CSS file and append it to
|
2939
|
* the list. The name of this file should have an '-rtl.css' suffix. For
|
2940
|
* example, a CSS file called 'mymodule-name.css' will have a
|
2941
|
* 'mymodule-name-rtl.css' file added to the list, if exists in the same
|
2942
|
* directory. This CSS file should contain overrides for properties which
|
2943
|
* should be reversed or otherwise different in a right-to-left display.
|
2944
|
* - 'inline': A string of CSS that should be placed in the given scope. Note
|
2945
|
* that it is better practice to use 'file' stylesheets, rather than
|
2946
|
* 'inline', as the CSS would then be aggregated and cached.
|
2947
|
* - 'external': The absolute path to an external CSS file that is not hosted
|
2948
|
* on the local server. These files will not be aggregated if CSS
|
2949
|
* aggregation is enabled.
|
2950
|
* @param $options
|
2951
|
* (optional) A string defining the 'type' of CSS that is being added in the
|
2952
|
* $data parameter ('file', 'inline', or 'external'), or an array which can
|
2953
|
* have any or all of the following keys:
|
2954
|
* - 'type': The type of stylesheet being added. Available options are 'file',
|
2955
|
* 'inline' or 'external'. Defaults to 'file'.
|
2956
|
* - 'basename': Force a basename for the file being added. Modules are
|
2957
|
* expected to use stylesheets with unique filenames, but integration of
|
2958
|
* external libraries may make this impossible. The basename of
|
2959
|
* 'modules/node/node.css' is 'node.css'. If the external library "node.js"
|
2960
|
* ships with a 'node.css', then a different, unique basename would be
|
2961
|
* 'node.js.css'.
|
2962
|
* - 'group': A number identifying the group in which to add the stylesheet.
|
2963
|
* Available constants are:
|
2964
|
* - CSS_SYSTEM: Any system-layer CSS.
|
2965
|
* - CSS_DEFAULT: (default) Any module-layer CSS.
|
2966
|
* - CSS_THEME: Any theme-layer CSS.
|
2967
|
* The group number serves as a weight: the markup for loading a stylesheet
|
2968
|
* within a lower weight group is output to the page before the markup for
|
2969
|
* loading a stylesheet within a higher weight group, so CSS within higher
|
2970
|
* weight groups take precendence over CSS within lower weight groups.
|
2971
|
* - 'every_page': For optimal front-end performance when aggregation is
|
2972
|
* enabled, this should be set to TRUE if the stylesheet is present on every
|
2973
|
* page of the website for users for whom it is present at all. This
|
2974
|
* defaults to FALSE. It is set to TRUE for stylesheets added via module and
|
2975
|
* theme .info files. Modules that add stylesheets within hook_init()
|
2976
|
* implementations, or from other code that ensures that the stylesheet is
|
2977
|
* added to all website pages, should also set this flag to TRUE. All
|
2978
|
* stylesheets within the same group that have the 'every_page' flag set to
|
2979
|
* TRUE and do not have 'preprocess' set to FALSE are aggregated together
|
2980
|
* into a single aggregate file, and that aggregate file can be reused
|
2981
|
* across a user's entire site visit, leading to faster navigation between
|
2982
|
* pages. However, stylesheets that are only needed on pages less frequently
|
2983
|
* visited, can be added by code that only runs for those particular pages,
|
2984
|
* and that code should not set the 'every_page' flag. This minimizes the
|
2985
|
* size of the aggregate file that the user needs to download when first
|
2986
|
* visiting the website. Stylesheets without the 'every_page' flag are
|
2987
|
* aggregated into a separate aggregate file. This other aggregate file is
|
2988
|
* likely to change from page to page, and each new aggregate file needs to
|
2989
|
* be downloaded when first encountered, so it should be kept relatively
|
2990
|
* small by ensuring that most commonly needed stylesheets are added to
|
2991
|
* every page.
|
2992
|
* - 'weight': The weight of the stylesheet specifies the order in which the
|
2993
|
* CSS will appear relative to other stylesheets with the same group and
|
2994
|
* 'every_page' flag. The exact ordering of stylesheets is as follows:
|
2995
|
* - First by group.
|
2996
|
* - Then by the 'every_page' flag, with TRUE coming before FALSE.
|
2997
|
* - Then by weight.
|
2998
|
* - Then by the order in which the CSS was added. For example, all else
|
2999
|
* being the same, a stylesheet added by a call to drupal_add_css() that
|
3000
|
* happened later in the page request gets added to the page after one for
|
3001
|
* which drupal_add_css() happened earlier in the page request.
|
3002
|
* - 'media': The media type for the stylesheet, e.g., all, print, screen.
|
3003
|
* Defaults to 'all'.
|
3004
|
* - 'preprocess': If TRUE and CSS aggregation/compression is enabled, the
|
3005
|
* styles will be aggregated and compressed. Defaults to TRUE.
|
3006
|
* - 'browsers': An array containing information specifying which browsers
|
3007
|
* should load the CSS item. See drupal_pre_render_conditional_comments()
|
3008
|
* for details.
|
3009
|
*
|
3010
|
* @return
|
3011
|
* An array of queued cascading stylesheets.
|
3012
|
*
|
3013
|
* @see drupal_get_css()
|
3014
|
*/
|
3015
|
function drupal_add_css($data = NULL, $options = NULL) {
|
3016
|
$css = &drupal_static(__FUNCTION__, array());
|
3017
|
|
3018
|
// Construct the options, taking the defaults into consideration.
|
3019
|
if (isset($options)) {
|
3020
|
if (!is_array($options)) {
|
3021
|
$options = array('type' => $options);
|
3022
|
}
|
3023
|
}
|
3024
|
else {
|
3025
|
$options = array();
|
3026
|
}
|
3027
|
|
3028
|
// Create an array of CSS files for each media type first, since each type needs to be served
|
3029
|
// to the browser differently.
|
3030
|
if (isset($data)) {
|
3031
|
$options += array(
|
3032
|
'type' => 'file',
|
3033
|
'group' => CSS_DEFAULT,
|
3034
|
'weight' => 0,
|
3035
|
'every_page' => FALSE,
|
3036
|
'media' => 'all',
|
3037
|
'preprocess' => TRUE,
|
3038
|
'data' => $data,
|
3039
|
'browsers' => array(),
|
3040
|
);
|
3041
|
$options['browsers'] += array(
|
3042
|
'IE' => TRUE,
|
3043
|
'!IE' => TRUE,
|
3044
|
);
|
3045
|
|
3046
|
// Files with a query string cannot be preprocessed.
|
3047
|
if ($options['type'] === 'file' && $options['preprocess'] && strpos($options['data'], '?') !== FALSE) {
|
3048
|
$options['preprocess'] = FALSE;
|
3049
|
}
|
3050
|
|
3051
|
// Always add a tiny value to the weight, to conserve the insertion order.
|
3052
|
$options['weight'] += count($css) / 1000;
|
3053
|
|
3054
|
// Add the data to the CSS array depending on the type.
|
3055
|
switch ($options['type']) {
|
3056
|
case 'inline':
|
3057
|
// For inline stylesheets, we don't want to use the $data as the array
|
3058
|
// key as $data could be a very long string of CSS.
|
3059
|
$css[] = $options;
|
3060
|
break;
|
3061
|
default:
|
3062
|
// Local and external files must keep their name as the associative key
|
3063
|
// so the same CSS file is not be added twice.
|
3064
|
$css[$data] = $options;
|
3065
|
}
|
3066
|
}
|
3067
|
|
3068
|
return $css;
|
3069
|
}
|
3070
|
|
3071
|
/**
|
3072
|
* Returns a themed representation of all stylesheets to attach to the page.
|
3073
|
*
|
3074
|
* It loads the CSS in order, with 'module' first, then 'theme' afterwards.
|
3075
|
* This ensures proper cascading of styles so themes can easily override
|
3076
|
* module styles through CSS selectors.
|
3077
|
*
|
3078
|
* Themes may replace module-defined CSS files by adding a stylesheet with the
|
3079
|
* same filename. For example, themes/bartik/system-menus.css would replace
|
3080
|
* modules/system/system-menus.css. This allows themes to override complete
|
3081
|
* CSS files, rather than specific selectors, when necessary.
|
3082
|
*
|
3083
|
* If the original CSS file is being overridden by a theme, the theme is
|
3084
|
* responsible for supplying an accompanying RTL CSS file to replace the
|
3085
|
* module's.
|
3086
|
*
|
3087
|
* @param $css
|
3088
|
* (optional) An array of CSS files. If no array is provided, the default
|
3089
|
* stylesheets array is used instead.
|
3090
|
* @param $skip_alter
|
3091
|
* (optional) If set to TRUE, this function skips calling drupal_alter() on
|
3092
|
* $css, useful when the calling function passes a $css array that has already
|
3093
|
* been altered.
|
3094
|
*
|
3095
|
* @return
|
3096
|
* A string of XHTML CSS tags.
|
3097
|
*
|
3098
|
* @see drupal_add_css()
|
3099
|
*/
|
3100
|
function drupal_get_css($css = NULL, $skip_alter = FALSE) {
|
3101
|
if (!isset($css)) {
|
3102
|
$css = drupal_add_css();
|
3103
|
}
|
3104
|
|
3105
|
// Allow modules and themes to alter the CSS items.
|
3106
|
if (!$skip_alter) {
|
3107
|
drupal_alter('css', $css);
|
3108
|
}
|
3109
|
|
3110
|
// Sort CSS items, so that they appear in the correct order.
|
3111
|
uasort($css, 'drupal_sort_css_js');
|
3112
|
|
3113
|
// Provide the page with information about the individual CSS files used,
|
3114
|
// information not otherwise available when CSS aggregation is enabled. The
|
3115
|
// setting is attached later in this function, but is set here, so that CSS
|
3116
|
// files removed below are still considered "used" and prevented from being
|
3117
|
// added in a later AJAX request.
|
3118
|
// Skip if no files were added to the page or jQuery.extend() will overwrite
|
3119
|
// the Drupal.settings.ajaxPageState.css object with an empty array.
|
3120
|
if (!empty($css)) {
|
3121
|
// Cast the array to an object to be on the safe side even if not empty.
|
3122
|
$setting['ajaxPageState']['css'] = (object) array_fill_keys(array_keys($css), 1);
|
3123
|
}
|
3124
|
|
3125
|
// Remove the overridden CSS files. Later CSS files override former ones.
|
3126
|
$previous_item = array();
|
3127
|
foreach ($css as $key => $item) {
|
3128
|
if ($item['type'] == 'file') {
|
3129
|
// If defined, force a unique basename for this file.
|
3130
|
$basename = isset($item['basename']) ? $item['basename'] : drupal_basename($item['data']);
|
3131
|
if (isset($previous_item[$basename])) {
|
3132
|
// Remove the previous item that shared the same base name.
|
3133
|
unset($css[$previous_item[$basename]]);
|
3134
|
}
|
3135
|
$previous_item[$basename] = $key;
|
3136
|
}
|
3137
|
}
|
3138
|
|
3139
|
// Render the HTML needed to load the CSS.
|
3140
|
$styles = array(
|
3141
|
'#type' => 'styles',
|
3142
|
'#items' => $css,
|
3143
|
);
|
3144
|
|
3145
|
if (!empty($setting)) {
|
3146
|
$styles['#attached']['js'][] = array('type' => 'setting', 'data' => $setting);
|
3147
|
}
|
3148
|
|
3149
|
return drupal_render($styles);
|
3150
|
}
|
3151
|
|
3152
|
/**
|
3153
|
* Sorts CSS and JavaScript resources.
|
3154
|
*
|
3155
|
* Callback for uasort() within:
|
3156
|
* - drupal_get_css()
|
3157
|
* - drupal_get_js()
|
3158
|
*
|
3159
|
* This sort order helps optimize front-end performance while providing modules
|
3160
|
* and themes with the necessary control for ordering the CSS and JavaScript
|
3161
|
* appearing on a page.
|
3162
|
*
|
3163
|
* @param $a
|
3164
|
* First item for comparison. The compared items should be associative arrays
|
3165
|
* of member items from drupal_add_css() or drupal_add_js().
|
3166
|
* @param $b
|
3167
|
* Second item for comparison.
|
3168
|
*
|
3169
|
* @see drupal_add_css()
|
3170
|
* @see drupal_add_js()
|
3171
|
*/
|
3172
|
function drupal_sort_css_js($a, $b) {
|
3173
|
// First order by group, so that, for example, all items in the CSS_SYSTEM
|
3174
|
// group appear before items in the CSS_DEFAULT group, which appear before
|
3175
|
// all items in the CSS_THEME group. Modules may create additional groups by
|
3176
|
// defining their own constants.
|
3177
|
if ($a['group'] < $b['group']) {
|
3178
|
return -1;
|
3179
|
}
|
3180
|
elseif ($a['group'] > $b['group']) {
|
3181
|
return 1;
|
3182
|
}
|
3183
|
// Within a group, order all infrequently needed, page-specific files after
|
3184
|
// common files needed throughout the website. Separating this way allows for
|
3185
|
// the aggregate file generated for all of the common files to be reused
|
3186
|
// across a site visit without being cut by a page using a less common file.
|
3187
|
elseif ($a['every_page'] && !$b['every_page']) {
|
3188
|
return -1;
|
3189
|
}
|
3190
|
elseif (!$a['every_page'] && $b['every_page']) {
|
3191
|
return 1;
|
3192
|
}
|
3193
|
// Finally, order by weight.
|
3194
|
elseif ($a['weight'] < $b['weight']) {
|
3195
|
return -1;
|
3196
|
}
|
3197
|
elseif ($a['weight'] > $b['weight']) {
|
3198
|
return 1;
|
3199
|
}
|
3200
|
else {
|
3201
|
return 0;
|
3202
|
}
|
3203
|
}
|
3204
|
|
3205
|
/**
|
3206
|
* Default callback to group CSS items.
|
3207
|
*
|
3208
|
* This function arranges the CSS items that are in the #items property of the
|
3209
|
* styles element into groups. Arranging the CSS items into groups serves two
|
3210
|
* purposes. When aggregation is enabled, files within a group are aggregated
|
3211
|
* into a single file, significantly improving page loading performance by
|
3212
|
* minimizing network traffic overhead. When aggregation is disabled, grouping
|
3213
|
* allows multiple files to be loaded from a single STYLE tag, enabling sites
|
3214
|
* with many modules enabled or a complex theme being used to stay within IE's
|
3215
|
* 31 CSS inclusion tag limit: http://drupal.org/node/228818.
|
3216
|
*
|
3217
|
* This function puts multiple items into the same group if they are groupable
|
3218
|
* and if they are for the same 'media' and 'browsers'. Items of the 'file' type
|
3219
|
* are groupable if their 'preprocess' flag is TRUE, items of the 'inline' type
|
3220
|
* are always groupable, and items of the 'external' type are never groupable.
|
3221
|
* This function also ensures that the process of grouping items does not change
|
3222
|
* their relative order. This requirement may result in multiple groups for the
|
3223
|
* same type, media, and browsers, if needed to accommodate other items in
|
3224
|
* between.
|
3225
|
*
|
3226
|
* @param $css
|
3227
|
* An array of CSS items, as returned by drupal_add_css(), but after
|
3228
|
* alteration performed by drupal_get_css().
|
3229
|
*
|
3230
|
* @return
|
3231
|
* An array of CSS groups. Each group contains the same keys (e.g., 'media',
|
3232
|
* 'data', etc.) as a CSS item from the $css parameter, with the value of
|
3233
|
* each key applying to the group as a whole. Each group also contains an
|
3234
|
* 'items' key, which is the subset of items from $css that are in the group.
|
3235
|
*
|
3236
|
* @see drupal_pre_render_styles()
|
3237
|
* @see system_element_info()
|
3238
|
*/
|
3239
|
function drupal_group_css($css) {
|
3240
|
$groups = array();
|
3241
|
// If a group can contain multiple items, we track the information that must
|
3242
|
// be the same for each item in the group, so that when we iterate the next
|
3243
|
// item, we can determine if it can be put into the current group, or if a
|
3244
|
// new group needs to be made for it.
|
3245
|
$current_group_keys = NULL;
|
3246
|
// When creating a new group, we pre-increment $i, so by initializing it to
|
3247
|
// -1, the first group will have index 0.
|
3248
|
$i = -1;
|
3249
|
foreach ($css as $item) {
|
3250
|
// The browsers for which the CSS item needs to be loaded is part of the
|
3251
|
// information that determines when a new group is needed, but the order of
|
3252
|
// keys in the array doesn't matter, and we don't want a new group if all
|
3253
|
// that's different is that order.
|
3254
|
ksort($item['browsers']);
|
3255
|
|
3256
|
// If the item can be grouped with other items, set $group_keys to an array
|
3257
|
// of information that must be the same for all items in its group. If the
|
3258
|
// item can't be grouped with other items, set $group_keys to FALSE. We
|
3259
|
// put items into a group that can be aggregated together: whether they will
|
3260
|
// be aggregated is up to the _drupal_css_aggregate() function or an
|
3261
|
// override of that function specified in hook_css_alter(), but regardless
|
3262
|
// of the details of that function, a group represents items that can be
|
3263
|
// aggregated. Since a group may be rendered with a single HTML tag, all
|
3264
|
// items in the group must share the same information that would need to be
|
3265
|
// part of that HTML tag.
|
3266
|
switch ($item['type']) {
|
3267
|
case 'file':
|
3268
|
// Group file items if their 'preprocess' flag is TRUE.
|
3269
|
// Help ensure maximum reuse of aggregate files by only grouping
|
3270
|
// together items that share the same 'group' value and 'every_page'
|
3271
|
// flag. See drupal_add_css() for details about that.
|
3272
|
$group_keys = $item['preprocess'] ? array($item['type'], $item['group'], $item['every_page'], $item['media'], $item['browsers']) : FALSE;
|
3273
|
break;
|
3274
|
case 'inline':
|
3275
|
// Always group inline items.
|
3276
|
$group_keys = array($item['type'], $item['media'], $item['browsers']);
|
3277
|
break;
|
3278
|
case 'external':
|
3279
|
// Do not group external items.
|
3280
|
$group_keys = FALSE;
|
3281
|
break;
|
3282
|
}
|
3283
|
|
3284
|
// If the group keys don't match the most recent group we're working with,
|
3285
|
// then a new group must be made.
|
3286
|
if ($group_keys !== $current_group_keys) {
|
3287
|
$i++;
|
3288
|
// Initialize the new group with the same properties as the first item
|
3289
|
// being placed into it. The item's 'data' and 'weight' properties are
|
3290
|
// unique to the item and should not be carried over to the group.
|
3291
|
$groups[$i] = $item;
|
3292
|
unset($groups[$i]['data'], $groups[$i]['weight']);
|
3293
|
$groups[$i]['items'] = array();
|
3294
|
$current_group_keys = $group_keys ? $group_keys : NULL;
|
3295
|
}
|
3296
|
|
3297
|
// Add the item to the current group.
|
3298
|
$groups[$i]['items'][] = $item;
|
3299
|
}
|
3300
|
return $groups;
|
3301
|
}
|
3302
|
|
3303
|
/**
|
3304
|
* Default callback to aggregate CSS files and inline content.
|
3305
|
*
|
3306
|
* Having the browser load fewer CSS files results in much faster page loads
|
3307
|
* than when it loads many small files. This function aggregates files within
|
3308
|
* the same group into a single file unless the site-wide setting to do so is
|
3309
|
* disabled (commonly the case during site development). To optimize download,
|
3310
|
* it also compresses the aggregate files by removing comments, whitespace, and
|
3311
|
* other unnecessary content. Additionally, this functions aggregates inline
|
3312
|
* content together, regardless of the site-wide aggregation setting.
|
3313
|
*
|
3314
|
* @param $css_groups
|
3315
|
* An array of CSS groups as returned by drupal_group_css(). This function
|
3316
|
* modifies the group's 'data' property for each group that is aggregated.
|
3317
|
*
|
3318
|
* @see drupal_group_css()
|
3319
|
* @see drupal_pre_render_styles()
|
3320
|
* @see system_element_info()
|
3321
|
*/
|
3322
|
function drupal_aggregate_css(&$css_groups) {
|
3323
|
$preprocess_css = (variable_get('preprocess_css', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
|
3324
|
|
3325
|
// For each group that needs aggregation, aggregate its items.
|
3326
|
foreach ($css_groups as $key => $group) {
|
3327
|
switch ($group['type']) {
|
3328
|
// If a file group can be aggregated into a single file, do so, and set
|
3329
|
// the group's data property to the file path of the aggregate file.
|
3330
|
case 'file':
|
3331
|
if ($group['preprocess'] && $preprocess_css) {
|
3332
|
$css_groups[$key]['data'] = drupal_build_css_cache($group['items']);
|
3333
|
}
|
3334
|
break;
|
3335
|
// Aggregate all inline CSS content into the group's data property.
|
3336
|
case 'inline':
|
3337
|
$css_groups[$key]['data'] = '';
|
3338
|
foreach ($group['items'] as $item) {
|
3339
|
$css_groups[$key]['data'] .= drupal_load_stylesheet_content($item['data'], $item['preprocess']);
|
3340
|
}
|
3341
|
break;
|
3342
|
}
|
3343
|
}
|
3344
|
}
|
3345
|
|
3346
|
/**
|
3347
|
* #pre_render callback to add the elements needed for CSS tags to be rendered.
|
3348
|
*
|
3349
|
* For production websites, LINK tags are preferable to STYLE tags with @import
|
3350
|
* statements, because:
|
3351
|
* - They are the standard tag intended for linking to a resource.
|
3352
|
* - On Firefox 2 and perhaps other browsers, CSS files included with @import
|
3353
|
* statements don't get saved when saving the complete web page for offline
|
3354
|
* use: http://drupal.org/node/145218.
|
3355
|
* - On IE, if only LINK tags and no @import statements are used, all the CSS
|
3356
|
* files are downloaded in parallel, resulting in faster page load, but if
|
3357
|
* @import statements are used and span across multiple STYLE tags, all the
|
3358
|
* ones from one STYLE tag must be downloaded before downloading begins for
|
3359
|
* the next STYLE tag. Furthermore, IE7 does not support media declaration on
|
3360
|
* the @import statement, so multiple STYLE tags must be used when different
|
3361
|
* files are for different media types. Non-IE browsers always download in
|
3362
|
* parallel, so this is an IE-specific performance quirk:
|
3363
|
* http://www.stevesouders.com/blog/2009/04/09/dont-use-import/.
|
3364
|
*
|
3365
|
* However, IE has an annoying limit of 31 total CSS inclusion tags
|
3366
|
* (http://drupal.org/node/228818) and LINK tags are limited to one file per
|
3367
|
* tag, whereas STYLE tags can contain multiple @import statements allowing
|
3368
|
* multiple files to be loaded per tag. When CSS aggregation is disabled, a
|
3369
|
* Drupal site can easily have more than 31 CSS files that need to be loaded, so
|
3370
|
* using LINK tags exclusively would result in a site that would display
|
3371
|
* incorrectly in IE. Depending on different needs, different strategies can be
|
3372
|
* employed to decide when to use LINK tags and when to use STYLE tags.
|
3373
|
*
|
3374
|
* The strategy employed by this function is to use LINK tags for all aggregate
|
3375
|
* files and for all files that cannot be aggregated (e.g., if 'preprocess' is
|
3376
|
* set to FALSE or the type is 'external'), and to use STYLE tags for groups
|
3377
|
* of files that could be aggregated together but aren't (e.g., if the site-wide
|
3378
|
* aggregation setting is disabled). This results in all LINK tags when
|
3379
|
* aggregation is enabled, a guarantee that as many or only slightly more tags
|
3380
|
* are used with aggregation disabled than enabled (so that if the limit were to
|
3381
|
* be crossed with aggregation enabled, the site developer would also notice the
|
3382
|
* problem while aggregation is disabled), and an easy way for a developer to
|
3383
|
* view HTML source while aggregation is disabled and know what files will be
|
3384
|
* aggregated together when aggregation becomes enabled.
|
3385
|
*
|
3386
|
* This function evaluates the aggregation enabled/disabled condition on a group
|
3387
|
* by group basis by testing whether an aggregate file has been made for the
|
3388
|
* group rather than by testing the site-wide aggregation setting. This allows
|
3389
|
* this function to work correctly even if modules have implemented custom
|
3390
|
* logic for grouping and aggregating files.
|
3391
|
*
|
3392
|
* @param $element
|
3393
|
* A render array containing:
|
3394
|
* - '#items': The CSS items as returned by drupal_add_css() and altered by
|
3395
|
* drupal_get_css().
|
3396
|
* - '#group_callback': A function to call to group #items to enable the use
|
3397
|
* of fewer tags by aggregating files and/or using multiple @import
|
3398
|
* statements within a single tag.
|
3399
|
* - '#aggregate_callback': A function to call to aggregate the items within
|
3400
|
* the groups arranged by the #group_callback function.
|
3401
|
*
|
3402
|
* @return
|
3403
|
* A render array that will render to a string of XHTML CSS tags.
|
3404
|
*
|
3405
|
* @see drupal_get_css()
|
3406
|
*/
|
3407
|
function drupal_pre_render_styles($elements) {
|
3408
|
// Group and aggregate the items.
|
3409
|
if (isset($elements['#group_callback'])) {
|
3410
|
$elements['#groups'] = $elements['#group_callback']($elements['#items']);
|
3411
|
}
|
3412
|
if (isset($elements['#aggregate_callback'])) {
|
3413
|
$elements['#aggregate_callback']($elements['#groups']);
|
3414
|
}
|
3415
|
|
3416
|
// A dummy query-string is added to filenames, to gain control over
|
3417
|
// browser-caching. The string changes on every update or full cache
|
3418
|
// flush, forcing browsers to load a new copy of the files, as the
|
3419
|
// URL changed.
|
3420
|
$query_string = variable_get('css_js_query_string', '0');
|
3421
|
|
3422
|
// For inline CSS to validate as XHTML, all CSS containing XHTML needs to be
|
3423
|
// wrapped in CDATA. To make that backwards compatible with HTML 4, we need to
|
3424
|
// comment out the CDATA-tag.
|
3425
|
$embed_prefix = "\n<!--/*--><![CDATA[/*><!--*/\n";
|
3426
|
$embed_suffix = "\n/*]]>*/-->\n";
|
3427
|
|
3428
|
// Defaults for LINK and STYLE elements.
|
3429
|
$link_element_defaults = array(
|
3430
|
'#type' => 'html_tag',
|
3431
|
'#tag' => 'link',
|
3432
|
'#attributes' => array(
|
3433
|
'type' => 'text/css',
|
3434
|
'rel' => 'stylesheet',
|
3435
|
),
|
3436
|
);
|
3437
|
$style_element_defaults = array(
|
3438
|
'#type' => 'html_tag',
|
3439
|
'#tag' => 'style',
|
3440
|
'#attributes' => array(
|
3441
|
'type' => 'text/css',
|
3442
|
),
|
3443
|
);
|
3444
|
|
3445
|
// Loop through each group.
|
3446
|
foreach ($elements['#groups'] as $group) {
|
3447
|
switch ($group['type']) {
|
3448
|
// For file items, there are three possibilites.
|
3449
|
// - The group has been aggregated: in this case, output a LINK tag for
|
3450
|
// the aggregate file.
|
3451
|
// - The group can be aggregated but has not been (most likely because
|
3452
|
// the site administrator disabled the site-wide setting): in this case,
|
3453
|
// output as few STYLE tags for the group as possible, using @import
|
3454
|
// statement for each file in the group. This enables us to stay within
|
3455
|
// IE's limit of 31 total CSS inclusion tags.
|
3456
|
// - The group contains items not eligible for aggregation (their
|
3457
|
// 'preprocess' flag has been set to FALSE): in this case, output a LINK
|
3458
|
// tag for each file.
|
3459
|
case 'file':
|
3460
|
// The group has been aggregated into a single file: output a LINK tag
|
3461
|
// for the aggregate file.
|
3462
|
if (isset($group['data'])) {
|
3463
|
$element = $link_element_defaults;
|
3464
|
$element['#attributes']['href'] = file_create_url($group['data']);
|
3465
|
$element['#attributes']['media'] = $group['media'];
|
3466
|
$element['#browsers'] = $group['browsers'];
|
3467
|
$elements[] = $element;
|
3468
|
}
|
3469
|
// The group can be aggregated, but hasn't been: combine multiple items
|
3470
|
// into as few STYLE tags as possible.
|
3471
|
elseif ($group['preprocess']) {
|
3472
|
$import = array();
|
3473
|
foreach ($group['items'] as $item) {
|
3474
|
// A theme's .info file may have an entry for a file that doesn't
|
3475
|
// exist as a way of overriding a module or base theme CSS file from
|
3476
|
// being added to the page. Normally, file_exists() calls that need
|
3477
|
// to run for every page request should be minimized, but this one
|
3478
|
// is okay, because it only runs when CSS aggregation is disabled.
|
3479
|
// On a server under heavy enough load that file_exists() calls need
|
3480
|
// to be minimized, CSS aggregation should be enabled, in which case
|
3481
|
// this code is not run. When aggregation is enabled,
|
3482
|
// drupal_load_stylesheet() checks file_exists(), but only when
|
3483
|
// building the aggregate file, which is then reused for many page
|
3484
|
// requests.
|
3485
|
if (file_exists($item['data'])) {
|
3486
|
// The dummy query string needs to be added to the URL to control
|
3487
|
// browser-caching. IE7 does not support a media type on the
|
3488
|
// @import statement, so we instead specify the media for the
|
3489
|
// group on the STYLE tag.
|
3490
|
$import[] = '@import url("' . check_plain(file_create_url($item['data']) . '?' . $query_string) . '");';
|
3491
|
}
|
3492
|
}
|
3493
|
// In addition to IE's limit of 31 total CSS inclusion tags, it also
|
3494
|
// has a limit of 31 @import statements per STYLE tag.
|
3495
|
while (!empty($import)) {
|
3496
|
$import_batch = array_slice($import, 0, 31);
|
3497
|
$import = array_slice($import, 31);
|
3498
|
$element = $style_element_defaults;
|
3499
|
// This simplifies the JavaScript regex, allowing each line
|
3500
|
// (separated by \n) to be treated as a completely different string.
|
3501
|
// This means that we can use ^ and $ on one line at a time, and not
|
3502
|
// worry about style tags since they'll never match the regex.
|
3503
|
$element['#value'] = "\n" . implode("\n", $import_batch) . "\n";
|
3504
|
$element['#attributes']['media'] = $group['media'];
|
3505
|
$element['#browsers'] = $group['browsers'];
|
3506
|
$elements[] = $element;
|
3507
|
}
|
3508
|
}
|
3509
|
// The group contains items ineligible for aggregation: output a LINK
|
3510
|
// tag for each file.
|
3511
|
else {
|
3512
|
foreach ($group['items'] as $item) {
|
3513
|
$element = $link_element_defaults;
|
3514
|
// We do not check file_exists() here, because this code runs for
|
3515
|
// files whose 'preprocess' is set to FALSE, and therefore, even
|
3516
|
// when aggregation is enabled, and we want to avoid needlessly
|
3517
|
// taxing a server that may be under heavy load. The file_exists()
|
3518
|
// performed above for files whose 'preprocess' is TRUE is done for
|
3519
|
// the benefit of theme .info files, but code that deals with files
|
3520
|
// whose 'preprocess' is FALSE is responsible for ensuring the file
|
3521
|
// exists.
|
3522
|
// The dummy query string needs to be added to the URL to control
|
3523
|
// browser-caching.
|
3524
|
$query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
|
3525
|
$element['#attributes']['href'] = file_create_url($item['data']) . $query_string_separator . $query_string;
|
3526
|
$element['#attributes']['media'] = $item['media'];
|
3527
|
$element['#browsers'] = $group['browsers'];
|
3528
|
$elements[] = $element;
|
3529
|
}
|
3530
|
}
|
3531
|
break;
|
3532
|
// For inline content, the 'data' property contains the CSS content. If
|
3533
|
// the group's 'data' property is set, then output it in a single STYLE
|
3534
|
// tag. Otherwise, output a separate STYLE tag for each item.
|
3535
|
case 'inline':
|
3536
|
if (isset($group['data'])) {
|
3537
|
$element = $style_element_defaults;
|
3538
|
$element['#value'] = $group['data'];
|
3539
|
$element['#value_prefix'] = $embed_prefix;
|
3540
|
$element['#value_suffix'] = $embed_suffix;
|
3541
|
$element['#attributes']['media'] = $group['media'];
|
3542
|
$element['#browsers'] = $group['browsers'];
|
3543
|
$elements[] = $element;
|
3544
|
}
|
3545
|
else {
|
3546
|
foreach ($group['items'] as $item) {
|
3547
|
$element = $style_element_defaults;
|
3548
|
$element['#value'] = $item['data'];
|
3549
|
$element['#value_prefix'] = $embed_prefix;
|
3550
|
$element['#value_suffix'] = $embed_suffix;
|
3551
|
$element['#attributes']['media'] = $item['media'];
|
3552
|
$element['#browsers'] = $group['browsers'];
|
3553
|
$elements[] = $element;
|
3554
|
}
|
3555
|
}
|
3556
|
break;
|
3557
|
// Output a LINK tag for each external item. The item's 'data' property
|
3558
|
// contains the full URL.
|
3559
|
case 'external':
|
3560
|
foreach ($group['items'] as $item) {
|
3561
|
$element = $link_element_defaults;
|
3562
|
$element['#attributes']['href'] = $item['data'];
|
3563
|
$element['#attributes']['media'] = $item['media'];
|
3564
|
$element['#browsers'] = $group['browsers'];
|
3565
|
$elements[] = $element;
|
3566
|
}
|
3567
|
break;
|
3568
|
}
|
3569
|
}
|
3570
|
|
3571
|
return $elements;
|
3572
|
}
|
3573
|
|
3574
|
/**
|
3575
|
* Aggregates and optimizes CSS files into a cache file in the files directory.
|
3576
|
*
|
3577
|
* The file name for the CSS cache file is generated from the hash of the
|
3578
|
* aggregated contents of the files in $css. This forces proxies and browsers
|
3579
|
* to download new CSS when the CSS changes.
|
3580
|
*
|
3581
|
* The cache file name is retrieved on a page load via a lookup variable that
|
3582
|
* contains an associative array. The array key is the hash of the file names
|
3583
|
* in $css while the value is the cache file name. The cache file is generated
|
3584
|
* in two cases. First, if there is no file name value for the key, which will
|
3585
|
* happen if a new file name has been added to $css or after the lookup
|
3586
|
* variable is emptied to force a rebuild of the cache. Second, the cache file
|
3587
|
* is generated if it is missing on disk. Old cache files are not deleted
|
3588
|
* immediately when the lookup variable is emptied, but are deleted after a set
|
3589
|
* period by drupal_delete_file_if_stale(). This ensures that files referenced
|
3590
|
* by a cached page will still be available.
|
3591
|
*
|
3592
|
* @param $css
|
3593
|
* An array of CSS files to aggregate and compress into one file.
|
3594
|
*
|
3595
|
* @return
|
3596
|
* The URI of the CSS cache file, or FALSE if the file could not be saved.
|
3597
|
*/
|
3598
|
function drupal_build_css_cache($css) {
|
3599
|
$data = '';
|
3600
|
$uri = '';
|
3601
|
$map = variable_get('drupal_css_cache_files', array());
|
3602
|
// Create a new array so that only the file names are used to create the hash.
|
3603
|
// This prevents new aggregates from being created unnecessarily.
|
3604
|
$css_data = array();
|
3605
|
foreach ($css as $css_file) {
|
3606
|
$css_data[] = $css_file['data'];
|
3607
|
}
|
3608
|
$key = hash('sha256', serialize($css_data));
|
3609
|
if (isset($map[$key])) {
|
3610
|
$uri = $map[$key];
|
3611
|
}
|
3612
|
|
3613
|
if (empty($uri) || !file_exists($uri)) {
|
3614
|
// Build aggregate CSS file.
|
3615
|
foreach ($css as $stylesheet) {
|
3616
|
// Only 'file' stylesheets can be aggregated.
|
3617
|
if ($stylesheet['type'] == 'file') {
|
3618
|
$contents = drupal_load_stylesheet($stylesheet['data'], TRUE);
|
3619
|
|
3620
|
// Build the base URL of this CSS file: start with the full URL.
|
3621
|
$css_base_url = file_create_url($stylesheet['data']);
|
3622
|
// Move to the parent.
|
3623
|
$css_base_url = substr($css_base_url, 0, strrpos($css_base_url, '/'));
|
3624
|
// Simplify to a relative URL if the stylesheet URL starts with the
|
3625
|
// base URL of the website.
|
3626
|
if (substr($css_base_url, 0, strlen($GLOBALS['base_root'])) == $GLOBALS['base_root']) {
|
3627
|
$css_base_url = substr($css_base_url, strlen($GLOBALS['base_root']));
|
3628
|
}
|
3629
|
|
3630
|
_drupal_build_css_path(NULL, $css_base_url . '/');
|
3631
|
// Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
|
3632
|
$data .= preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);
|
3633
|
}
|
3634
|
}
|
3635
|
|
3636
|
// Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
|
3637
|
// @import rules must proceed any other style, so we move those to the top.
|
3638
|
$regexp = '/@import[^;]+;/i';
|
3639
|
preg_match_all($regexp, $data, $matches);
|
3640
|
$data = preg_replace($regexp, '', $data);
|
3641
|
$data = implode('', $matches[0]) . $data;
|
3642
|
|
3643
|
// Prefix filename to prevent blocking by firewalls which reject files
|
3644
|
// starting with "ad*".
|
3645
|
$filename = 'css_' . drupal_hash_base64($data) . '.css';
|
3646
|
// Create the css/ within the files folder.
|
3647
|
$csspath = 'public://css';
|
3648
|
$uri = $csspath . '/' . $filename;
|
3649
|
// Create the CSS file.
|
3650
|
file_prepare_directory($csspath, FILE_CREATE_DIRECTORY);
|
3651
|
if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
|
3652
|
return FALSE;
|
3653
|
}
|
3654
|
// If CSS gzip compression is enabled, clean URLs are enabled (which means
|
3655
|
// that rewrite rules are working) and the zlib extension is available then
|
3656
|
// create a gzipped version of this file. This file is served conditionally
|
3657
|
// to browsers that accept gzip using .htaccess rules.
|
3658
|
if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
|
3659
|
if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
|
3660
|
return FALSE;
|
3661
|
}
|
3662
|
}
|
3663
|
// Save the updated map.
|
3664
|
$map[$key] = $uri;
|
3665
|
variable_set('drupal_css_cache_files', $map);
|
3666
|
}
|
3667
|
return $uri;
|
3668
|
}
|
3669
|
|
3670
|
/**
|
3671
|
* Prefixes all paths within a CSS file for drupal_build_css_cache().
|
3672
|
*/
|
3673
|
function _drupal_build_css_path($matches, $base = NULL) {
|
3674
|
$_base = &drupal_static(__FUNCTION__);
|
3675
|
// Store base path for preg_replace_callback.
|
3676
|
if (isset($base)) {
|
3677
|
$_base = $base;
|
3678
|
}
|
3679
|
|
3680
|
// Prefix with base and remove '../' segments where possible.
|
3681
|
$path = $_base . $matches[1];
|
3682
|
$last = '';
|
3683
|
while ($path != $last) {
|
3684
|
$last = $path;
|
3685
|
$path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
|
3686
|
}
|
3687
|
return 'url(' . $path . ')';
|
3688
|
}
|
3689
|
|
3690
|
/**
|
3691
|
* Loads the stylesheet and resolves all @import commands.
|
3692
|
*
|
3693
|
* Loads a stylesheet and replaces @import commands with the contents of the
|
3694
|
* imported file. Use this instead of file_get_contents when processing
|
3695
|
* stylesheets.
|
3696
|
*
|
3697
|
* The returned contents are compressed removing white space and comments only
|
3698
|
* when CSS aggregation is enabled. This optimization will not apply for
|
3699
|
* color.module enabled themes with CSS aggregation turned off.
|
3700
|
*
|
3701
|
* @param $file
|
3702
|
* Name of the stylesheet to be processed.
|
3703
|
* @param $optimize
|
3704
|
* Defines if CSS contents should be compressed or not.
|
3705
|
* @param $reset_basepath
|
3706
|
* Used internally to facilitate recursive resolution of @import commands.
|
3707
|
*
|
3708
|
* @return
|
3709
|
* Contents of the stylesheet, including any resolved @import commands.
|
3710
|
*/
|
3711
|
function drupal_load_stylesheet($file, $optimize = NULL, $reset_basepath = TRUE) {
|
3712
|
// These statics are not cache variables, so we don't use drupal_static().
|
3713
|
static $_optimize, $basepath;
|
3714
|
if ($reset_basepath) {
|
3715
|
$basepath = '';
|
3716
|
}
|
3717
|
// Store the value of $optimize for preg_replace_callback with nested
|
3718
|
// @import loops.
|
3719
|
if (isset($optimize)) {
|
3720
|
$_optimize = $optimize;
|
3721
|
}
|
3722
|
|
3723
|
// Stylesheets are relative one to each other. Start by adding a base path
|
3724
|
// prefix provided by the parent stylesheet (if necessary).
|
3725
|
if ($basepath && !file_uri_scheme($file)) {
|
3726
|
$file = $basepath . '/' . $file;
|
3727
|
}
|
3728
|
// Store the parent base path to restore it later.
|
3729
|
$parent_base_path = $basepath;
|
3730
|
// Set the current base path to process possible child imports.
|
3731
|
$basepath = dirname($file);
|
3732
|
|
3733
|
// Load the CSS stylesheet. We suppress errors because themes may specify
|
3734
|
// stylesheets in their .info file that don't exist in the theme's path,
|
3735
|
// but are merely there to disable certain module CSS files.
|
3736
|
$content = '';
|
3737
|
if ($contents = @file_get_contents($file)) {
|
3738
|
// Return the processed stylesheet.
|
3739
|
$content = drupal_load_stylesheet_content($contents, $_optimize);
|
3740
|
}
|
3741
|
|
3742
|
// Restore the parent base path as the file and its childen are processed.
|
3743
|
$basepath = $parent_base_path;
|
3744
|
return $content;
|
3745
|
}
|
3746
|
|
3747
|
/**
|
3748
|
* Processes the contents of a stylesheet for aggregation.
|
3749
|
*
|
3750
|
* @param $contents
|
3751
|
* The contents of the stylesheet.
|
3752
|
* @param $optimize
|
3753
|
* (optional) Boolean whether CSS contents should be minified. Defaults to
|
3754
|
* FALSE.
|
3755
|
*
|
3756
|
* @return
|
3757
|
* Contents of the stylesheet including the imported stylesheets.
|
3758
|
*/
|
3759
|
function drupal_load_stylesheet_content($contents, $optimize = FALSE) {
|
3760
|
// Remove multiple charset declarations for standards compliance (and fixing Safari problems).
|
3761
|
$contents = preg_replace('/^@charset\s+[\'"](\S*?)\b[\'"];/i', '', $contents);
|
3762
|
|
3763
|
if ($optimize) {
|
3764
|
// Perform some safe CSS optimizations.
|
3765
|
// Regexp to match comment blocks.
|
3766
|
$comment = '/\*[^*]*\*+(?:[^/*][^*]*\*+)*/';
|
3767
|
// Regexp to match double quoted strings.
|
3768
|
$double_quot = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
|
3769
|
// Regexp to match single quoted strings.
|
3770
|
$single_quot = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'";
|
3771
|
// Strip all comment blocks, but keep double/single quoted strings.
|
3772
|
$contents = preg_replace(
|
3773
|
"<($double_quot|$single_quot)|$comment>Ss",
|
3774
|
"$1",
|
3775
|
$contents
|
3776
|
);
|
3777
|
// Remove certain whitespace.
|
3778
|
// There are different conditions for removing leading and trailing
|
3779
|
// whitespace.
|
3780
|
// @see http://php.net/manual/regexp.reference.subpatterns.php
|
3781
|
$contents = preg_replace('<
|
3782
|
# Strip leading and trailing whitespace.
|
3783
|
\s*([@{};,])\s*
|
3784
|
# Strip only leading whitespace from:
|
3785
|
# - Closing parenthesis: Retain "@media (bar) and foo".
|
3786
|
| \s+([\)])
|
3787
|
# Strip only trailing whitespace from:
|
3788
|
# - Opening parenthesis: Retain "@media (bar) and foo".
|
3789
|
# - Colon: Retain :pseudo-selectors.
|
3790
|
| ([\(:])\s+
|
3791
|
>xS',
|
3792
|
// Only one of the three capturing groups will match, so its reference
|
3793
|
// will contain the wanted value and the references for the
|
3794
|
// two non-matching groups will be replaced with empty strings.
|
3795
|
'$1$2$3',
|
3796
|
$contents
|
3797
|
);
|
3798
|
// End the file with a new line.
|
3799
|
$contents = trim($contents);
|
3800
|
$contents .= "\n";
|
3801
|
}
|
3802
|
|
3803
|
// Replaces @import commands with the actual stylesheet content.
|
3804
|
// This happens recursively but omits external files.
|
3805
|
$contents = preg_replace_callback('/@import\s*(?:url\(\s*)?[\'"]?(?![a-z]+:)([^\'"\()]+)[\'"]?\s*\)?\s*;/', '_drupal_load_stylesheet', $contents);
|
3806
|
return $contents;
|
3807
|
}
|
3808
|
|
3809
|
/**
|
3810
|
* Loads stylesheets recursively and returns contents with corrected paths.
|
3811
|
*
|
3812
|
* This function is used for recursive loading of stylesheets and
|
3813
|
* returns the stylesheet content with all url() paths corrected.
|
3814
|
*/
|
3815
|
function _drupal_load_stylesheet($matches) {
|
3816
|
$filename = $matches[1];
|
3817
|
// Load the imported stylesheet and replace @import commands in there as well.
|
3818
|
$file = drupal_load_stylesheet($filename, NULL, FALSE);
|
3819
|
|
3820
|
// Determine the file's directory.
|
3821
|
$directory = dirname($filename);
|
3822
|
// If the file is in the current directory, make sure '.' doesn't appear in
|
3823
|
// the url() path.
|
3824
|
$directory = $directory == '.' ? '' : $directory .'/';
|
3825
|
|
3826
|
// Alter all internal url() paths. Leave external paths alone. We don't need
|
3827
|
// to normalize absolute paths here (i.e. remove folder/... segments) because
|
3828
|
// that will be done later.
|
3829
|
return preg_replace('/url\(\s*([\'"]?)(?![a-z]+:|\/+)([^\'")]+)([\'"]?)\s*\)/i', 'url(\1' . $directory . '\2\3)', $file);
|
3830
|
}
|
3831
|
|
3832
|
/**
|
3833
|
* Deletes old cached CSS files.
|
3834
|
*/
|
3835
|
function drupal_clear_css_cache() {
|
3836
|
variable_del('drupal_css_cache_files');
|
3837
|
file_scan_directory('public://css', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
|
3838
|
}
|
3839
|
|
3840
|
/**
|
3841
|
* Callback to delete files modified more than a set time ago.
|
3842
|
*/
|
3843
|
function drupal_delete_file_if_stale($uri) {
|
3844
|
// Default stale file threshold is 30 days.
|
3845
|
if (REQUEST_TIME - filemtime($uri) > variable_get('drupal_stale_file_threshold', 2592000)) {
|
3846
|
file_unmanaged_delete($uri);
|
3847
|
}
|
3848
|
}
|
3849
|
|
3850
|
/**
|
3851
|
* Prepares a string for use as a CSS identifier (element, class, or ID name).
|
3852
|
*
|
3853
|
* http://www.w3.org/TR/CSS21/syndata.html#characters shows the syntax for valid
|
3854
|
* CSS identifiers (including element names, classes, and IDs in selectors.)
|
3855
|
*
|
3856
|
* @param $identifier
|
3857
|
* The identifier to clean.
|
3858
|
* @param $filter
|
3859
|
* An array of string replacements to use on the identifier.
|
3860
|
*
|
3861
|
* @return
|
3862
|
* The cleaned identifier.
|
3863
|
*/
|
3864
|
function drupal_clean_css_identifier($identifier, $filter = array(' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '')) {
|
3865
|
// By default, we filter using Drupal's coding standards.
|
3866
|
$identifier = strtr($identifier, $filter);
|
3867
|
|
3868
|
// Valid characters in a CSS identifier are:
|
3869
|
// - the hyphen (U+002D)
|
3870
|
// - a-z (U+0030 - U+0039)
|
3871
|
// - A-Z (U+0041 - U+005A)
|
3872
|
// - the underscore (U+005F)
|
3873
|
// - 0-9 (U+0061 - U+007A)
|
3874
|
// - ISO 10646 characters U+00A1 and higher
|
3875
|
// We strip out any character not in the above list.
|
3876
|
$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);
|
3877
|
|
3878
|
return $identifier;
|
3879
|
}
|
3880
|
|
3881
|
/**
|
3882
|
* Prepares a string for use as a valid class name.
|
3883
|
*
|
3884
|
* Do not pass one string containing multiple classes as they will be
|
3885
|
* incorrectly concatenated with dashes, i.e. "one two" will become "one-two".
|
3886
|
*
|
3887
|
* @param $class
|
3888
|
* The class name to clean.
|
3889
|
*
|
3890
|
* @return
|
3891
|
* The cleaned class name.
|
3892
|
*/
|
3893
|
function drupal_html_class($class) {
|
3894
|
// The output of this function will never change, so this uses a normal
|
3895
|
// static instead of drupal_static().
|
3896
|
static $classes = array();
|
3897
|
|
3898
|
if (!isset($classes[$class])) {
|
3899
|
$classes[$class] = drupal_clean_css_identifier(drupal_strtolower($class));
|
3900
|
}
|
3901
|
return $classes[$class];
|
3902
|
}
|
3903
|
|
3904
|
/**
|
3905
|
* Prepares a string for use as a valid HTML ID and guarantees uniqueness.
|
3906
|
*
|
3907
|
* This function ensures that each passed HTML ID value only exists once on the
|
3908
|
* page. By tracking the already returned ids, this function enables forms,
|
3909
|
* blocks, and other content to be output multiple times on the same page,
|
3910
|
* without breaking (X)HTML validation.
|
3911
|
*
|
3912
|
* For already existing IDs, a counter is appended to the ID string. Therefore,
|
3913
|
* JavaScript and CSS code should not rely on any value that was generated by
|
3914
|
* this function and instead should rely on manually added CSS classes or
|
3915
|
* similarly reliable constructs.
|
3916
|
*
|
3917
|
* Two consecutive hyphens separate the counter from the original ID. To manage
|
3918
|
* uniqueness across multiple Ajax requests on the same page, Ajax requests
|
3919
|
* POST an array of all IDs currently present on the page, which are used to
|
3920
|
* prime this function's cache upon first invocation.
|
3921
|
*
|
3922
|
* To allow reverse-parsing of IDs submitted via Ajax, any multiple consecutive
|
3923
|
* hyphens in the originally passed $id are replaced with a single hyphen.
|
3924
|
*
|
3925
|
* @param $id
|
3926
|
* The ID to clean.
|
3927
|
*
|
3928
|
* @return
|
3929
|
* The cleaned ID.
|
3930
|
*/
|
3931
|
function drupal_html_id($id) {
|
3932
|
// If this is an Ajax request, then content returned by this page request will
|
3933
|
// be merged with content already on the base page. The HTML IDs must be
|
3934
|
// unique for the fully merged content. Therefore, initialize $seen_ids to
|
3935
|
// take into account IDs that are already in use on the base page.
|
3936
|
$seen_ids_init = &drupal_static(__FUNCTION__ . ':init');
|
3937
|
if (!isset($seen_ids_init)) {
|
3938
|
// Ideally, Drupal would provide an API to persist state information about
|
3939
|
// prior page requests in the database, and we'd be able to add this
|
3940
|
// function's $seen_ids static variable to that state information in order
|
3941
|
// to have it properly initialized for this page request. However, no such
|
3942
|
// page state API exists, so instead, ajax.js adds all of the in-use HTML
|
3943
|
// IDs to the POST data of Ajax submissions. Direct use of $_POST is
|
3944
|
// normally not recommended as it could open up security risks, but because
|
3945
|
// the raw POST data is cast to a number before being returned by this
|
3946
|
// function, this usage is safe.
|
3947
|
if (empty($_POST['ajax_html_ids'])) {
|
3948
|
$seen_ids_init = array();
|
3949
|
}
|
3950
|
else {
|
3951
|
// This function ensures uniqueness by appending a counter to the base id
|
3952
|
// requested by the calling function after the first occurrence of that
|
3953
|
// requested id. $_POST['ajax_html_ids'] contains the ids as they were
|
3954
|
// returned by this function, potentially with the appended counter, so
|
3955
|
// we parse that to reconstruct the $seen_ids array.
|
3956
|
if (isset($_POST['ajax_html_ids'][0]) && strpos($_POST['ajax_html_ids'][0], ',') === FALSE) {
|
3957
|
$ajax_html_ids = $_POST['ajax_html_ids'];
|
3958
|
}
|
3959
|
else {
|
3960
|
// jquery.form.js may send the server a comma-separated string as the
|
3961
|
// first element of an array (see http://drupal.org/node/1575060), so
|
3962
|
// we need to convert it to an array in that case.
|
3963
|
$ajax_html_ids = explode(',', $_POST['ajax_html_ids'][0]);
|
3964
|
}
|
3965
|
foreach ($ajax_html_ids as $seen_id) {
|
3966
|
// We rely on '--' being used solely for separating a base id from the
|
3967
|
// counter, which this function ensures when returning an id.
|
3968
|
$parts = explode('--', $seen_id, 2);
|
3969
|
if (!empty($parts[1]) && is_numeric($parts[1])) {
|
3970
|
list($seen_id, $i) = $parts;
|
3971
|
}
|
3972
|
else {
|
3973
|
$i = 1;
|
3974
|
}
|
3975
|
if (!isset($seen_ids_init[$seen_id]) || ($i > $seen_ids_init[$seen_id])) {
|
3976
|
$seen_ids_init[$seen_id] = $i;
|
3977
|
}
|
3978
|
}
|
3979
|
}
|
3980
|
}
|
3981
|
$seen_ids = &drupal_static(__FUNCTION__, $seen_ids_init);
|
3982
|
|
3983
|
$id = strtr(drupal_strtolower($id), array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
|
3984
|
|
3985
|
// As defined in http://www.w3.org/TR/html4/types.html#type-name, HTML IDs can
|
3986
|
// only contain letters, digits ([0-9]), hyphens ("-"), underscores ("_"),
|
3987
|
// colons (":"), and periods ("."). We strip out any character not in that
|
3988
|
// list. Note that the CSS spec doesn't allow colons or periods in identifiers
|
3989
|
// (http://www.w3.org/TR/CSS21/syndata.html#characters), so we strip those two
|
3990
|
// characters as well.
|
3991
|
$id = preg_replace('/[^A-Za-z0-9\-_]/', '', $id);
|
3992
|
|
3993
|
// Removing multiple consecutive hyphens.
|
3994
|
$id = preg_replace('/\-+/', '-', $id);
|
3995
|
// Ensure IDs are unique by appending a counter after the first occurrence.
|
3996
|
// The counter needs to be appended with a delimiter that does not exist in
|
3997
|
// the base ID. Requiring a unique delimiter helps ensure that we really do
|
3998
|
// return unique IDs and also helps us re-create the $seen_ids array during
|
3999
|
// Ajax requests.
|
4000
|
if (isset($seen_ids[$id])) {
|
4001
|
$id = $id . '--' . ++$seen_ids[$id];
|
4002
|
}
|
4003
|
else {
|
4004
|
$seen_ids[$id] = 1;
|
4005
|
}
|
4006
|
|
4007
|
return $id;
|
4008
|
}
|
4009
|
|
4010
|
/**
|
4011
|
* Provides a standard HTML class name that identifies a page region.
|
4012
|
*
|
4013
|
* It is recommended that template preprocess functions apply this class to any
|
4014
|
* page region that is output by the theme (Drupal core already handles this in
|
4015
|
* the standard template preprocess implementation). Standardizing the class
|
4016
|
* names in this way allows modules to implement certain features, such as
|
4017
|
* drag-and-drop or dynamic Ajax loading, in a theme-independent way.
|
4018
|
*
|
4019
|
* @param $region
|
4020
|
* The name of the page region (for example, 'page_top' or 'content').
|
4021
|
*
|
4022
|
* @return
|
4023
|
* An HTML class that identifies the region (for example, 'region-page-top'
|
4024
|
* or 'region-content').
|
4025
|
*
|
4026
|
* @see template_preprocess_region()
|
4027
|
*/
|
4028
|
function drupal_region_class($region) {
|
4029
|
return drupal_html_class("region-$region");
|
4030
|
}
|
4031
|
|
4032
|
/**
|
4033
|
* Adds a JavaScript file, setting, or inline code to the page.
|
4034
|
*
|
4035
|
* The behavior of this function depends on the parameters it is called with.
|
4036
|
* Generally, it handles the addition of JavaScript to the page, either as
|
4037
|
* reference to an existing file or as inline code. The following actions can be
|
4038
|
* performed using this function:
|
4039
|
* - Add a file ('file'): Adds a reference to a JavaScript file to the page.
|
4040
|
* - Add inline JavaScript code ('inline'): Executes a piece of JavaScript code
|
4041
|
* on the current page by placing the code directly in the page (for example,
|
4042
|
* to tell the user that a new message arrived, by opening a pop up, alert
|
4043
|
* box, etc.). This should only be used for JavaScript that cannot be executed
|
4044
|
* from a file. When adding inline code, make sure that you are not relying on
|
4045
|
* $() being the jQuery function. Wrap your code in
|
4046
|
* @code (function ($) {... })(jQuery); @endcode
|
4047
|
* or use jQuery() instead of $().
|
4048
|
* - Add external JavaScript ('external'): Allows the inclusion of external
|
4049
|
* JavaScript files that are not hosted on the local server. Note that these
|
4050
|
* external JavaScript references do not get aggregated when preprocessing is
|
4051
|
* on.
|
4052
|
* - Add settings ('setting'): Adds settings to Drupal's global storage of
|
4053
|
* JavaScript settings. Per-page settings are required by some modules to
|
4054
|
* function properly. All settings will be accessible at Drupal.settings.
|
4055
|
*
|
4056
|
* Examples:
|
4057
|
* @code
|
4058
|
* drupal_add_js('misc/collapse.js');
|
4059
|
* drupal_add_js('misc/collapse.js', 'file');
|
4060
|
* drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
|
4061
|
* drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
|
4062
|
* array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
|
4063
|
* );
|
4064
|
* drupal_add_js('http://example.com/example.js', 'external');
|
4065
|
* drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');
|
4066
|
* @endcode
|
4067
|
*
|
4068
|
* Calling drupal_static_reset('drupal_add_js') will clear all JavaScript added
|
4069
|
* so far.
|
4070
|
*
|
4071
|
* If JavaScript aggregation is enabled, all JavaScript files added with
|
4072
|
* $options['preprocess'] set to TRUE will be merged into one aggregate file.
|
4073
|
* Preprocessed inline JavaScript will not be aggregated into this single file.
|
4074
|
* Externally hosted JavaScripts are never aggregated.
|
4075
|
*
|
4076
|
* The reason for aggregating the files is outlined quite thoroughly here:
|
4077
|
* http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
|
4078
|
* to request overhead, one bigger file just loads faster than two smaller ones
|
4079
|
* half its size."
|
4080
|
*
|
4081
|
* $options['preprocess'] should be only set to TRUE when a file is required for
|
4082
|
* all typical visitors and most pages of a site. It is critical that all
|
4083
|
* preprocessed files are added unconditionally on every page, even if the
|
4084
|
* files are not needed on a page. This is normally done by calling
|
4085
|
* drupal_add_js() in a hook_init() implementation.
|
4086
|
*
|
4087
|
* Non-preprocessed files should only be added to the page when they are
|
4088
|
* actually needed.
|
4089
|
*
|
4090
|
* @param $data
|
4091
|
* (optional) If given, the value depends on the $options parameter, or
|
4092
|
* $options['type'] if $options is passed as an associative array:
|
4093
|
* - 'file': Path to the file relative to base_path().
|
4094
|
* - 'inline': The JavaScript code that should be placed in the given scope.
|
4095
|
* - 'external': The absolute path to an external JavaScript file that is not
|
4096
|
* hosted on the local server. These files will not be aggregated if
|
4097
|
* JavaScript aggregation is enabled.
|
4098
|
* - 'setting': An associative array with configuration options. The array is
|
4099
|
* merged directly into Drupal.settings. All modules should wrap their
|
4100
|
* actual configuration settings in another variable to prevent conflicts in
|
4101
|
* the Drupal.settings namespace. Items added with a string key will replace
|
4102
|
* existing settings with that key; items with numeric array keys will be
|
4103
|
* added to the existing settings array.
|
4104
|
* @param $options
|
4105
|
* (optional) A string defining the type of JavaScript that is being added in
|
4106
|
* the $data parameter ('file'/'setting'/'inline'/'external'), or an
|
4107
|
* associative array. JavaScript settings should always pass the string
|
4108
|
* 'setting' only. Other types can have the following elements in the array:
|
4109
|
* - type: The type of JavaScript that is to be added to the page. Allowed
|
4110
|
* values are 'file', 'inline', 'external' or 'setting'. Defaults
|
4111
|
* to 'file'.
|
4112
|
* - scope: The location in which you want to place the script. Possible
|
4113
|
* values are 'header' or 'footer'. If your theme implements different
|
4114
|
* regions, you can also use these. Defaults to 'header'.
|
4115
|
* - group: A number identifying the group in which to add the JavaScript.
|
4116
|
* Available constants are:
|
4117
|
* - JS_LIBRARY: Any libraries, settings, or jQuery plugins.
|
4118
|
* - JS_DEFAULT: Any module-layer JavaScript.
|
4119
|
* - JS_THEME: Any theme-layer JavaScript.
|
4120
|
* The group number serves as a weight: JavaScript within a lower weight
|
4121
|
* group is presented on the page before JavaScript within a higher weight
|
4122
|
* group.
|
4123
|
* - every_page: For optimal front-end performance when aggregation is
|
4124
|
* enabled, this should be set to TRUE if the JavaScript is present on every
|
4125
|
* page of the website for users for whom it is present at all. This
|
4126
|
* defaults to FALSE. It is set to TRUE for JavaScript files that are added
|
4127
|
* via module and theme .info files. Modules that add JavaScript within
|
4128
|
* hook_init() implementations, or from other code that ensures that the
|
4129
|
* JavaScript is added to all website pages, should also set this flag to
|
4130
|
* TRUE. All JavaScript files within the same group and that have the
|
4131
|
* 'every_page' flag set to TRUE and do not have 'preprocess' set to FALSE
|
4132
|
* are aggregated together into a single aggregate file, and that aggregate
|
4133
|
* file can be reused across a user's entire site visit, leading to faster
|
4134
|
* navigation between pages. However, JavaScript that is only needed on
|
4135
|
* pages less frequently visited, can be added by code that only runs for
|
4136
|
* those particular pages, and that code should not set the 'every_page'
|
4137
|
* flag. This minimizes the size of the aggregate file that the user needs
|
4138
|
* to download when first visiting the website. JavaScript without the
|
4139
|
* 'every_page' flag is aggregated into a separate aggregate file. This
|
4140
|
* other aggregate file is likely to change from page to page, and each new
|
4141
|
* aggregate file needs to be downloaded when first encountered, so it
|
4142
|
* should be kept relatively small by ensuring that most commonly needed
|
4143
|
* JavaScript is added to every page.
|
4144
|
* - weight: A number defining the order in which the JavaScript is added to
|
4145
|
* the page relative to other JavaScript with the same 'scope', 'group',
|
4146
|
* and 'every_page' value. In some cases, the order in which the JavaScript
|
4147
|
* is presented on the page is very important. jQuery, for example, must be
|
4148
|
* added to the page before any jQuery code is run, so jquery.js uses the
|
4149
|
* JS_LIBRARY group and a weight of -20, jquery.once.js (a library drupal.js
|
4150
|
* depends on) uses the JS_LIBRARY group and a weight of -19, drupal.js uses
|
4151
|
* the JS_LIBRARY group and a weight of -1, other libraries use the
|
4152
|
* JS_LIBRARY group and a weight of 0 or higher, and all other scripts use
|
4153
|
* one of the other group constants. The exact ordering of JavaScript is as
|
4154
|
* follows:
|
4155
|
* - First by scope, with 'header' first, 'footer' last, and any other
|
4156
|
* scopes provided by a custom theme coming in between, as determined by
|
4157
|
* the theme.
|
4158
|
* - Then by group.
|
4159
|
* - Then by the 'every_page' flag, with TRUE coming before FALSE.
|
4160
|
* - Then by weight.
|
4161
|
* - Then by the order in which the JavaScript was added. For example, all
|
4162
|
* else being the same, JavaScript added by a call to drupal_add_js() that
|
4163
|
* happened later in the page request gets added to the page after one for
|
4164
|
* which drupal_add_js() happened earlier in the page request.
|
4165
|
* - requires_jquery: Set this to FALSE if the JavaScript you are adding does
|
4166
|
* not have a dependency on jQuery. Defaults to TRUE, except for JavaScript
|
4167
|
* settings where it defaults to FALSE. This is used on sites that have the
|
4168
|
* 'javascript_always_use_jquery' variable set to FALSE; on those sites, if
|
4169
|
* all the JavaScript added to the page by drupal_add_js() does not have a
|
4170
|
* dependency on jQuery, then for improved front-end performance Drupal
|
4171
|
* will not add jQuery and related libraries and settings to the page.
|
4172
|
* - defer: If set to TRUE, the defer attribute is set on the <script>
|
4173
|
* tag. Defaults to FALSE.
|
4174
|
* - cache: If set to FALSE, the JavaScript file is loaded anew on every page
|
4175
|
* call; in other words, it is not cached. Used only when 'type' references
|
4176
|
* a JavaScript file. Defaults to TRUE.
|
4177
|
* - preprocess: If TRUE and JavaScript aggregation is enabled, the script
|
4178
|
* file will be aggregated. Defaults to TRUE.
|
4179
|
*
|
4180
|
* @return
|
4181
|
* The current array of JavaScript files, settings, and in-line code,
|
4182
|
* including Drupal defaults, anything previously added with calls to
|
4183
|
* drupal_add_js(), and this function call's additions.
|
4184
|
*
|
4185
|
* @see drupal_get_js()
|
4186
|
*/
|
4187
|
function drupal_add_js($data = NULL, $options = NULL) {
|
4188
|
$javascript = &drupal_static(__FUNCTION__, array());
|
4189
|
$jquery_added = &drupal_static(__FUNCTION__ . ':jquery_added', FALSE);
|
4190
|
|
4191
|
// If the $javascript variable has been reset with drupal_static_reset(),
|
4192
|
// jQuery and related files will have been removed from the list, so set the
|
4193
|
// variable back to FALSE to indicate they have not yet been added.
|
4194
|
if (empty($javascript)) {
|
4195
|
$jquery_added = FALSE;
|
4196
|
}
|
4197
|
|
4198
|
// Construct the options, taking the defaults into consideration.
|
4199
|
if (isset($options)) {
|
4200
|
if (!is_array($options)) {
|
4201
|
$options = array('type' => $options);
|
4202
|
}
|
4203
|
}
|
4204
|
else {
|
4205
|
$options = array();
|
4206
|
}
|
4207
|
if (isset($options['type']) && $options['type'] == 'setting') {
|
4208
|
$options += array('requires_jquery' => FALSE);
|
4209
|
}
|
4210
|
$options += drupal_js_defaults($data);
|
4211
|
|
4212
|
// Preprocess can only be set if caching is enabled.
|
4213
|
$options['preprocess'] = $options['cache'] ? $options['preprocess'] : FALSE;
|
4214
|
|
4215
|
// Tweak the weight so that files of the same weight are included in the
|
4216
|
// order of the calls to drupal_add_js().
|
4217
|
$options['weight'] += count($javascript) / 1000;
|
4218
|
|
4219
|
if (isset($data)) {
|
4220
|
// Add jquery.js, drupal.js, and related files and settings if they have
|
4221
|
// not been added yet. However, if the 'javascript_always_use_jquery'
|
4222
|
// variable is set to FALSE (indicating that the site does not want jQuery
|
4223
|
// automatically added on all pages) then only add it if a file or setting
|
4224
|
// that requires jQuery is being added also.
|
4225
|
if (!$jquery_added && (variable_get('javascript_always_use_jquery', TRUE) || $options['requires_jquery'])) {
|
4226
|
$jquery_added = TRUE;
|
4227
|
// url() generates the prefix using hook_url_outbound_alter(). Instead of
|
4228
|
// running the hook_url_outbound_alter() again here, extract the prefix
|
4229
|
// from url().
|
4230
|
url('', array('prefix' => &$prefix));
|
4231
|
$default_javascript = array(
|
4232
|
'settings' => array(
|
4233
|
'data' => array(
|
4234
|
array('basePath' => base_path()),
|
4235
|
array('pathPrefix' => empty($prefix) ? '' : $prefix),
|
4236
|
),
|
4237
|
'type' => 'setting',
|
4238
|
'scope' => 'header',
|
4239
|
'group' => JS_LIBRARY,
|
4240
|
'every_page' => TRUE,
|
4241
|
'weight' => 0,
|
4242
|
),
|
4243
|
'misc/drupal.js' => array(
|
4244
|
'data' => 'misc/drupal.js',
|
4245
|
'type' => 'file',
|
4246
|
'scope' => 'header',
|
4247
|
'group' => JS_LIBRARY,
|
4248
|
'every_page' => TRUE,
|
4249
|
'weight' => -1,
|
4250
|
'requires_jquery' => TRUE,
|
4251
|
'preprocess' => TRUE,
|
4252
|
'cache' => TRUE,
|
4253
|
'defer' => FALSE,
|
4254
|
),
|
4255
|
);
|
4256
|
$javascript = drupal_array_merge_deep($javascript, $default_javascript);
|
4257
|
// Register all required libraries.
|
4258
|
drupal_add_library('system', 'jquery', TRUE);
|
4259
|
drupal_add_library('system', 'jquery.once', TRUE);
|
4260
|
}
|
4261
|
|
4262
|
switch ($options['type']) {
|
4263
|
case 'setting':
|
4264
|
// All JavaScript settings are placed in the header of the page with
|
4265
|
// the library weight so that inline scripts appear afterwards.
|
4266
|
$javascript['settings']['data'][] = $data;
|
4267
|
break;
|
4268
|
|
4269
|
case 'inline':
|
4270
|
$javascript[] = $options;
|
4271
|
break;
|
4272
|
|
4273
|
default: // 'file' and 'external'
|
4274
|
// Local and external files must keep their name as the associative key
|
4275
|
// so the same JavaScript file is not added twice.
|
4276
|
$javascript[$options['data']] = $options;
|
4277
|
}
|
4278
|
}
|
4279
|
return $javascript;
|
4280
|
}
|
4281
|
|
4282
|
/**
|
4283
|
* Constructs an array of the defaults that are used for JavaScript items.
|
4284
|
*
|
4285
|
* @param $data
|
4286
|
* (optional) The default data parameter for the JavaScript item array.
|
4287
|
*
|
4288
|
* @see drupal_get_js()
|
4289
|
* @see drupal_add_js()
|
4290
|
*/
|
4291
|
function drupal_js_defaults($data = NULL) {
|
4292
|
return array(
|
4293
|
'type' => 'file',
|
4294
|
'group' => JS_DEFAULT,
|
4295
|
'every_page' => FALSE,
|
4296
|
'weight' => 0,
|
4297
|
'requires_jquery' => TRUE,
|
4298
|
'scope' => 'header',
|
4299
|
'cache' => TRUE,
|
4300
|
'defer' => FALSE,
|
4301
|
'preprocess' => TRUE,
|
4302
|
'version' => NULL,
|
4303
|
'data' => $data,
|
4304
|
);
|
4305
|
}
|
4306
|
|
4307
|
/**
|
4308
|
* Returns a themed presentation of all JavaScript code for the current page.
|
4309
|
*
|
4310
|
* References to JavaScript files are placed in a certain order: first, all
|
4311
|
* 'core' files, then all 'module' and finally all 'theme' JavaScript files
|
4312
|
* are added to the page. Then, all settings are output, followed by 'inline'
|
4313
|
* JavaScript code. If running update.php, all preprocessing is disabled.
|
4314
|
*
|
4315
|
* Note that hook_js_alter(&$javascript) is called during this function call
|
4316
|
* to allow alterations of the JavaScript during its presentation. Calls to
|
4317
|
* drupal_add_js() from hook_js_alter() will not be added to the output
|
4318
|
* presentation. The correct way to add JavaScript during hook_js_alter()
|
4319
|
* is to add another element to the $javascript array, deriving from
|
4320
|
* drupal_js_defaults(). See locale_js_alter() for an example of this.
|
4321
|
*
|
4322
|
* @param $scope
|
4323
|
* (optional) The scope for which the JavaScript rules should be returned.
|
4324
|
* Defaults to 'header'.
|
4325
|
* @param $javascript
|
4326
|
* (optional) An array with all JavaScript code. Defaults to the default
|
4327
|
* JavaScript array for the given scope.
|
4328
|
* @param $skip_alter
|
4329
|
* (optional) If set to TRUE, this function skips calling drupal_alter() on
|
4330
|
* $javascript, useful when the calling function passes a $javascript array
|
4331
|
* that has already been altered.
|
4332
|
*
|
4333
|
* @return
|
4334
|
* All JavaScript code segments and includes for the scope as HTML tags.
|
4335
|
*
|
4336
|
* @see drupal_add_js()
|
4337
|
* @see locale_js_alter()
|
4338
|
* @see drupal_js_defaults()
|
4339
|
*/
|
4340
|
function drupal_get_js($scope = 'header', $javascript = NULL, $skip_alter = FALSE) {
|
4341
|
if (!isset($javascript)) {
|
4342
|
$javascript = drupal_add_js();
|
4343
|
}
|
4344
|
|
4345
|
// If no JavaScript items have been added, or if the only JavaScript items
|
4346
|
// that have been added are JavaScript settings (which don't do anything
|
4347
|
// without any JavaScript code to use them), then no JavaScript code should
|
4348
|
// be added to the page.
|
4349
|
if (empty($javascript) || (isset($javascript['settings']) && count($javascript) == 1)) {
|
4350
|
return '';
|
4351
|
}
|
4352
|
|
4353
|
// Allow modules to alter the JavaScript.
|
4354
|
if (!$skip_alter) {
|
4355
|
drupal_alter('js', $javascript);
|
4356
|
}
|
4357
|
|
4358
|
// Filter out elements of the given scope.
|
4359
|
$items = array();
|
4360
|
foreach ($javascript as $key => $item) {
|
4361
|
if ($item['scope'] == $scope) {
|
4362
|
$items[$key] = $item;
|
4363
|
}
|
4364
|
}
|
4365
|
|
4366
|
$output = '';
|
4367
|
// The index counter is used to keep aggregated and non-aggregated files in
|
4368
|
// order by weight.
|
4369
|
$index = 1;
|
4370
|
$processed = array();
|
4371
|
$files = array();
|
4372
|
$preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
|
4373
|
|
4374
|
// A dummy query-string is added to filenames, to gain control over
|
4375
|
// browser-caching. The string changes on every update or full cache
|
4376
|
// flush, forcing browsers to load a new copy of the files, as the
|
4377
|
// URL changed. Files that should not be cached (see drupal_add_js())
|
4378
|
// get REQUEST_TIME as query-string instead, to enforce reload on every
|
4379
|
// page request.
|
4380
|
$default_query_string = variable_get('css_js_query_string', '0');
|
4381
|
|
4382
|
// For inline JavaScript to validate as XHTML, all JavaScript containing
|
4383
|
// XHTML needs to be wrapped in CDATA. To make that backwards compatible
|
4384
|
// with HTML 4, we need to comment out the CDATA-tag.
|
4385
|
$embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
|
4386
|
$embed_suffix = "\n//--><!]]>\n";
|
4387
|
|
4388
|
// Since JavaScript may look for arguments in the URL and act on them, some
|
4389
|
// third-party code might require the use of a different query string.
|
4390
|
$js_version_string = variable_get('drupal_js_version_query_string', 'v=');
|
4391
|
|
4392
|
// Sort the JavaScript so that it appears in the correct order.
|
4393
|
uasort($items, 'drupal_sort_css_js');
|
4394
|
|
4395
|
// Provide the page with information about the individual JavaScript files
|
4396
|
// used, information not otherwise available when aggregation is enabled.
|
4397
|
$setting['ajaxPageState']['js'] = array_fill_keys(array_keys($items), 1);
|
4398
|
unset($setting['ajaxPageState']['js']['settings']);
|
4399
|
drupal_add_js($setting, 'setting');
|
4400
|
|
4401
|
// If we're outputting the header scope, then this might be the final time
|
4402
|
// that drupal_get_js() is running, so add the setting to this output as well
|
4403
|
// as to the drupal_add_js() cache. If $items['settings'] doesn't exist, it's
|
4404
|
// because drupal_get_js() was intentionally passed a $javascript argument
|
4405
|
// stripped off settings, potentially in order to override how settings get
|
4406
|
// output, so in this case, do not add the setting to this output.
|
4407
|
if ($scope == 'header' && isset($items['settings'])) {
|
4408
|
$items['settings']['data'][] = $setting;
|
4409
|
}
|
4410
|
|
4411
|
// Loop through the JavaScript to construct the rendered output.
|
4412
|
$element = array(
|
4413
|
'#tag' => 'script',
|
4414
|
'#value' => '',
|
4415
|
'#attributes' => array(
|
4416
|
'type' => 'text/javascript',
|
4417
|
),
|
4418
|
);
|
4419
|
foreach ($items as $item) {
|
4420
|
$query_string = empty($item['version']) ? $default_query_string : $js_version_string . $item['version'];
|
4421
|
|
4422
|
switch ($item['type']) {
|
4423
|
case 'setting':
|
4424
|
$js_element = $element;
|
4425
|
$js_element['#value_prefix'] = $embed_prefix;
|
4426
|
$js_element['#value'] = 'jQuery.extend(Drupal.settings, ' . drupal_json_encode(drupal_array_merge_deep_array($item['data'])) . ");";
|
4427
|
$js_element['#value_suffix'] = $embed_suffix;
|
4428
|
$output .= theme('html_tag', array('element' => $js_element));
|
4429
|
break;
|
4430
|
|
4431
|
case 'inline':
|
4432
|
$js_element = $element;
|
4433
|
if ($item['defer']) {
|
4434
|
$js_element['#attributes']['defer'] = 'defer';
|
4435
|
}
|
4436
|
$js_element['#value_prefix'] = $embed_prefix;
|
4437
|
$js_element['#value'] = $item['data'];
|
4438
|
$js_element['#value_suffix'] = $embed_suffix;
|
4439
|
$processed[$index++] = theme('html_tag', array('element' => $js_element));
|
4440
|
break;
|
4441
|
|
4442
|
case 'file':
|
4443
|
$js_element = $element;
|
4444
|
if (!$item['preprocess'] || !$preprocess_js) {
|
4445
|
if ($item['defer']) {
|
4446
|
$js_element['#attributes']['defer'] = 'defer';
|
4447
|
}
|
4448
|
$query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
|
4449
|
$js_element['#attributes']['src'] = file_create_url($item['data']) . $query_string_separator . ($item['cache'] ? $query_string : REQUEST_TIME);
|
4450
|
$processed[$index++] = theme('html_tag', array('element' => $js_element));
|
4451
|
}
|
4452
|
else {
|
4453
|
// By increasing the index for each aggregated file, we maintain
|
4454
|
// the relative ordering of JS by weight. We also set the key such
|
4455
|
// that groups are split by items sharing the same 'group' value and
|
4456
|
// 'every_page' flag. While this potentially results in more aggregate
|
4457
|
// files, it helps make each one more reusable across a site visit,
|
4458
|
// leading to better front-end performance of a website as a whole.
|
4459
|
// See drupal_add_js() for details.
|
4460
|
$key = 'aggregate_' . $item['group'] . '_' . $item['every_page'] . '_' . $index;
|
4461
|
$processed[$key] = '';
|
4462
|
$files[$key][$item['data']] = $item;
|
4463
|
}
|
4464
|
break;
|
4465
|
|
4466
|
case 'external':
|
4467
|
$js_element = $element;
|
4468
|
// Preprocessing for external JavaScript files is ignored.
|
4469
|
if ($item['defer']) {
|
4470
|
$js_element['#attributes']['defer'] = 'defer';
|
4471
|
}
|
4472
|
$js_element['#attributes']['src'] = $item['data'];
|
4473
|
$processed[$index++] = theme('html_tag', array('element' => $js_element));
|
4474
|
break;
|
4475
|
}
|
4476
|
}
|
4477
|
|
4478
|
// Aggregate any remaining JS files that haven't already been output.
|
4479
|
if ($preprocess_js && count($files) > 0) {
|
4480
|
foreach ($files as $key => $file_set) {
|
4481
|
$uri = drupal_build_js_cache($file_set);
|
4482
|
// Only include the file if was written successfully. Errors are logged
|
4483
|
// using watchdog.
|
4484
|
if ($uri) {
|
4485
|
$preprocess_file = file_create_url($uri);
|
4486
|
$js_element = $element;
|
4487
|
$js_element['#attributes']['src'] = $preprocess_file;
|
4488
|
$processed[$key] = theme('html_tag', array('element' => $js_element));
|
4489
|
}
|
4490
|
}
|
4491
|
}
|
4492
|
|
4493
|
// Keep the order of JS files consistent as some are preprocessed and others are not.
|
4494
|
// Make sure any inline or JS setting variables appear last after libraries have loaded.
|
4495
|
return implode('', $processed) . $output;
|
4496
|
}
|
4497
|
|
4498
|
/**
|
4499
|
* Adds attachments to a render() structure.
|
4500
|
*
|
4501
|
* Libraries, JavaScript, CSS and other types of custom structures are attached
|
4502
|
* to elements using the #attached property. The #attached property is an
|
4503
|
* associative array, where the keys are the attachment types and the values are
|
4504
|
* the attached data. For example:
|
4505
|
* @code
|
4506
|
* $build['#attached'] = array(
|
4507
|
* 'js' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.js'),
|
4508
|
* 'css' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.css'),
|
4509
|
* );
|
4510
|
* @endcode
|
4511
|
*
|
4512
|
* 'js', 'css', and 'library' are types that get special handling. For any
|
4513
|
* other kind of attached data, the array key must be the full name of the
|
4514
|
* callback function and each value an array of arguments. For example:
|
4515
|
* @code
|
4516
|
* $build['#attached']['drupal_add_http_header'] = array(
|
4517
|
* array('Content-Type', 'application/rss+xml; charset=utf-8'),
|
4518
|
* );
|
4519
|
* @endcode
|
4520
|
*
|
4521
|
* External 'js' and 'css' files can also be loaded. For example:
|
4522
|
* @code
|
4523
|
* $build['#attached']['js'] = array(
|
4524
|
* 'http://code.jquery.com/jquery-1.4.2.min.js' => array(
|
4525
|
* 'type' => 'external',
|
4526
|
* ),
|
4527
|
* );
|
4528
|
* @endcode
|
4529
|
*
|
4530
|
* @param $elements
|
4531
|
* The structured array describing the data being rendered.
|
4532
|
* @param $group
|
4533
|
* The default group of JavaScript and CSS being added. This is only applied
|
4534
|
* to the stylesheets and JavaScript items that don't have an explicit group
|
4535
|
* assigned to them.
|
4536
|
* @param $dependency_check
|
4537
|
* When TRUE, will exit if a given library's dependencies are missing. When
|
4538
|
* set to FALSE, will continue to add the libraries, even though one or more
|
4539
|
* dependencies are missing. Defaults to FALSE.
|
4540
|
* @param $every_page
|
4541
|
* Set to TRUE to indicate that the attachments are added to every page on the
|
4542
|
* site. Only attachments with the every_page flag set to TRUE can participate
|
4543
|
* in JavaScript/CSS aggregation.
|
4544
|
*
|
4545
|
* @return
|
4546
|
* FALSE if there were any missing library dependencies; TRUE if all library
|
4547
|
* dependencies were met.
|
4548
|
*
|
4549
|
* @see drupal_add_library()
|
4550
|
* @see drupal_add_js()
|
4551
|
* @see drupal_add_css()
|
4552
|
* @see drupal_render()
|
4553
|
*/
|
4554
|
function drupal_process_attached($elements, $group = JS_DEFAULT, $dependency_check = FALSE, $every_page = NULL) {
|
4555
|
// Add defaults to the special attached structures that should be processed differently.
|
4556
|
$elements['#attached'] += array(
|
4557
|
'library' => array(),
|
4558
|
'js' => array(),
|
4559
|
'css' => array(),
|
4560
|
);
|
4561
|
|
4562
|
// Add the libraries first.
|
4563
|
$success = TRUE;
|
4564
|
foreach ($elements['#attached']['library'] as $library) {
|
4565
|
if (drupal_add_library($library[0], $library[1], $every_page) === FALSE) {
|
4566
|
$success = FALSE;
|
4567
|
// Exit if the dependency is missing.
|
4568
|
if ($dependency_check) {
|
4569
|
return $success;
|
4570
|
}
|
4571
|
}
|
4572
|
}
|
4573
|
unset($elements['#attached']['library']);
|
4574
|
|
4575
|
// Add both the JavaScript and the CSS.
|
4576
|
// The parameters for drupal_add_js() and drupal_add_css() require special
|
4577
|
// handling.
|
4578
|
foreach (array('js', 'css') as $type) {
|
4579
|
foreach ($elements['#attached'][$type] as $data => $options) {
|
4580
|
// If the value is not an array, it's a filename and passed as first
|
4581
|
// (and only) argument.
|
4582
|
if (!is_array($options)) {
|
4583
|
$data = $options;
|
4584
|
$options = NULL;
|
4585
|
}
|
4586
|
// In some cases, the first parameter ($data) is an array. Arrays can't be
|
4587
|
// passed as keys in PHP, so we have to get $data from the value array.
|
4588
|
if (is_numeric($data)) {
|
4589
|
$data = $options['data'];
|
4590
|
unset($options['data']);
|
4591
|
}
|
4592
|
// Apply the default group if it isn't explicitly given.
|
4593
|
if (!isset($options['group'])) {
|
4594
|
$options['group'] = $group;
|
4595
|
}
|
4596
|
// Set the every_page flag if one was passed.
|
4597
|
if (isset($every_page)) {
|
4598
|
$options['every_page'] = $every_page;
|
4599
|
}
|
4600
|
call_user_func('drupal_add_' . $type, $data, $options);
|
4601
|
}
|
4602
|
unset($elements['#attached'][$type]);
|
4603
|
}
|
4604
|
|
4605
|
// Add additional types of attachments specified in the render() structure.
|
4606
|
// Libraries, JavaScript and CSS have been added already, as they require
|
4607
|
// special handling.
|
4608
|
foreach ($elements['#attached'] as $callback => $options) {
|
4609
|
if (function_exists($callback)) {
|
4610
|
foreach ($elements['#attached'][$callback] as $args) {
|
4611
|
call_user_func_array($callback, $args);
|
4612
|
}
|
4613
|
}
|
4614
|
}
|
4615
|
|
4616
|
return $success;
|
4617
|
}
|
4618
|
|
4619
|
/**
|
4620
|
* Adds JavaScript to change the state of an element based on another element.
|
4621
|
*
|
4622
|
* A "state" means a certain property on a DOM element, such as "visible" or
|
4623
|
* "checked". A state can be applied to an element, depending on the state of
|
4624
|
* another element on the page. In general, states depend on HTML attributes and
|
4625
|
* DOM element properties, which change due to user interaction.
|
4626
|
*
|
4627
|
* Since states are driven by JavaScript only, it is important to understand
|
4628
|
* that all states are applied on presentation only, none of the states force
|
4629
|
* any server-side logic, and that they will not be applied for site visitors
|
4630
|
* without JavaScript support. All modules implementing states have to make
|
4631
|
* sure that the intended logic also works without JavaScript being enabled.
|
4632
|
*
|
4633
|
* #states is an associative array in the form of:
|
4634
|
* @code
|
4635
|
* array(
|
4636
|
* STATE1 => CONDITIONS_ARRAY1,
|
4637
|
* STATE2 => CONDITIONS_ARRAY2,
|
4638
|
* ...
|
4639
|
* )
|
4640
|
* @endcode
|
4641
|
* Each key is the name of a state to apply to the element, such as 'visible'.
|
4642
|
* Each value is a list of conditions that denote when the state should be
|
4643
|
* applied.
|
4644
|
*
|
4645
|
* Multiple different states may be specified to act on complex conditions:
|
4646
|
* @code
|
4647
|
* array(
|
4648
|
* 'visible' => CONDITIONS,
|
4649
|
* 'checked' => OTHER_CONDITIONS,
|
4650
|
* )
|
4651
|
* @endcode
|
4652
|
*
|
4653
|
* Every condition is a key/value pair, whose key is a jQuery selector that
|
4654
|
* denotes another element on the page, and whose value is an array of
|
4655
|
* conditions, which must bet met on that element:
|
4656
|
* @code
|
4657
|
* array(
|
4658
|
* 'visible' => array(
|
4659
|
* JQUERY_SELECTOR => REMOTE_CONDITIONS,
|
4660
|
* JQUERY_SELECTOR => REMOTE_CONDITIONS,
|
4661
|
* ...
|
4662
|
* ),
|
4663
|
* )
|
4664
|
* @endcode
|
4665
|
* All conditions must be met for the state to be applied.
|
4666
|
*
|
4667
|
* Each remote condition is a key/value pair specifying conditions on the other
|
4668
|
* element that need to be met to apply the state to the element:
|
4669
|
* @code
|
4670
|
* array(
|
4671
|
* 'visible' => array(
|
4672
|
* ':input[name="remote_checkbox"]' => array('checked' => TRUE),
|
4673
|
* ),
|
4674
|
* )
|
4675
|
* @endcode
|
4676
|
*
|
4677
|
* For example, to show a textfield only when a checkbox is checked:
|
4678
|
* @code
|
4679
|
* $form['toggle_me'] = array(
|
4680
|
* '#type' => 'checkbox',
|
4681
|
* '#title' => t('Tick this box to type'),
|
4682
|
* );
|
4683
|
* $form['settings'] = array(
|
4684
|
* '#type' => 'textfield',
|
4685
|
* '#states' => array(
|
4686
|
* // Only show this field when the 'toggle_me' checkbox is enabled.
|
4687
|
* 'visible' => array(
|
4688
|
* ':input[name="toggle_me"]' => array('checked' => TRUE),
|
4689
|
* ),
|
4690
|
* ),
|
4691
|
* );
|
4692
|
* @endcode
|
4693
|
*
|
4694
|
* The following states may be applied to an element:
|
4695
|
* - enabled
|
4696
|
* - disabled
|
4697
|
* - required
|
4698
|
* - optional
|
4699
|
* - visible
|
4700
|
* - invisible
|
4701
|
* - checked
|
4702
|
* - unchecked
|
4703
|
* - expanded
|
4704
|
* - collapsed
|
4705
|
*
|
4706
|
* The following states may be used in remote conditions:
|
4707
|
* - empty
|
4708
|
* - filled
|
4709
|
* - checked
|
4710
|
* - unchecked
|
4711
|
* - expanded
|
4712
|
* - collapsed
|
4713
|
* - value
|
4714
|
*
|
4715
|
* The following states exist for both elements and remote conditions, but are
|
4716
|
* not fully implemented and may not change anything on the element:
|
4717
|
* - relevant
|
4718
|
* - irrelevant
|
4719
|
* - valid
|
4720
|
* - invalid
|
4721
|
* - touched
|
4722
|
* - untouched
|
4723
|
* - readwrite
|
4724
|
* - readonly
|
4725
|
*
|
4726
|
* When referencing select lists and radio buttons in remote conditions, a
|
4727
|
* 'value' condition must be used:
|
4728
|
* @code
|
4729
|
* '#states' => array(
|
4730
|
* // Show the settings if 'bar' has been selected for 'foo'.
|
4731
|
* 'visible' => array(
|
4732
|
* ':input[name="foo"]' => array('value' => 'bar'),
|
4733
|
* ),
|
4734
|
* ),
|
4735
|
* @endcode
|
4736
|
*
|
4737
|
* @param $elements
|
4738
|
* A renderable array element having a #states property as described above.
|
4739
|
*
|
4740
|
* @see form_example_states_form()
|
4741
|
*/
|
4742
|
function drupal_process_states(&$elements) {
|
4743
|
$elements['#attached']['library'][] = array('system', 'drupal.states');
|
4744
|
$elements['#attached']['js'][] = array(
|
4745
|
'type' => 'setting',
|
4746
|
'data' => array('states' => array('#' . $elements['#id'] => $elements['#states'])),
|
4747
|
);
|
4748
|
}
|
4749
|
|
4750
|
/**
|
4751
|
* Adds multiple JavaScript or CSS files at the same time.
|
4752
|
*
|
4753
|
* A library defines a set of JavaScript and/or CSS files, optionally using
|
4754
|
* settings, and optionally requiring another library. For example, a library
|
4755
|
* can be a jQuery plugin, a JavaScript framework, or a CSS framework. This
|
4756
|
* function allows modules to load a library defined/shipped by itself or a
|
4757
|
* depending module, without having to add all files of the library separately.
|
4758
|
* Each library is only loaded once.
|
4759
|
*
|
4760
|
* @param $module
|
4761
|
* The name of the module that registered the library.
|
4762
|
* @param $name
|
4763
|
* The name of the library to add.
|
4764
|
* @param $every_page
|
4765
|
* Set to TRUE if this library is added to every page on the site. Only items
|
4766
|
* with the every_page flag set to TRUE can participate in aggregation.
|
4767
|
*
|
4768
|
* @return
|
4769
|
* TRUE if the library was successfully added; FALSE if the library or one of
|
4770
|
* its dependencies could not be added.
|
4771
|
*
|
4772
|
* @see drupal_get_library()
|
4773
|
* @see hook_library()
|
4774
|
* @see hook_library_alter()
|
4775
|
*/
|
4776
|
function drupal_add_library($module, $name, $every_page = NULL) {
|
4777
|
$added = &drupal_static(__FUNCTION__, array());
|
4778
|
|
4779
|
// Only process the library if it exists and it was not added already.
|
4780
|
if (!isset($added[$module][$name])) {
|
4781
|
if ($library = drupal_get_library($module, $name)) {
|
4782
|
// Add all components within the library.
|
4783
|
$elements['#attached'] = array(
|
4784
|
'library' => $library['dependencies'],
|
4785
|
'js' => $library['js'],
|
4786
|
'css' => $library['css'],
|
4787
|
);
|
4788
|
$added[$module][$name] = drupal_process_attached($elements, JS_LIBRARY, TRUE, $every_page);
|
4789
|
}
|
4790
|
else {
|
4791
|
// Requested library does not exist.
|
4792
|
$added[$module][$name] = FALSE;
|
4793
|
}
|
4794
|
}
|
4795
|
|
4796
|
return $added[$module][$name];
|
4797
|
}
|
4798
|
|
4799
|
/**
|
4800
|
* Retrieves information for a JavaScript/CSS library.
|
4801
|
*
|
4802
|
* Library information is statically cached. Libraries are keyed by module for
|
4803
|
* several reasons:
|
4804
|
* - Libraries are not unique. Multiple modules might ship with the same library
|
4805
|
* in a different version or variant. This registry cannot (and does not
|
4806
|
* attempt to) prevent library conflicts.
|
4807
|
* - Modules implementing and thereby depending on a library that is registered
|
4808
|
* by another module can only rely on that module's library.
|
4809
|
* - Two (or more) modules can still register the same library and use it
|
4810
|
* without conflicts in case the libraries are loaded on certain pages only.
|
4811
|
*
|
4812
|
* @param $module
|
4813
|
* The name of a module that registered a library.
|
4814
|
* @param $name
|
4815
|
* (optional) The name of a registered library to retrieve. By default, all
|
4816
|
* libraries registered by $module are returned.
|
4817
|
*
|
4818
|
* @return
|
4819
|
* The definition of the requested library, if $name was passed and it exists,
|
4820
|
* or FALSE if it does not exist. If no $name was passed, an associative array
|
4821
|
* of libraries registered by $module is returned (which may be empty).
|
4822
|
*
|
4823
|
* @see drupal_add_library()
|
4824
|
* @see hook_library()
|
4825
|
* @see hook_library_alter()
|
4826
|
*
|
4827
|
* @todo The purpose of drupal_get_*() is completely different to other page
|
4828
|
* requisite API functions; find and use a different name.
|
4829
|
*/
|
4830
|
function drupal_get_library($module, $name = NULL) {
|
4831
|
$libraries = &drupal_static(__FUNCTION__, array());
|
4832
|
|
4833
|
if (!isset($libraries[$module])) {
|
4834
|
// Retrieve all libraries associated with the module.
|
4835
|
$module_libraries = module_invoke($module, 'library');
|
4836
|
if (empty($module_libraries)) {
|
4837
|
$module_libraries = array();
|
4838
|
}
|
4839
|
// Allow modules to alter the module's registered libraries.
|
4840
|
drupal_alter('library', $module_libraries, $module);
|
4841
|
|
4842
|
foreach ($module_libraries as $key => $data) {
|
4843
|
if (is_array($data)) {
|
4844
|
// Add default elements to allow for easier processing.
|
4845
|
$module_libraries[$key] += array('dependencies' => array(), 'js' => array(), 'css' => array());
|
4846
|
foreach ($module_libraries[$key]['js'] as $file => $options) {
|
4847
|
$module_libraries[$key]['js'][$file]['version'] = $module_libraries[$key]['version'];
|
4848
|
}
|
4849
|
}
|
4850
|
}
|
4851
|
$libraries[$module] = $module_libraries;
|
4852
|
}
|
4853
|
if (isset($name)) {
|
4854
|
if (!isset($libraries[$module][$name])) {
|
4855
|
$libraries[$module][$name] = FALSE;
|
4856
|
}
|
4857
|
return $libraries[$module][$name];
|
4858
|
}
|
4859
|
return $libraries[$module];
|
4860
|
}
|
4861
|
|
4862
|
/**
|
4863
|
* Assists in adding the tableDrag JavaScript behavior to a themed table.
|
4864
|
*
|
4865
|
* Draggable tables should be used wherever an outline or list of sortable items
|
4866
|
* needs to be arranged by an end-user. Draggable tables are very flexible and
|
4867
|
* can manipulate the value of form elements placed within individual columns.
|
4868
|
*
|
4869
|
* To set up a table to use drag and drop in place of weight select-lists or in
|
4870
|
* place of a form that contains parent relationships, the form must be themed
|
4871
|
* into a table. The table must have an ID attribute set. If using
|
4872
|
* theme_table(), the ID may be set as follows:
|
4873
|
* @code
|
4874
|
* $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'my-module-table')));
|
4875
|
* return $output;
|
4876
|
* @endcode
|
4877
|
*
|
4878
|
* In the theme function for the form, a special class must be added to each
|
4879
|
* form element within the same column, "grouping" them together.
|
4880
|
*
|
4881
|
* In a situation where a single weight column is being sorted in the table, the
|
4882
|
* classes could be added like this (in the theme function):
|
4883
|
* @code
|
4884
|
* $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
|
4885
|
* @endcode
|
4886
|
*
|
4887
|
* Each row of the table must also have a class of "draggable" in order to
|
4888
|
* enable the drag handles:
|
4889
|
* @code
|
4890
|
* $row = array(...);
|
4891
|
* $rows[] = array(
|
4892
|
* 'data' => $row,
|
4893
|
* 'class' => array('draggable'),
|
4894
|
* );
|
4895
|
* @endcode
|
4896
|
*
|
4897
|
* When tree relationships are present, the two additional classes
|
4898
|
* 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
|
4899
|
* - Rows with the 'tabledrag-leaf' class cannot have child rows.
|
4900
|
* - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
|
4901
|
*
|
4902
|
* Calling drupal_add_tabledrag() would then be written as such:
|
4903
|
* @code
|
4904
|
* drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
|
4905
|
* @endcode
|
4906
|
*
|
4907
|
* In a more complex case where there are several groups in one column (such as
|
4908
|
* the block regions on the admin/structure/block page), a separate subgroup
|
4909
|
* class must also be added to differentiate the groups.
|
4910
|
* @code
|
4911
|
* $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
|
4912
|
* @endcode
|
4913
|
*
|
4914
|
* $group is still 'my-element-weight', and the additional $subgroup variable
|
4915
|
* will be passed in as 'my-elements-weight-' . $region. This also means that
|
4916
|
* you'll need to call drupal_add_tabledrag() once for every region added.
|
4917
|
*
|
4918
|
* @code
|
4919
|
* foreach ($regions as $region) {
|
4920
|
* drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight', 'my-elements-weight-' . $region);
|
4921
|
* }
|
4922
|
* @endcode
|
4923
|
*
|
4924
|
* In a situation where tree relationships are present, adding multiple
|
4925
|
* subgroups is not necessary, because the table will contain indentations that
|
4926
|
* provide enough information about the sibling and parent relationships. See
|
4927
|
* theme_menu_overview_form() for an example creating a table containing parent
|
4928
|
* relationships.
|
4929
|
*
|
4930
|
* Note that this function should be called from the theme layer, such as in a
|
4931
|
* .tpl.php file, theme_ function, or in a template_preprocess function, not in
|
4932
|
* a form declaration. Though the same JavaScript could be added to the page
|
4933
|
* using drupal_add_js() directly, this function helps keep template files
|
4934
|
* clean and readable. It also prevents tabledrag.js from being added twice
|
4935
|
* accidentally.
|
4936
|
*
|
4937
|
* @param $table_id
|
4938
|
* String containing the target table's id attribute. If the table does not
|
4939
|
* have an id, one will need to be set, such as <table id="my-module-table">.
|
4940
|
* @param $action
|
4941
|
* String describing the action to be done on the form item. Either 'match'
|
4942
|
* 'depth', or 'order'. Match is typically used for parent relationships.
|
4943
|
* Order is typically used to set weights on other form elements with the same
|
4944
|
* group. Depth updates the target element with the current indentation.
|
4945
|
* @param $relationship
|
4946
|
* String describing where the $action variable should be performed. Either
|
4947
|
* 'parent', 'sibling', 'group', or 'self'. Parent will only look for fields
|
4948
|
* up the tree. Sibling will look for fields in the same group in rows above
|
4949
|
* and below it. Self affects the dragged row itself. Group affects the
|
4950
|
* dragged row, plus any children below it (the entire dragged group).
|
4951
|
* @param $group
|
4952
|
* A class name applied on all related form elements for this action.
|
4953
|
* @param $subgroup
|
4954
|
* (optional) If the group has several subgroups within it, this string should
|
4955
|
* contain the class name identifying fields in the same subgroup.
|
4956
|
* @param $source
|
4957
|
* (optional) If the $action is 'match', this string should contain the class
|
4958
|
* name identifying what field will be used as the source value when matching
|
4959
|
* the value in $subgroup.
|
4960
|
* @param $hidden
|
4961
|
* (optional) The column containing the field elements may be entirely hidden
|
4962
|
* from view dynamically when the JavaScript is loaded. Set to FALSE if the
|
4963
|
* column should not be hidden.
|
4964
|
* @param $limit
|
4965
|
* (optional) Limit the maximum amount of parenting in this table.
|
4966
|
* @see block-admin-display-form.tpl.php
|
4967
|
* @see theme_menu_overview_form()
|
4968
|
*/
|
4969
|
function drupal_add_tabledrag($table_id, $action, $relationship, $group, $subgroup = NULL, $source = NULL, $hidden = TRUE, $limit = 0) {
|
4970
|
$js_added = &drupal_static(__FUNCTION__, FALSE);
|
4971
|
if (!$js_added) {
|
4972
|
// Add the table drag JavaScript to the page before the module JavaScript
|
4973
|
// to ensure that table drag behaviors are registered before any module
|
4974
|
// uses it.
|
4975
|
drupal_add_library('system', 'jquery.cookie');
|
4976
|
drupal_add_js('misc/tabledrag.js', array('weight' => -1));
|
4977
|
$js_added = TRUE;
|
4978
|
}
|
4979
|
|
4980
|
// If a subgroup or source isn't set, assume it is the same as the group.
|
4981
|
$target = isset($subgroup) ? $subgroup : $group;
|
4982
|
$source = isset($source) ? $source : $target;
|
4983
|
$settings['tableDrag'][$table_id][$group][] = array(
|
4984
|
'target' => $target,
|
4985
|
'source' => $source,
|
4986
|
'relationship' => $relationship,
|
4987
|
'action' => $action,
|
4988
|
'hidden' => $hidden,
|
4989
|
'limit' => $limit,
|
4990
|
);
|
4991
|
drupal_add_js($settings, 'setting');
|
4992
|
}
|
4993
|
|
4994
|
/**
|
4995
|
* Aggregates JavaScript files into a cache file in the files directory.
|
4996
|
*
|
4997
|
* The file name for the JavaScript cache file is generated from the hash of
|
4998
|
* the aggregated contents of the files in $files. This forces proxies and
|
4999
|
* browsers to download new JavaScript when the JavaScript changes.
|
5000
|
*
|
5001
|
* The cache file name is retrieved on a page load via a lookup variable that
|
5002
|
* contains an associative array. The array key is the hash of the names in
|
5003
|
* $files while the value is the cache file name. The cache file is generated
|
5004
|
* in two cases. First, if there is no file name value for the key, which will
|
5005
|
* happen if a new file name has been added to $files or after the lookup
|
5006
|
* variable is emptied to force a rebuild of the cache. Second, the cache file
|
5007
|
* is generated if it is missing on disk. Old cache files are not deleted
|
5008
|
* immediately when the lookup variable is emptied, but are deleted after a set
|
5009
|
* period by drupal_delete_file_if_stale(). This ensures that files referenced
|
5010
|
* by a cached page will still be available.
|
5011
|
*
|
5012
|
* @param $files
|
5013
|
* An array of JavaScript files to aggregate and compress into one file.
|
5014
|
*
|
5015
|
* @return
|
5016
|
* The URI of the cache file, or FALSE if the file could not be saved.
|
5017
|
*/
|
5018
|
function drupal_build_js_cache($files) {
|
5019
|
$contents = '';
|
5020
|
$uri = '';
|
5021
|
$map = variable_get('drupal_js_cache_files', array());
|
5022
|
// Create a new array so that only the file names are used to create the hash.
|
5023
|
// This prevents new aggregates from being created unnecessarily.
|
5024
|
$js_data = array();
|
5025
|
foreach ($files as $file) {
|
5026
|
$js_data[] = $file['data'];
|
5027
|
}
|
5028
|
$key = hash('sha256', serialize($js_data));
|
5029
|
if (isset($map[$key])) {
|
5030
|
$uri = $map[$key];
|
5031
|
}
|
5032
|
|
5033
|
if (empty($uri) || !file_exists($uri)) {
|
5034
|
// Build aggregate JS file.
|
5035
|
foreach ($files as $path => $info) {
|
5036
|
if ($info['preprocess']) {
|
5037
|
// Append a ';' and a newline after each JS file to prevent them from running together.
|
5038
|
$contents .= file_get_contents($path) . ";\n";
|
5039
|
}
|
5040
|
}
|
5041
|
// Prefix filename to prevent blocking by firewalls which reject files
|
5042
|
// starting with "ad*".
|
5043
|
$filename = 'js_' . drupal_hash_base64($contents) . '.js';
|
5044
|
// Create the js/ within the files folder.
|
5045
|
$jspath = 'public://js';
|
5046
|
$uri = $jspath . '/' . $filename;
|
5047
|
// Create the JS file.
|
5048
|
file_prepare_directory($jspath, FILE_CREATE_DIRECTORY);
|
5049
|
if (!file_exists($uri) && !file_unmanaged_save_data($contents, $uri, FILE_EXISTS_REPLACE)) {
|
5050
|
return FALSE;
|
5051
|
}
|
5052
|
// If JS gzip compression is enabled, clean URLs are enabled (which means
|
5053
|
// that rewrite rules are working) and the zlib extension is available then
|
5054
|
// create a gzipped version of this file. This file is served conditionally
|
5055
|
// to browsers that accept gzip using .htaccess rules.
|
5056
|
if (variable_get('js_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
|
5057
|
if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($contents, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
|
5058
|
return FALSE;
|
5059
|
}
|
5060
|
}
|
5061
|
$map[$key] = $uri;
|
5062
|
variable_set('drupal_js_cache_files', $map);
|
5063
|
}
|
5064
|
return $uri;
|
5065
|
}
|
5066
|
|
5067
|
/**
|
5068
|
* Deletes old cached JavaScript files and variables.
|
5069
|
*/
|
5070
|
function drupal_clear_js_cache() {
|
5071
|
variable_del('javascript_parsed');
|
5072
|
variable_del('drupal_js_cache_files');
|
5073
|
file_scan_directory('public://js', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
|
5074
|
}
|
5075
|
|
5076
|
/**
|
5077
|
* Converts a PHP variable into its JavaScript equivalent.
|
5078
|
*
|
5079
|
* We use HTML-safe strings, with several characters escaped.
|
5080
|
*
|
5081
|
* @see drupal_json_decode()
|
5082
|
* @see drupal_json_encode_helper()
|
5083
|
* @ingroup php_wrappers
|
5084
|
*/
|
5085
|
function drupal_json_encode($var) {
|
5086
|
// The PHP version cannot change within a request.
|
5087
|
static $php530;
|
5088
|
|
5089
|
if (!isset($php530)) {
|
5090
|
$php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
|
5091
|
}
|
5092
|
|
5093
|
if ($php530) {
|
5094
|
// Encode <, >, ', &, and " using the json_encode() options parameter.
|
5095
|
return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
|
5096
|
}
|
5097
|
|
5098
|
// json_encode() escapes <, >, ', &, and " using its options parameter, but
|
5099
|
// does not support this parameter prior to PHP 5.3.0. Use a helper instead.
|
5100
|
include_once DRUPAL_ROOT . '/includes/json-encode.inc';
|
5101
|
return drupal_json_encode_helper($var);
|
5102
|
}
|
5103
|
|
5104
|
/**
|
5105
|
* Converts an HTML-safe JSON string into its PHP equivalent.
|
5106
|
*
|
5107
|
* @see drupal_json_encode()
|
5108
|
* @ingroup php_wrappers
|
5109
|
*/
|
5110
|
function drupal_json_decode($var) {
|
5111
|
return json_decode($var, TRUE);
|
5112
|
}
|
5113
|
|
5114
|
/**
|
5115
|
* Returns data in JSON format.
|
5116
|
*
|
5117
|
* This function should be used for JavaScript callback functions returning
|
5118
|
* data in JSON format. It sets the header for JavaScript output.
|
5119
|
*
|
5120
|
* @param $var
|
5121
|
* (optional) If set, the variable will be converted to JSON and output.
|
5122
|
*/
|
5123
|
function drupal_json_output($var = NULL) {
|
5124
|
// We are returning JSON, so tell the browser.
|
5125
|
drupal_add_http_header('Content-Type', 'application/json');
|
5126
|
|
5127
|
if (isset($var)) {
|
5128
|
echo drupal_json_encode($var);
|
5129
|
}
|
5130
|
}
|
5131
|
|
5132
|
/**
|
5133
|
* Ensures the private key variable used to generate tokens is set.
|
5134
|
*
|
5135
|
* @return
|
5136
|
* The private key.
|
5137
|
*/
|
5138
|
function drupal_get_private_key() {
|
5139
|
if (!($key = variable_get('drupal_private_key', 0))) {
|
5140
|
$key = drupal_random_key();
|
5141
|
variable_set('drupal_private_key', $key);
|
5142
|
}
|
5143
|
return $key;
|
5144
|
}
|
5145
|
|
5146
|
/**
|
5147
|
* Generates a token based on $value, the user session, and the private key.
|
5148
|
*
|
5149
|
* @param $value
|
5150
|
* An additional value to base the token on.
|
5151
|
*
|
5152
|
* The generated token is based on the session ID of the current user. Normally,
|
5153
|
* anonymous users do not have a session, so the generated token will be
|
5154
|
* different on every page request. To generate a token for users without a
|
5155
|
* session, manually start a session prior to calling this function.
|
5156
|
*
|
5157
|
* @return string
|
5158
|
* A 43-character URL-safe token for validation, based on the user session ID,
|
5159
|
* the hash salt provided from drupal_get_hash_salt(), and the
|
5160
|
* 'drupal_private_key' configuration variable.
|
5161
|
*
|
5162
|
* @see drupal_get_hash_salt()
|
5163
|
*/
|
5164
|
function drupal_get_token($value = '') {
|
5165
|
return drupal_hmac_base64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());
|
5166
|
}
|
5167
|
|
5168
|
/**
|
5169
|
* Validates a token based on $value, the user session, and the private key.
|
5170
|
*
|
5171
|
* @param $token
|
5172
|
* The token to be validated.
|
5173
|
* @param $value
|
5174
|
* An additional value to base the token on.
|
5175
|
* @param $skip_anonymous
|
5176
|
* Set to true to skip token validation for anonymous users.
|
5177
|
*
|
5178
|
* @return
|
5179
|
* True for a valid token, false for an invalid token. When $skip_anonymous
|
5180
|
* is true, the return value will always be true for anonymous users.
|
5181
|
*/
|
5182
|
function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
|
5183
|
global $user;
|
5184
|
return (($skip_anonymous && $user->uid == 0) || ($token === drupal_get_token($value)));
|
5185
|
}
|
5186
|
|
5187
|
function _drupal_bootstrap_full() {
|
5188
|
static $called = FALSE;
|
5189
|
|
5190
|
if ($called) {
|
5191
|
return;
|
5192
|
}
|
5193
|
$called = TRUE;
|
5194
|
require_once DRUPAL_ROOT . '/' . variable_get('path_inc', 'includes/path.inc');
|
5195
|
require_once DRUPAL_ROOT . '/includes/theme.inc';
|
5196
|
require_once DRUPAL_ROOT . '/includes/pager.inc';
|
5197
|
require_once DRUPAL_ROOT . '/' . variable_get('menu_inc', 'includes/menu.inc');
|
5198
|
require_once DRUPAL_ROOT . '/includes/tablesort.inc';
|
5199
|
require_once DRUPAL_ROOT . '/includes/file.inc';
|
5200
|
require_once DRUPAL_ROOT . '/includes/unicode.inc';
|
5201
|
require_once DRUPAL_ROOT . '/includes/image.inc';
|
5202
|
require_once DRUPAL_ROOT . '/includes/form.inc';
|
5203
|
require_once DRUPAL_ROOT . '/includes/mail.inc';
|
5204
|
require_once DRUPAL_ROOT . '/includes/actions.inc';
|
5205
|
require_once DRUPAL_ROOT . '/includes/ajax.inc';
|
5206
|
require_once DRUPAL_ROOT . '/includes/token.inc';
|
5207
|
require_once DRUPAL_ROOT . '/includes/errors.inc';
|
5208
|
|
5209
|
// Detect string handling method
|
5210
|
unicode_check();
|
5211
|
// Undo magic quotes
|
5212
|
fix_gpc_magic();
|
5213
|
// Load all enabled modules
|
5214
|
module_load_all();
|
5215
|
// Make sure all stream wrappers are registered.
|
5216
|
file_get_stream_wrappers();
|
5217
|
// Ensure mt_rand is reseeded, to prevent random values from one page load
|
5218
|
// being exploited to predict random values in subsequent page loads.
|
5219
|
$seed = unpack("L", drupal_random_bytes(4));
|
5220
|
mt_srand($seed[1]);
|
5221
|
|
5222
|
$test_info = &$GLOBALS['drupal_test_info'];
|
5223
|
if (!empty($test_info['in_child_site'])) {
|
5224
|
// Running inside the simpletest child site, log fatal errors to test
|
5225
|
// specific file directory.
|
5226
|
ini_set('log_errors', 1);
|
5227
|
ini_set('error_log', 'public://error.log');
|
5228
|
}
|
5229
|
|
5230
|
// Initialize $_GET['q'] prior to invoking hook_init().
|
5231
|
drupal_path_initialize();
|
5232
|
|
5233
|
// Let all modules take action before the menu system handles the request.
|
5234
|
// We do not want this while running update.php.
|
5235
|
if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
|
5236
|
// Prior to invoking hook_init(), initialize the theme (potentially a custom
|
5237
|
// one for this page), so that:
|
5238
|
// - Modules with hook_init() implementations that call theme() or
|
5239
|
// theme_get_registry() don't initialize the incorrect theme.
|
5240
|
// - The theme can have hook_*_alter() implementations affect page building
|
5241
|
// (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
|
5242
|
// ahead of when rendering starts.
|
5243
|
menu_set_custom_theme();
|
5244
|
drupal_theme_initialize();
|
5245
|
module_invoke_all('init');
|
5246
|
}
|
5247
|
}
|
5248
|
|
5249
|
/**
|
5250
|
* Stores the current page in the cache.
|
5251
|
*
|
5252
|
* If page_compression is enabled, a gzipped version of the page is stored in
|
5253
|
* the cache to avoid compressing the output on each request. The cache entry
|
5254
|
* is unzipped in the relatively rare event that the page is requested by a
|
5255
|
* client without gzip support.
|
5256
|
*
|
5257
|
* Page compression requires the PHP zlib extension
|
5258
|
* (http://php.net/manual/ref.zlib.php).
|
5259
|
*
|
5260
|
* @see drupal_page_header()
|
5261
|
*/
|
5262
|
function drupal_page_set_cache() {
|
5263
|
global $base_root;
|
5264
|
|
5265
|
if (drupal_page_is_cacheable()) {
|
5266
|
|
5267
|
// Check whether the current page might be compressed.
|
5268
|
$page_compressed = variable_get('page_compression', TRUE) && extension_loaded('zlib');
|
5269
|
|
5270
|
$cache = (object) array(
|
5271
|
'cid' => $base_root . request_uri(),
|
5272
|
'data' => array(
|
5273
|
'path' => $_GET['q'],
|
5274
|
'body' => ob_get_clean(),
|
5275
|
'title' => drupal_get_title(),
|
5276
|
'headers' => array(),
|
5277
|
// We need to store whether page was compressed or not,
|
5278
|
// because by the time it is read, the configuration might change.
|
5279
|
'page_compressed' => $page_compressed,
|
5280
|
),
|
5281
|
'expire' => CACHE_TEMPORARY,
|
5282
|
'created' => REQUEST_TIME,
|
5283
|
);
|
5284
|
|
5285
|
// Restore preferred header names based on the lower-case names returned
|
5286
|
// by drupal_get_http_header().
|
5287
|
$header_names = _drupal_set_preferred_header_name();
|
5288
|
foreach (drupal_get_http_header() as $name_lower => $value) {
|
5289
|
$cache->data['headers'][$header_names[$name_lower]] = $value;
|
5290
|
if ($name_lower == 'expires') {
|
5291
|
// Use the actual timestamp from an Expires header if available.
|
5292
|
$cache->expire = strtotime($value);
|
5293
|
}
|
5294
|
}
|
5295
|
|
5296
|
if ($cache->data['body']) {
|
5297
|
if ($page_compressed) {
|
5298
|
$cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
|
5299
|
}
|
5300
|
cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire);
|
5301
|
}
|
5302
|
return $cache;
|
5303
|
}
|
5304
|
}
|
5305
|
|
5306
|
/**
|
5307
|
* Executes a cron run when called.
|
5308
|
*
|
5309
|
* Do not call this function from a test. Use $this->cronRun() instead.
|
5310
|
*
|
5311
|
* @return
|
5312
|
* TRUE if cron ran successfully.
|
5313
|
*/
|
5314
|
function drupal_cron_run() {
|
5315
|
// Allow execution to continue even if the request gets canceled.
|
5316
|
@ignore_user_abort(TRUE);
|
5317
|
|
5318
|
// Prevent session information from being saved while cron is running.
|
5319
|
$original_session_saving = drupal_save_session();
|
5320
|
drupal_save_session(FALSE);
|
5321
|
|
5322
|
// Force the current user to anonymous to ensure consistent permissions on
|
5323
|
// cron runs.
|
5324
|
$original_user = $GLOBALS['user'];
|
5325
|
$GLOBALS['user'] = drupal_anonymous_user();
|
5326
|
|
5327
|
// Try to allocate enough time to run all the hook_cron implementations.
|
5328
|
drupal_set_time_limit(240);
|
5329
|
|
5330
|
$return = FALSE;
|
5331
|
// Grab the defined cron queues.
|
5332
|
$queues = module_invoke_all('cron_queue_info');
|
5333
|
drupal_alter('cron_queue_info', $queues);
|
5334
|
|
5335
|
// Try to acquire cron lock.
|
5336
|
if (!lock_acquire('cron', 240.0)) {
|
5337
|
// Cron is still running normally.
|
5338
|
watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
|
5339
|
}
|
5340
|
else {
|
5341
|
// Make sure every queue exists. There is no harm in trying to recreate an
|
5342
|
// existing queue.
|
5343
|
foreach ($queues as $queue_name => $info) {
|
5344
|
DrupalQueue::get($queue_name)->createQueue();
|
5345
|
}
|
5346
|
|
5347
|
// Iterate through the modules calling their cron handlers (if any):
|
5348
|
foreach (module_implements('cron') as $module) {
|
5349
|
// Do not let an exception thrown by one module disturb another.
|
5350
|
try {
|
5351
|
module_invoke($module, 'cron');
|
5352
|
}
|
5353
|
catch (Exception $e) {
|
5354
|
watchdog_exception('cron', $e);
|
5355
|
}
|
5356
|
}
|
5357
|
|
5358
|
// Record cron time.
|
5359
|
variable_set('cron_last', REQUEST_TIME);
|
5360
|
watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
|
5361
|
|
5362
|
// Release cron lock.
|
5363
|
lock_release('cron');
|
5364
|
|
5365
|
// Return TRUE so other functions can check if it did run successfully
|
5366
|
$return = TRUE;
|
5367
|
}
|
5368
|
|
5369
|
foreach ($queues as $queue_name => $info) {
|
5370
|
if (!empty($info['skip on cron'])) {
|
5371
|
// Do not run if queue wants to skip.
|
5372
|
continue;
|
5373
|
}
|
5374
|
$function = $info['worker callback'];
|
5375
|
$end = time() + (isset($info['time']) ? $info['time'] : 15);
|
5376
|
$queue = DrupalQueue::get($queue_name);
|
5377
|
while (time() < $end && ($item = $queue->claimItem())) {
|
5378
|
try {
|
5379
|
$function($item->data);
|
5380
|
$queue->deleteItem($item);
|
5381
|
}
|
5382
|
catch (Exception $e) {
|
5383
|
// In case of exception log it and leave the item in the queue
|
5384
|
// to be processed again later.
|
5385
|
watchdog_exception('cron', $e);
|
5386
|
}
|
5387
|
}
|
5388
|
}
|
5389
|
// Restore the user.
|
5390
|
$GLOBALS['user'] = $original_user;
|
5391
|
drupal_save_session($original_session_saving);
|
5392
|
|
5393
|
return $return;
|
5394
|
}
|
5395
|
|
5396
|
/**
|
5397
|
* DEPRECATED: Shutdown function: Performs cron cleanup.
|
5398
|
*
|
5399
|
* This function is deprecated because the 'cron_semaphore' variable it
|
5400
|
* references no longer exists. It is therefore no longer used as a shutdown
|
5401
|
* function by Drupal core.
|
5402
|
*
|
5403
|
* @deprecated
|
5404
|
*/
|
5405
|
function drupal_cron_cleanup() {
|
5406
|
// See if the semaphore is still locked.
|
5407
|
if (variable_get('cron_semaphore', FALSE)) {
|
5408
|
watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);
|
5409
|
|
5410
|
// Release cron semaphore.
|
5411
|
variable_del('cron_semaphore');
|
5412
|
}
|
5413
|
}
|
5414
|
|
5415
|
/**
|
5416
|
* Returns information about system object files (modules, themes, etc.).
|
5417
|
*
|
5418
|
* This function is used to find all or some system object files (module files,
|
5419
|
* theme files, etc.) that exist on the site. It searches in several locations,
|
5420
|
* depending on what type of object you are looking for. For instance, if you
|
5421
|
* are looking for modules and call:
|
5422
|
* @code
|
5423
|
* drupal_system_listing("/\.module$/", "modules", 'name', 0);
|
5424
|
* @endcode
|
5425
|
* this function will search the site-wide modules directory (i.e., /modules/),
|
5426
|
* your installation profile's directory (i.e.,
|
5427
|
* /profiles/your_site_profile/modules/), the all-sites directory (i.e.,
|
5428
|
* /sites/all/modules/), and your site-specific directory (i.e.,
|
5429
|
* /sites/your_site_dir/modules/), in that order, and return information about
|
5430
|
* all of the files ending in .module in those directories.
|
5431
|
*
|
5432
|
* The information is returned in an associative array, which can be keyed on
|
5433
|
* the file name ($key = 'filename'), the file name without the extension ($key
|
5434
|
* = 'name'), or the full file stream URI ($key = 'uri'). If you use a key of
|
5435
|
* 'filename' or 'name', files found later in the search will take precedence
|
5436
|
* over files found earlier (unless they belong to a module or theme not
|
5437
|
* compatible with Drupal core); if you choose a key of 'uri', you will get all
|
5438
|
* files found.
|
5439
|
*
|
5440
|
* @param string $mask
|
5441
|
* The preg_match() regular expression for the files to find.
|
5442
|
* @param string $directory
|
5443
|
* The subdirectory name in which the files are found. For example,
|
5444
|
* 'modules' will search in sub-directories of the top-level /modules
|
5445
|
* directory, sub-directories of /sites/all/modules/, etc.
|
5446
|
* @param string $key
|
5447
|
* The key to be used for the associative array returned. Possible values are
|
5448
|
* 'uri', for the file's URI; 'filename', for the basename of the file; and
|
5449
|
* 'name' for the name of the file without the extension. If you choose 'name'
|
5450
|
* or 'filename', only the highest-precedence file will be returned.
|
5451
|
* @param int $min_depth
|
5452
|
* Minimum depth of directories to return files from, relative to each
|
5453
|
* directory searched. For instance, a minimum depth of 2 would find modules
|
5454
|
* inside /modules/node/tests, but not modules directly in /modules/node.
|
5455
|
*
|
5456
|
* @return array
|
5457
|
* An associative array of file objects, keyed on the chosen key. Each element
|
5458
|
* in the array is an object containing file information, with properties:
|
5459
|
* - 'uri': Full URI of the file.
|
5460
|
* - 'filename': File name.
|
5461
|
* - 'name': Name of file without the extension.
|
5462
|
*/
|
5463
|
function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
|
5464
|
$config = conf_path();
|
5465
|
|
5466
|
$searchdir = array($directory);
|
5467
|
$files = array();
|
5468
|
|
5469
|
// The 'profiles' directory contains pristine collections of modules and
|
5470
|
// themes as organized by a distribution. It is pristine in the same way
|
5471
|
// that /modules is pristine for core; users should avoid changing anything
|
5472
|
// there in favor of sites/all or sites/<domain> directories.
|
5473
|
$profiles = array();
|
5474
|
$profile = drupal_get_profile();
|
5475
|
// For SimpleTest to be able to test modules packaged together with a
|
5476
|
// distribution we need to include the profile of the parent site (in which
|
5477
|
// test runs are triggered).
|
5478
|
if (drupal_valid_test_ua()) {
|
5479
|
$testing_profile = variable_get('simpletest_parent_profile', FALSE);
|
5480
|
if ($testing_profile && $testing_profile != $profile) {
|
5481
|
$profiles[] = $testing_profile;
|
5482
|
}
|
5483
|
}
|
5484
|
// In case both profile directories contain the same extension, the actual
|
5485
|
// profile always has precedence.
|
5486
|
$profiles[] = $profile;
|
5487
|
foreach ($profiles as $profile) {
|
5488
|
if (file_exists("profiles/$profile/$directory")) {
|
5489
|
$searchdir[] = "profiles/$profile/$directory";
|
5490
|
}
|
5491
|
}
|
5492
|
|
5493
|
// Always search sites/all/* as well as the global directories.
|
5494
|
$searchdir[] = 'sites/all/' . $directory;
|
5495
|
|
5496
|
if (file_exists("$config/$directory")) {
|
5497
|
$searchdir[] = "$config/$directory";
|
5498
|
}
|
5499
|
|
5500
|
// Get current list of items.
|
5501
|
if (!function_exists('file_scan_directory')) {
|
5502
|
require_once DRUPAL_ROOT . '/includes/file.inc';
|
5503
|
}
|
5504
|
foreach ($searchdir as $dir) {
|
5505
|
$files_to_add = file_scan_directory($dir, $mask, array('key' => $key, 'min_depth' => $min_depth));
|
5506
|
|
5507
|
// Duplicate files found in later search directories take precedence over
|
5508
|
// earlier ones, so we want them to overwrite keys in our resulting
|
5509
|
// $files array.
|
5510
|
// The exception to this is if the later file is from a module or theme not
|
5511
|
// compatible with Drupal core. This may occur during upgrades of Drupal
|
5512
|
// core when new modules exist in core while older contrib modules with the
|
5513
|
// same name exist in a directory such as sites/all/modules/.
|
5514
|
foreach (array_intersect_key($files_to_add, $files) as $file_key => $file) {
|
5515
|
// If it has no info file, then we just behave liberally and accept the
|
5516
|
// new resource on the list for merging.
|
5517
|
if (file_exists($info_file = dirname($file->uri) . '/' . $file->name . '.info')) {
|
5518
|
// Get the .info file for the module or theme this file belongs to.
|
5519
|
$info = drupal_parse_info_file($info_file);
|
5520
|
|
5521
|
// If the module or theme is incompatible with Drupal core, remove it
|
5522
|
// from the array for the current search directory, so it is not
|
5523
|
// overwritten when merged with the $files array.
|
5524
|
if (isset($info['core']) && $info['core'] != DRUPAL_CORE_COMPATIBILITY) {
|
5525
|
unset($files_to_add[$file_key]);
|
5526
|
}
|
5527
|
}
|
5528
|
}
|
5529
|
$files = array_merge($files, $files_to_add);
|
5530
|
}
|
5531
|
|
5532
|
return $files;
|
5533
|
}
|
5534
|
|
5535
|
/**
|
5536
|
* Sets the main page content value for later use.
|
5537
|
*
|
5538
|
* Given the nature of the Drupal page handling, this will be called once with
|
5539
|
* a string or array. We store that and return it later as the block is being
|
5540
|
* displayed.
|
5541
|
*
|
5542
|
* @param $content
|
5543
|
* A string or renderable array representing the body of the page.
|
5544
|
*
|
5545
|
* @return
|
5546
|
* If called without $content, a renderable array representing the body of
|
5547
|
* the page.
|
5548
|
*/
|
5549
|
function drupal_set_page_content($content = NULL) {
|
5550
|
$content_block = &drupal_static(__FUNCTION__, NULL);
|
5551
|
$main_content_display = &drupal_static('system_main_content_added', FALSE);
|
5552
|
|
5553
|
if (!empty($content)) {
|
5554
|
$content_block = (is_array($content) ? $content : array('main' => array('#markup' => $content)));
|
5555
|
}
|
5556
|
else {
|
5557
|
// Indicate that the main content has been requested. We assume that
|
5558
|
// the module requesting the content will be adding it to the page.
|
5559
|
// A module can indicate that it does not handle the content by setting
|
5560
|
// the static variable back to FALSE after calling this function.
|
5561
|
$main_content_display = TRUE;
|
5562
|
return $content_block;
|
5563
|
}
|
5564
|
}
|
5565
|
|
5566
|
/**
|
5567
|
* #pre_render callback to render #browsers into #prefix and #suffix.
|
5568
|
*
|
5569
|
* @param $elements
|
5570
|
* A render array with a '#browsers' property. The '#browsers' property can
|
5571
|
* contain any or all of the following keys:
|
5572
|
* - 'IE': If FALSE, the element is not rendered by Internet Explorer. If
|
5573
|
* TRUE, the element is rendered by Internet Explorer. Can also be a string
|
5574
|
* containing an expression for Internet Explorer to evaluate as part of a
|
5575
|
* conditional comment. For example, this can be set to 'lt IE 7' for the
|
5576
|
* element to be rendered in Internet Explorer 6, but not in Internet
|
5577
|
* Explorer 7 or higher. Defaults to TRUE.
|
5578
|
* - '!IE': If FALSE, the element is not rendered by browsers other than
|
5579
|
* Internet Explorer. If TRUE, the element is rendered by those browsers.
|
5580
|
* Defaults to TRUE.
|
5581
|
* Examples:
|
5582
|
* - To render an element in all browsers, '#browsers' can be left out or set
|
5583
|
* to array('IE' => TRUE, '!IE' => TRUE).
|
5584
|
* - To render an element in Internet Explorer only, '#browsers' can be set
|
5585
|
* to array('!IE' => FALSE).
|
5586
|
* - To render an element in Internet Explorer 6 only, '#browsers' can be set
|
5587
|
* to array('IE' => 'lt IE 7', '!IE' => FALSE).
|
5588
|
* - To render an element in Internet Explorer 8 and higher and in all other
|
5589
|
* browsers, '#browsers' can be set to array('IE' => 'gte IE 8').
|
5590
|
*
|
5591
|
* @return
|
5592
|
* The passed-in element with markup for conditional comments potentially
|
5593
|
* added to '#prefix' and '#suffix'.
|
5594
|
*/
|
5595
|
function drupal_pre_render_conditional_comments($elements) {
|
5596
|
$browsers = isset($elements['#browsers']) ? $elements['#browsers'] : array();
|
5597
|
$browsers += array(
|
5598
|
'IE' => TRUE,
|
5599
|
'!IE' => TRUE,
|
5600
|
);
|
5601
|
|
5602
|
// If rendering in all browsers, no need for conditional comments.
|
5603
|
if ($browsers['IE'] === TRUE && $browsers['!IE']) {
|
5604
|
return $elements;
|
5605
|
}
|
5606
|
|
5607
|
// Determine the conditional comment expression for Internet Explorer to
|
5608
|
// evaluate.
|
5609
|
if ($browsers['IE'] === TRUE) {
|
5610
|
$expression = 'IE';
|
5611
|
}
|
5612
|
elseif ($browsers['IE'] === FALSE) {
|
5613
|
$expression = '!IE';
|
5614
|
}
|
5615
|
else {
|
5616
|
$expression = $browsers['IE'];
|
5617
|
}
|
5618
|
|
5619
|
// Wrap the element's potentially existing #prefix and #suffix properties with
|
5620
|
// conditional comment markup. The conditional comment expression is evaluated
|
5621
|
// by Internet Explorer only. To control the rendering by other browsers,
|
5622
|
// either the "downlevel-hidden" or "downlevel-revealed" technique must be
|
5623
|
// used. See http://en.wikipedia.org/wiki/Conditional_comment for details.
|
5624
|
$elements += array(
|
5625
|
'#prefix' => '',
|
5626
|
'#suffix' => '',
|
5627
|
);
|
5628
|
if (!$browsers['!IE']) {
|
5629
|
// "downlevel-hidden".
|
5630
|
$elements['#prefix'] = "\n<!--[if $expression]>\n" . $elements['#prefix'];
|
5631
|
$elements['#suffix'] .= "<![endif]-->\n";
|
5632
|
}
|
5633
|
else {
|
5634
|
// "downlevel-revealed".
|
5635
|
$elements['#prefix'] = "\n<!--[if $expression]><!-->\n" . $elements['#prefix'];
|
5636
|
$elements['#suffix'] .= "<!--<![endif]-->\n";
|
5637
|
}
|
5638
|
|
5639
|
return $elements;
|
5640
|
}
|
5641
|
|
5642
|
/**
|
5643
|
* #pre_render callback to render a link into #markup.
|
5644
|
*
|
5645
|
* Doing so during pre_render gives modules a chance to alter the link parts.
|
5646
|
*
|
5647
|
* @param $elements
|
5648
|
* A structured array whose keys form the arguments to l():
|
5649
|
* - #title: The link text to pass as argument to l().
|
5650
|
* - #href: The URL path component to pass as argument to l().
|
5651
|
* - #options: (optional) An array of options to pass to l().
|
5652
|
*
|
5653
|
* @return
|
5654
|
* The passed-in elements containing a rendered link in '#markup'.
|
5655
|
*/
|
5656
|
function drupal_pre_render_link($element) {
|
5657
|
// By default, link options to pass to l() are normally set in #options.
|
5658
|
$element += array('#options' => array());
|
5659
|
// However, within the scope of renderable elements, #attributes is a valid
|
5660
|
// way to specify attributes, too. Take them into account, but do not override
|
5661
|
// attributes from #options.
|
5662
|
if (isset($element['#attributes'])) {
|
5663
|
$element['#options'] += array('attributes' => array());
|
5664
|
$element['#options']['attributes'] += $element['#attributes'];
|
5665
|
}
|
5666
|
|
5667
|
// This #pre_render callback can be invoked from inside or outside of a Form
|
5668
|
// API context, and depending on that, a HTML ID may be already set in
|
5669
|
// different locations. #options should have precedence over Form API's #id.
|
5670
|
// #attributes have been taken over into #options above already.
|
5671
|
if (isset($element['#options']['attributes']['id'])) {
|
5672
|
$element['#id'] = $element['#options']['attributes']['id'];
|
5673
|
}
|
5674
|
elseif (isset($element['#id'])) {
|
5675
|
$element['#options']['attributes']['id'] = $element['#id'];
|
5676
|
}
|
5677
|
|
5678
|
// Conditionally invoke ajax_pre_render_element(), if #ajax is set.
|
5679
|
if (isset($element['#ajax']) && !isset($element['#ajax_processed'])) {
|
5680
|
// If no HTML ID was found above, automatically create one.
|
5681
|
if (!isset($element['#id'])) {
|
5682
|
$element['#id'] = $element['#options']['attributes']['id'] = drupal_html_id('ajax-link');
|
5683
|
}
|
5684
|
// If #ajax['path] was not specified, use the href as Ajax request URL.
|
5685
|
if (!isset($element['#ajax']['path'])) {
|
5686
|
$element['#ajax']['path'] = $element['#href'];
|
5687
|
$element['#ajax']['options'] = $element['#options'];
|
5688
|
}
|
5689
|
$element = ajax_pre_render_element($element);
|
5690
|
}
|
5691
|
|
5692
|
$element['#markup'] = l($element['#title'], $element['#href'], $element['#options']);
|
5693
|
return $element;
|
5694
|
}
|
5695
|
|
5696
|
/**
|
5697
|
* #pre_render callback that collects child links into a single array.
|
5698
|
*
|
5699
|
* This function can be added as a pre_render callback for a renderable array,
|
5700
|
* usually one which will be themed by theme_links(). It iterates through all
|
5701
|
* unrendered children of the element, collects any #links properties it finds,
|
5702
|
* merges them into the parent element's #links array, and prevents those
|
5703
|
* children from being rendered separately.
|
5704
|
*
|
5705
|
* The purpose of this is to allow links to be logically grouped into related
|
5706
|
* categories, so that each child group can be rendered as its own list of
|
5707
|
* links if drupal_render() is called on it, but calling drupal_render() on the
|
5708
|
* parent element will still produce a single list containing all the remaining
|
5709
|
* links, regardless of what group they were in.
|
5710
|
*
|
5711
|
* A typical example comes from node links, which are stored in a renderable
|
5712
|
* array similar to this:
|
5713
|
* @code
|
5714
|
* $node->content['links'] = array(
|
5715
|
* '#theme' => 'links__node',
|
5716
|
* '#pre_render' => array('drupal_pre_render_links'),
|
5717
|
* 'comment' => array(
|
5718
|
* '#theme' => 'links__node__comment',
|
5719
|
* '#links' => array(
|
5720
|
* // An array of links associated with node comments, suitable for
|
5721
|
* // passing in to theme_links().
|
5722
|
* ),
|
5723
|
* ),
|
5724
|
* 'statistics' => array(
|
5725
|
* '#theme' => 'links__node__statistics',
|
5726
|
* '#links' => array(
|
5727
|
* // An array of links associated with node statistics, suitable for
|
5728
|
* // passing in to theme_links().
|
5729
|
* ),
|
5730
|
* ),
|
5731
|
* 'translation' => array(
|
5732
|
* '#theme' => 'links__node__translation',
|
5733
|
* '#links' => array(
|
5734
|
* // An array of links associated with node translation, suitable for
|
5735
|
* // passing in to theme_links().
|
5736
|
* ),
|
5737
|
* ),
|
5738
|
* );
|
5739
|
* @endcode
|
5740
|
*
|
5741
|
* In this example, the links are grouped by functionality, which can be
|
5742
|
* helpful to themers who want to display certain kinds of links independently.
|
5743
|
* For example, adding this code to node.tpl.php will result in the comment
|
5744
|
* links being rendered as a single list:
|
5745
|
* @code
|
5746
|
* print render($content['links']['comment']);
|
5747
|
* @endcode
|
5748
|
*
|
5749
|
* (where $node->content has been transformed into $content before handing
|
5750
|
* control to the node.tpl.php template).
|
5751
|
*
|
5752
|
* The pre_render function defined here allows the above flexibility, but also
|
5753
|
* allows the following code to be used to render all remaining links into a
|
5754
|
* single list, regardless of their group:
|
5755
|
* @code
|
5756
|
* print render($content['links']);
|
5757
|
* @endcode
|
5758
|
*
|
5759
|
* In the above example, this will result in the statistics and translation
|
5760
|
* links being rendered together in a single list (but not the comment links,
|
5761
|
* which were rendered previously on their own).
|
5762
|
*
|
5763
|
* Because of the way this function works, the individual properties of each
|
5764
|
* group (for example, a group-specific #theme property such as
|
5765
|
* 'links__node__comment' in the example above, or any other property such as
|
5766
|
* #attributes or #pre_render that is attached to it) are only used when that
|
5767
|
* group is rendered on its own. When the group is rendered together with other
|
5768
|
* children, these child-specific properties are ignored, and only the overall
|
5769
|
* properties of the parent are used.
|
5770
|
*/
|
5771
|
function drupal_pre_render_links($element) {
|
5772
|
$element += array('#links' => array());
|
5773
|
foreach (element_children($element) as $key) {
|
5774
|
$child = &$element[$key];
|
5775
|
// If the child has links which have not been printed yet and the user has
|
5776
|
// access to it, merge its links in to the parent.
|
5777
|
if (isset($child['#links']) && empty($child['#printed']) && (!isset($child['#access']) || $child['#access'])) {
|
5778
|
$element['#links'] += $child['#links'];
|
5779
|
// Mark the child as having been printed already (so that its links
|
5780
|
// cannot be mistakenly rendered twice).
|
5781
|
$child['#printed'] = TRUE;
|
5782
|
}
|
5783
|
}
|
5784
|
return $element;
|
5785
|
}
|
5786
|
|
5787
|
/**
|
5788
|
* #pre_render callback to append contents in #markup to #children.
|
5789
|
*
|
5790
|
* This needs to be a #pre_render callback, because eventually assigned
|
5791
|
* #theme_wrappers will expect the element's rendered content in #children.
|
5792
|
* Note that if also a #theme is defined for the element, then the result of
|
5793
|
* the theme callback will override #children.
|
5794
|
*
|
5795
|
* @param $elements
|
5796
|
* A structured array using the #markup key.
|
5797
|
*
|
5798
|
* @return
|
5799
|
* The passed-in elements, but #markup appended to #children.
|
5800
|
*
|
5801
|
* @see drupal_render()
|
5802
|
*/
|
5803
|
function drupal_pre_render_markup($elements) {
|
5804
|
$elements['#children'] = $elements['#markup'];
|
5805
|
return $elements;
|
5806
|
}
|
5807
|
|
5808
|
/**
|
5809
|
* Renders the page, including all theming.
|
5810
|
*
|
5811
|
* @param $page
|
5812
|
* A string or array representing the content of a page. The array consists of
|
5813
|
* the following keys:
|
5814
|
* - #type: Value is always 'page'. This pushes the theming through
|
5815
|
* page.tpl.php (required).
|
5816
|
* - #show_messages: Suppress drupal_get_message() items. Used by Batch
|
5817
|
* API (optional).
|
5818
|
*
|
5819
|
* @see hook_page_alter()
|
5820
|
* @see element_info()
|
5821
|
*/
|
5822
|
function drupal_render_page($page) {
|
5823
|
$main_content_display = &drupal_static('system_main_content_added', FALSE);
|
5824
|
|
5825
|
// Allow menu callbacks to return strings or arbitrary arrays to render.
|
5826
|
// If the array returned is not of #type page directly, we need to fill
|
5827
|
// in the page with defaults.
|
5828
|
if (is_string($page) || (is_array($page) && (!isset($page['#type']) || ($page['#type'] != 'page')))) {
|
5829
|
drupal_set_page_content($page);
|
5830
|
$page = element_info('page');
|
5831
|
}
|
5832
|
|
5833
|
// Modules can add elements to $page as needed in hook_page_build().
|
5834
|
foreach (module_implements('page_build') as $module) {
|
5835
|
$function = $module . '_page_build';
|
5836
|
$function($page);
|
5837
|
}
|
5838
|
// Modules alter the $page as needed. Blocks are populated into regions like
|
5839
|
// 'sidebar_first', 'footer', etc.
|
5840
|
drupal_alter('page', $page);
|
5841
|
|
5842
|
// If no module has taken care of the main content, add it to the page now.
|
5843
|
// This allows the site to still be usable even if no modules that
|
5844
|
// control page regions (for example, the Block module) are enabled.
|
5845
|
if (!$main_content_display) {
|
5846
|
$page['content']['system_main'] = drupal_set_page_content();
|
5847
|
}
|
5848
|
|
5849
|
return drupal_render($page);
|
5850
|
}
|
5851
|
|
5852
|
/**
|
5853
|
* Renders HTML given a structured array tree.
|
5854
|
*
|
5855
|
* Recursively iterates over each of the array elements, generating HTML code.
|
5856
|
*
|
5857
|
* Renderable arrays have two kinds of key/value pairs: properties and
|
5858
|
* children. Properties have keys starting with '#' and their values influence
|
5859
|
* how the array will be rendered. Children are all elements whose keys do not
|
5860
|
* start with a '#'. Their values should be renderable arrays themselves,
|
5861
|
* which will be rendered during the rendering of the parent array. The markup
|
5862
|
* provided by the children is typically inserted into the markup generated by
|
5863
|
* the parent array.
|
5864
|
*
|
5865
|
* HTML generation for a renderable array, and the treatment of any children,
|
5866
|
* is controlled by two properties containing theme functions, #theme and
|
5867
|
* #theme_wrappers.
|
5868
|
*
|
5869
|
* #theme is the theme function called first. If it is set and the element has
|
5870
|
* any children, it is the responsibility of the theme function to render
|
5871
|
* these children. For elements that are not allowed to have any children,
|
5872
|
* e.g. buttons or textfields, the theme function can be used to render the
|
5873
|
* element itself. If #theme is not present and the element has children, each
|
5874
|
* child is itself rendered by a call to drupal_render(), and the results are
|
5875
|
* concatenated.
|
5876
|
*
|
5877
|
* The #theme_wrappers property contains an array of theme functions which will
|
5878
|
* be called, in order, after #theme has run. These can be used to add further
|
5879
|
* markup around the rendered children; e.g., fieldsets add the required markup
|
5880
|
* for a fieldset around their rendered child elements. All wrapper theme
|
5881
|
* functions have to include the element's #children property in their output,
|
5882
|
* as it contains the output of the previous theme functions and the rendered
|
5883
|
* children.
|
5884
|
*
|
5885
|
* For example, for the form element type, by default only the #theme_wrappers
|
5886
|
* property is set, which adds the form markup around the rendered child
|
5887
|
* elements of the form. This allows you to set the #theme property on a
|
5888
|
* specific form to a custom theme function, giving you complete control over
|
5889
|
* the placement of the form's children while not at all having to deal with
|
5890
|
* the form markup itself.
|
5891
|
*
|
5892
|
* drupal_render() can optionally cache the rendered output of elements to
|
5893
|
* improve performance. To use drupal_render() caching, set the element's #cache
|
5894
|
* property to an associative array with one or several of the following keys:
|
5895
|
* - 'keys': An array of one or more keys that identify the element. If 'keys'
|
5896
|
* is set, the cache ID is created automatically from these keys. See
|
5897
|
* drupal_render_cid_create().
|
5898
|
* - 'granularity' (optional): Define the cache granularity using binary
|
5899
|
* combinations of the cache granularity constants, e.g.
|
5900
|
* DRUPAL_CACHE_PER_USER to cache for each user separately or
|
5901
|
* DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE to cache separately for each
|
5902
|
* page and role. If not specified the element is cached globally for each
|
5903
|
* theme and language.
|
5904
|
* - 'cid': Specify the cache ID directly. Either 'keys' or 'cid' is required.
|
5905
|
* If 'cid' is set, 'keys' and 'granularity' are ignored. Use only if you
|
5906
|
* have special requirements.
|
5907
|
* - 'expire': Set to one of the cache lifetime constants.
|
5908
|
* - 'bin': Specify a cache bin to cache the element in. Defaults to 'cache'.
|
5909
|
*
|
5910
|
* This function is usually called from within another function, like
|
5911
|
* drupal_get_form() or a theme function. Elements are sorted internally
|
5912
|
* using uasort(). Since this is expensive, when passing already sorted
|
5913
|
* elements to drupal_render(), for example from a database query, set
|
5914
|
* $elements['#sorted'] = TRUE to avoid sorting them a second time.
|
5915
|
*
|
5916
|
* drupal_render() flags each element with a '#printed' status to indicate that
|
5917
|
* the element has been rendered, which allows individual elements of a given
|
5918
|
* array to be rendered independently and prevents them from being rendered
|
5919
|
* more than once on subsequent calls to drupal_render() (e.g., as part of a
|
5920
|
* larger array). If the same array or array element is passed more than once
|
5921
|
* to drupal_render(), it simply returns an empty string.
|
5922
|
*
|
5923
|
* @param array $elements
|
5924
|
* The structured array describing the data to be rendered.
|
5925
|
*
|
5926
|
* @return string
|
5927
|
* The rendered HTML.
|
5928
|
*/
|
5929
|
function drupal_render(&$elements) {
|
5930
|
// Early-return nothing if user does not have access.
|
5931
|
if (empty($elements) || (isset($elements['#access']) && !$elements['#access'])) {
|
5932
|
return '';
|
5933
|
}
|
5934
|
|
5935
|
// Do not print elements twice.
|
5936
|
if (!empty($elements['#printed'])) {
|
5937
|
return '';
|
5938
|
}
|
5939
|
|
5940
|
// Try to fetch the element's markup from cache and return.
|
5941
|
if (isset($elements['#cache'])) {
|
5942
|
$cached_output = drupal_render_cache_get($elements);
|
5943
|
if ($cached_output !== FALSE) {
|
5944
|
return $cached_output;
|
5945
|
}
|
5946
|
}
|
5947
|
|
5948
|
// If #markup is set, ensure #type is set. This allows to specify just #markup
|
5949
|
// on an element without setting #type.
|
5950
|
if (isset($elements['#markup']) && !isset($elements['#type'])) {
|
5951
|
$elements['#type'] = 'markup';
|
5952
|
}
|
5953
|
|
5954
|
// If the default values for this element have not been loaded yet, populate
|
5955
|
// them.
|
5956
|
if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
|
5957
|
$elements += element_info($elements['#type']);
|
5958
|
}
|
5959
|
|
5960
|
// Make any final changes to the element before it is rendered. This means
|
5961
|
// that the $element or the children can be altered or corrected before the
|
5962
|
// element is rendered into the final text.
|
5963
|
if (isset($elements['#pre_render'])) {
|
5964
|
foreach ($elements['#pre_render'] as $function) {
|
5965
|
if (function_exists($function)) {
|
5966
|
$elements = $function($elements);
|
5967
|
}
|
5968
|
}
|
5969
|
}
|
5970
|
|
5971
|
// Allow #pre_render to abort rendering.
|
5972
|
if (!empty($elements['#printed'])) {
|
5973
|
return '';
|
5974
|
}
|
5975
|
|
5976
|
// Get the children of the element, sorted by weight.
|
5977
|
$children = element_children($elements, TRUE);
|
5978
|
|
5979
|
// Initialize this element's #children, unless a #pre_render callback already
|
5980
|
// preset #children.
|
5981
|
if (!isset($elements['#children'])) {
|
5982
|
$elements['#children'] = '';
|
5983
|
}
|
5984
|
// Call the element's #theme function if it is set. Then any children of the
|
5985
|
// element have to be rendered there.
|
5986
|
if (isset($elements['#theme'])) {
|
5987
|
$elements['#children'] = theme($elements['#theme'], $elements);
|
5988
|
}
|
5989
|
// If #theme was not set and the element has children, render them now.
|
5990
|
// This is the same process as drupal_render_children() but is inlined
|
5991
|
// for speed.
|
5992
|
if ($elements['#children'] == '') {
|
5993
|
foreach ($children as $key) {
|
5994
|
$elements['#children'] .= drupal_render($elements[$key]);
|
5995
|
}
|
5996
|
}
|
5997
|
|
5998
|
// Let the theme functions in #theme_wrappers add markup around the rendered
|
5999
|
// children.
|
6000
|
if (isset($elements['#theme_wrappers'])) {
|
6001
|
foreach ($elements['#theme_wrappers'] as $theme_wrapper) {
|
6002
|
$elements['#children'] = theme($theme_wrapper, $elements);
|
6003
|
}
|
6004
|
}
|
6005
|
|
6006
|
// Filter the outputted content and make any last changes before the
|
6007
|
// content is sent to the browser. The changes are made on $content
|
6008
|
// which allows the output'ed text to be filtered.
|
6009
|
if (isset($elements['#post_render'])) {
|
6010
|
foreach ($elements['#post_render'] as $function) {
|
6011
|
if (function_exists($function)) {
|
6012
|
$elements['#children'] = $function($elements['#children'], $elements);
|
6013
|
}
|
6014
|
}
|
6015
|
}
|
6016
|
|
6017
|
// Add any JavaScript state information associated with the element.
|
6018
|
if (!empty($elements['#states'])) {
|
6019
|
drupal_process_states($elements);
|
6020
|
}
|
6021
|
|
6022
|
// Add additional libraries, CSS, JavaScript an other custom
|
6023
|
// attached data associated with this element.
|
6024
|
if (!empty($elements['#attached'])) {
|
6025
|
drupal_process_attached($elements);
|
6026
|
}
|
6027
|
|
6028
|
$prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
|
6029
|
$suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
|
6030
|
$output = $prefix . $elements['#children'] . $suffix;
|
6031
|
|
6032
|
// Cache the processed element if #cache is set.
|
6033
|
if (isset($elements['#cache'])) {
|
6034
|
drupal_render_cache_set($output, $elements);
|
6035
|
}
|
6036
|
|
6037
|
$elements['#printed'] = TRUE;
|
6038
|
return $output;
|
6039
|
}
|
6040
|
|
6041
|
/**
|
6042
|
* Renders children of an element and concatenates them.
|
6043
|
*
|
6044
|
* @param array $element
|
6045
|
* The structured array whose children shall be rendered.
|
6046
|
* @param array $children_keys
|
6047
|
* (optional) If the keys of the element's children are already known, they
|
6048
|
* can be passed in to save another run of element_children().
|
6049
|
*
|
6050
|
* @return string
|
6051
|
* The rendered HTML of all children of the element.
|
6052
|
|
6053
|
* @see drupal_render()
|
6054
|
*/
|
6055
|
function drupal_render_children(&$element, $children_keys = NULL) {
|
6056
|
if ($children_keys === NULL) {
|
6057
|
$children_keys = element_children($element);
|
6058
|
}
|
6059
|
$output = '';
|
6060
|
foreach ($children_keys as $key) {
|
6061
|
if (!empty($element[$key])) {
|
6062
|
$output .= drupal_render($element[$key]);
|
6063
|
}
|
6064
|
}
|
6065
|
return $output;
|
6066
|
}
|
6067
|
|
6068
|
/**
|
6069
|
* Renders an element.
|
6070
|
*
|
6071
|
* This function renders an element using drupal_render(). The top level
|
6072
|
* element is shown with show() before rendering, so it will always be rendered
|
6073
|
* even if hide() had been previously used on it.
|
6074
|
*
|
6075
|
* @param $element
|
6076
|
* The element to be rendered.
|
6077
|
*
|
6078
|
* @return
|
6079
|
* The rendered element.
|
6080
|
*
|
6081
|
* @see drupal_render()
|
6082
|
* @see show()
|
6083
|
* @see hide()
|
6084
|
*/
|
6085
|
function render(&$element) {
|
6086
|
if (is_array($element)) {
|
6087
|
show($element);
|
6088
|
return drupal_render($element);
|
6089
|
}
|
6090
|
else {
|
6091
|
// Safe-guard for inappropriate use of render() on flat variables: return
|
6092
|
// the variable as-is.
|
6093
|
return $element;
|
6094
|
}
|
6095
|
}
|
6096
|
|
6097
|
/**
|
6098
|
* Hides an element from later rendering.
|
6099
|
*
|
6100
|
* The first time render() or drupal_render() is called on an element tree,
|
6101
|
* as each element in the tree is rendered, it is marked with a #printed flag
|
6102
|
* and the rendered children of the element are cached. Subsequent calls to
|
6103
|
* render() or drupal_render() will not traverse the child tree of this element
|
6104
|
* again: they will just use the cached children. So if you want to hide an
|
6105
|
* element, be sure to call hide() on the element before its parent tree is
|
6106
|
* rendered for the first time, as it will have no effect on subsequent
|
6107
|
* renderings of the parent tree.
|
6108
|
*
|
6109
|
* @param $element
|
6110
|
* The element to be hidden.
|
6111
|
*
|
6112
|
* @return
|
6113
|
* The element.
|
6114
|
*
|
6115
|
* @see render()
|
6116
|
* @see show()
|
6117
|
*/
|
6118
|
function hide(&$element) {
|
6119
|
$element['#printed'] = TRUE;
|
6120
|
return $element;
|
6121
|
}
|
6122
|
|
6123
|
/**
|
6124
|
* Shows a hidden element for later rendering.
|
6125
|
*
|
6126
|
* You can also use render($element), which shows the element while rendering
|
6127
|
* it.
|
6128
|
*
|
6129
|
* The first time render() or drupal_render() is called on an element tree,
|
6130
|
* as each element in the tree is rendered, it is marked with a #printed flag
|
6131
|
* and the rendered children of the element are cached. Subsequent calls to
|
6132
|
* render() or drupal_render() will not traverse the child tree of this element
|
6133
|
* again: they will just use the cached children. So if you want to show an
|
6134
|
* element, be sure to call show() on the element before its parent tree is
|
6135
|
* rendered for the first time, as it will have no effect on subsequent
|
6136
|
* renderings of the parent tree.
|
6137
|
*
|
6138
|
* @param $element
|
6139
|
* The element to be shown.
|
6140
|
*
|
6141
|
* @return
|
6142
|
* The element.
|
6143
|
*
|
6144
|
* @see render()
|
6145
|
* @see hide()
|
6146
|
*/
|
6147
|
function show(&$element) {
|
6148
|
$element['#printed'] = FALSE;
|
6149
|
return $element;
|
6150
|
}
|
6151
|
|
6152
|
/**
|
6153
|
* Gets the rendered output of a renderable element from the cache.
|
6154
|
*
|
6155
|
* @param $elements
|
6156
|
* A renderable array.
|
6157
|
*
|
6158
|
* @return
|
6159
|
* A markup string containing the rendered content of the element, or FALSE
|
6160
|
* if no cached copy of the element is available.
|
6161
|
*
|
6162
|
* @see drupal_render()
|
6163
|
* @see drupal_render_cache_set()
|
6164
|
*/
|
6165
|
function drupal_render_cache_get($elements) {
|
6166
|
if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
|
6167
|
return FALSE;
|
6168
|
}
|
6169
|
$bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
|
6170
|
|
6171
|
if (!empty($cid) && $cache = cache_get($cid, $bin)) {
|
6172
|
// Add additional libraries, JavaScript, CSS and other data attached
|
6173
|
// to this element.
|
6174
|
if (isset($cache->data['#attached'])) {
|
6175
|
drupal_process_attached($cache->data);
|
6176
|
}
|
6177
|
// Return the rendered output.
|
6178
|
return $cache->data['#markup'];
|
6179
|
}
|
6180
|
return FALSE;
|
6181
|
}
|
6182
|
|
6183
|
/**
|
6184
|
* Caches the rendered output of a renderable element.
|
6185
|
*
|
6186
|
* This is called by drupal_render() if the #cache property is set on an
|
6187
|
* element.
|
6188
|
*
|
6189
|
* @param $markup
|
6190
|
* The rendered output string of $elements.
|
6191
|
* @param $elements
|
6192
|
* A renderable array.
|
6193
|
*
|
6194
|
* @see drupal_render_cache_get()
|
6195
|
*/
|
6196
|
function drupal_render_cache_set(&$markup, $elements) {
|
6197
|
// Create the cache ID for the element.
|
6198
|
if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
|
6199
|
return FALSE;
|
6200
|
}
|
6201
|
|
6202
|
// Cache implementations are allowed to modify the markup, to support
|
6203
|
// replacing markup with edge-side include commands. The supporting cache
|
6204
|
// backend will store the markup in some other key (like
|
6205
|
// $data['#real-value']) and return an include command instead. When the
|
6206
|
// ESI command is executed by the content accelerator, the real value can
|
6207
|
// be retrieved and used.
|
6208
|
$data['#markup'] = &$markup;
|
6209
|
// Persist attached data associated with this element.
|
6210
|
$attached = drupal_render_collect_attached($elements, TRUE);
|
6211
|
if ($attached) {
|
6212
|
$data['#attached'] = $attached;
|
6213
|
}
|
6214
|
$bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
|
6215
|
$expire = isset($elements['#cache']['expire']) ? $elements['#cache']['expire'] : CACHE_PERMANENT;
|
6216
|
cache_set($cid, $data, $bin, $expire);
|
6217
|
}
|
6218
|
|
6219
|
/**
|
6220
|
* Collects #attached for an element and its children into a single array.
|
6221
|
*
|
6222
|
* When caching elements, it is necessary to collect all libraries, JavaScript
|
6223
|
* and CSS into a single array, from both the element itself and all child
|
6224
|
* elements. This allows drupal_render() to add these back to the page when the
|
6225
|
* element is returned from cache.
|
6226
|
*
|
6227
|
* @param $elements
|
6228
|
* The element to collect #attached from.
|
6229
|
* @param $return
|
6230
|
* Whether to return the attached elements and reset the internal static.
|
6231
|
*
|
6232
|
* @return
|
6233
|
* The #attached array for this element and its descendants.
|
6234
|
*/
|
6235
|
function drupal_render_collect_attached($elements, $return = FALSE) {
|
6236
|
$attached = &drupal_static(__FUNCTION__, array());
|
6237
|
|
6238
|
// Collect all #attached for this element.
|
6239
|
if (isset($elements['#attached'])) {
|
6240
|
foreach ($elements['#attached'] as $key => $value) {
|
6241
|
if (!isset($attached[$key])) {
|
6242
|
$attached[$key] = array();
|
6243
|
}
|
6244
|
$attached[$key] = array_merge($attached[$key], $value);
|
6245
|
}
|
6246
|
}
|
6247
|
if ($children = element_children($elements)) {
|
6248
|
foreach ($children as $child) {
|
6249
|
drupal_render_collect_attached($elements[$child]);
|
6250
|
}
|
6251
|
}
|
6252
|
|
6253
|
// If this was the first call to the function, return all attached elements
|
6254
|
// and reset the static cache.
|
6255
|
if ($return) {
|
6256
|
$return = $attached;
|
6257
|
$attached = array();
|
6258
|
return $return;
|
6259
|
}
|
6260
|
}
|
6261
|
|
6262
|
/**
|
6263
|
* Prepares an element for caching based on a query.
|
6264
|
*
|
6265
|
* This smart caching strategy saves Drupal from querying and rendering to HTML
|
6266
|
* when the underlying query is unchanged.
|
6267
|
*
|
6268
|
* Expensive queries should use the query builder to create the query and then
|
6269
|
* call this function. Executing the query and formatting results should happen
|
6270
|
* in a #pre_render callback.
|
6271
|
*
|
6272
|
* @param $query
|
6273
|
* A select query object as returned by db_select().
|
6274
|
* @param $function
|
6275
|
* The name of the function doing this caching. A _pre_render suffix will be
|
6276
|
* added to this string and is also part of the cache key in
|
6277
|
* drupal_render_cache_set() and drupal_render_cache_get().
|
6278
|
* @param $expire
|
6279
|
* The cache expire time, passed eventually to cache_set().
|
6280
|
* @param $granularity
|
6281
|
* One or more granularity constants passed to drupal_render_cid_parts().
|
6282
|
*
|
6283
|
* @return
|
6284
|
* A renderable array with the following keys and values:
|
6285
|
* - #query: The passed-in $query.
|
6286
|
* - #pre_render: $function with a _pre_render suffix.
|
6287
|
* - #cache: An associative array prepared for drupal_render_cache_set().
|
6288
|
*/
|
6289
|
function drupal_render_cache_by_query($query, $function, $expire = CACHE_TEMPORARY, $granularity = NULL) {
|
6290
|
$cache_keys = array_merge(array($function), drupal_render_cid_parts($granularity));
|
6291
|
$query->preExecute();
|
6292
|
$cache_keys[] = hash('sha256', serialize(array((string) $query, $query->getArguments())));
|
6293
|
return array(
|
6294
|
'#query' => $query,
|
6295
|
'#pre_render' => array($function . '_pre_render'),
|
6296
|
'#cache' => array(
|
6297
|
'keys' => $cache_keys,
|
6298
|
'expire' => $expire,
|
6299
|
),
|
6300
|
);
|
6301
|
}
|
6302
|
|
6303
|
/**
|
6304
|
* Returns cache ID parts for building a cache ID.
|
6305
|
*
|
6306
|
* @param $granularity
|
6307
|
* One or more cache granularity constants. For example, to cache separately
|
6308
|
* for each user, use DRUPAL_CACHE_PER_USER. To cache separately for each
|
6309
|
* page and role, use the expression:
|
6310
|
* @code
|
6311
|
* DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE
|
6312
|
* @endcode
|
6313
|
*
|
6314
|
* @return
|
6315
|
* An array of cache ID parts, always containing the active theme. If the
|
6316
|
* locale module is enabled it also contains the active language. If
|
6317
|
* $granularity was passed in, more parts are added.
|
6318
|
*/
|
6319
|
function drupal_render_cid_parts($granularity = NULL) {
|
6320
|
global $theme, $base_root, $user;
|
6321
|
|
6322
|
$cid_parts[] = $theme;
|
6323
|
// If Locale is enabled but we have only one language we do not need it as cid
|
6324
|
// part.
|
6325
|
if (drupal_multilingual()) {
|
6326
|
foreach (language_types_configurable() as $language_type) {
|
6327
|
$cid_parts[] = $GLOBALS[$language_type]->language;
|
6328
|
}
|
6329
|
}
|
6330
|
|
6331
|
if (!empty($granularity)) {
|
6332
|
// 'PER_ROLE' and 'PER_USER' are mutually exclusive. 'PER_USER' can be a
|
6333
|
// resource drag for sites with many users, so when a module is being
|
6334
|
// equivocal, we favor the less expensive 'PER_ROLE' pattern.
|
6335
|
if ($granularity & DRUPAL_CACHE_PER_ROLE) {
|
6336
|
$cid_parts[] = 'r.' . implode(',', array_keys($user->roles));
|
6337
|
}
|
6338
|
elseif ($granularity & DRUPAL_CACHE_PER_USER) {
|
6339
|
$cid_parts[] = "u.$user->uid";
|
6340
|
}
|
6341
|
|
6342
|
if ($granularity & DRUPAL_CACHE_PER_PAGE) {
|
6343
|
$cid_parts[] = $base_root . request_uri();
|
6344
|
}
|
6345
|
}
|
6346
|
|
6347
|
return $cid_parts;
|
6348
|
}
|
6349
|
|
6350
|
/**
|
6351
|
* Creates the cache ID for a renderable element.
|
6352
|
*
|
6353
|
* This creates the cache ID string, either by returning the #cache['cid']
|
6354
|
* property if present or by building the cache ID out of the #cache['keys']
|
6355
|
* and, optionally, the #cache['granularity'] properties.
|
6356
|
*
|
6357
|
* @param $elements
|
6358
|
* A renderable array.
|
6359
|
*
|
6360
|
* @return
|
6361
|
* The cache ID string, or FALSE if the element may not be cached.
|
6362
|
*/
|
6363
|
function drupal_render_cid_create($elements) {
|
6364
|
if (isset($elements['#cache']['cid'])) {
|
6365
|
return $elements['#cache']['cid'];
|
6366
|
}
|
6367
|
elseif (isset($elements['#cache']['keys'])) {
|
6368
|
$granularity = isset($elements['#cache']['granularity']) ? $elements['#cache']['granularity'] : NULL;
|
6369
|
// Merge in additional cache ID parts based provided by drupal_render_cid_parts().
|
6370
|
$cid_parts = array_merge($elements['#cache']['keys'], drupal_render_cid_parts($granularity));
|
6371
|
return implode(':', $cid_parts);
|
6372
|
}
|
6373
|
return FALSE;
|
6374
|
}
|
6375
|
|
6376
|
/**
|
6377
|
* Function used by uasort to sort structured arrays by weight.
|
6378
|
*/
|
6379
|
function element_sort($a, $b) {
|
6380
|
$a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
|
6381
|
$b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
|
6382
|
if ($a_weight == $b_weight) {
|
6383
|
return 0;
|
6384
|
}
|
6385
|
return ($a_weight < $b_weight) ? -1 : 1;
|
6386
|
}
|
6387
|
|
6388
|
/**
|
6389
|
* Array sorting callback; sorts elements by title.
|
6390
|
*/
|
6391
|
function element_sort_by_title($a, $b) {
|
6392
|
$a_title = (is_array($a) && isset($a['#title'])) ? $a['#title'] : '';
|
6393
|
$b_title = (is_array($b) && isset($b['#title'])) ? $b['#title'] : '';
|
6394
|
return strnatcasecmp($a_title, $b_title);
|
6395
|
}
|
6396
|
|
6397
|
/**
|
6398
|
* Retrieves the default properties for the defined element type.
|
6399
|
*
|
6400
|
* @param $type
|
6401
|
* An element type as defined by hook_element_info().
|
6402
|
*/
|
6403
|
function element_info($type) {
|
6404
|
// Use the advanced drupal_static() pattern, since this is called very often.
|
6405
|
static $drupal_static_fast;
|
6406
|
if (!isset($drupal_static_fast)) {
|
6407
|
$drupal_static_fast['cache'] = &drupal_static(__FUNCTION__);
|
6408
|
}
|
6409
|
$cache = &$drupal_static_fast['cache'];
|
6410
|
|
6411
|
if (!isset($cache)) {
|
6412
|
$cache = module_invoke_all('element_info');
|
6413
|
foreach ($cache as $element_type => $info) {
|
6414
|
$cache[$element_type]['#type'] = $element_type;
|
6415
|
}
|
6416
|
// Allow modules to alter the element type defaults.
|
6417
|
drupal_alter('element_info', $cache);
|
6418
|
}
|
6419
|
|
6420
|
return isset($cache[$type]) ? $cache[$type] : array();
|
6421
|
}
|
6422
|
|
6423
|
/**
|
6424
|
* Retrieves a single property for the defined element type.
|
6425
|
*
|
6426
|
* @param $type
|
6427
|
* An element type as defined by hook_element_info().
|
6428
|
* @param $property_name
|
6429
|
* The property within the element type that should be returned.
|
6430
|
* @param $default
|
6431
|
* (Optional) The value to return if the element type does not specify a
|
6432
|
* value for the property. Defaults to NULL.
|
6433
|
*/
|
6434
|
function element_info_property($type, $property_name, $default = NULL) {
|
6435
|
return (($info = element_info($type)) && array_key_exists($property_name, $info)) ? $info[$property_name] : $default;
|
6436
|
}
|
6437
|
|
6438
|
/**
|
6439
|
* Sorts a structured array by the 'weight' element.
|
6440
|
*
|
6441
|
* Note that the sorting is by the 'weight' array element, not by the render
|
6442
|
* element property '#weight'.
|
6443
|
*
|
6444
|
* Callback for uasort() used in various functions.
|
6445
|
*
|
6446
|
* @param $a
|
6447
|
* First item for comparison. The compared items should be associative arrays
|
6448
|
* that optionally include a 'weight' element. For items without a 'weight'
|
6449
|
* element, a default value of 0 will be used.
|
6450
|
* @param $b
|
6451
|
* Second item for comparison.
|
6452
|
*/
|
6453
|
function drupal_sort_weight($a, $b) {
|
6454
|
$a_weight = (is_array($a) && isset($a['weight'])) ? $a['weight'] : 0;
|
6455
|
$b_weight = (is_array($b) && isset($b['weight'])) ? $b['weight'] : 0;
|
6456
|
if ($a_weight == $b_weight) {
|
6457
|
return 0;
|
6458
|
}
|
6459
|
return ($a_weight < $b_weight) ? -1 : 1;
|
6460
|
}
|
6461
|
|
6462
|
/**
|
6463
|
* Array sorting callback; sorts elements by 'title' key.
|
6464
|
*/
|
6465
|
function drupal_sort_title($a, $b) {
|
6466
|
if (!isset($b['title'])) {
|
6467
|
return -1;
|
6468
|
}
|
6469
|
if (!isset($a['title'])) {
|
6470
|
return 1;
|
6471
|
}
|
6472
|
return strcasecmp($a['title'], $b['title']);
|
6473
|
}
|
6474
|
|
6475
|
/**
|
6476
|
* Checks if the key is a property.
|
6477
|
*/
|
6478
|
function element_property($key) {
|
6479
|
return $key[0] == '#';
|
6480
|
}
|
6481
|
|
6482
|
/**
|
6483
|
* Gets properties of a structured array element (keys beginning with '#').
|
6484
|
*/
|
6485
|
function element_properties($element) {
|
6486
|
return array_filter(array_keys((array) $element), 'element_property');
|
6487
|
}
|
6488
|
|
6489
|
/**
|
6490
|
* Checks if the key is a child.
|
6491
|
*/
|
6492
|
function element_child($key) {
|
6493
|
return !isset($key[0]) || $key[0] != '#';
|
6494
|
}
|
6495
|
|
6496
|
/**
|
6497
|
* Identifies the children of an element array, optionally sorted by weight.
|
6498
|
*
|
6499
|
* The children of a element array are those key/value pairs whose key does
|
6500
|
* not start with a '#'. See drupal_render() for details.
|
6501
|
*
|
6502
|
* @param $elements
|
6503
|
* The element array whose children are to be identified.
|
6504
|
* @param $sort
|
6505
|
* Boolean to indicate whether the children should be sorted by weight.
|
6506
|
*
|
6507
|
* @return
|
6508
|
* The array keys of the element's children.
|
6509
|
*/
|
6510
|
function element_children(&$elements, $sort = FALSE) {
|
6511
|
// Do not attempt to sort elements which have already been sorted.
|
6512
|
$sort = isset($elements['#sorted']) ? !$elements['#sorted'] : $sort;
|
6513
|
|
6514
|
// Filter out properties from the element, leaving only children.
|
6515
|
$children = array();
|
6516
|
$sortable = FALSE;
|
6517
|
foreach ($elements as $key => $value) {
|
6518
|
if ($key === '' || $key[0] !== '#') {
|
6519
|
$children[$key] = $value;
|
6520
|
if (is_array($value) && isset($value['#weight'])) {
|
6521
|
$sortable = TRUE;
|
6522
|
}
|
6523
|
}
|
6524
|
}
|
6525
|
// Sort the children if necessary.
|
6526
|
if ($sort && $sortable) {
|
6527
|
uasort($children, 'element_sort');
|
6528
|
// Put the sorted children back into $elements in the correct order, to
|
6529
|
// preserve sorting if the same element is passed through
|
6530
|
// element_children() twice.
|
6531
|
foreach ($children as $key => $child) {
|
6532
|
unset($elements[$key]);
|
6533
|
$elements[$key] = $child;
|
6534
|
}
|
6535
|
$elements['#sorted'] = TRUE;
|
6536
|
}
|
6537
|
|
6538
|
return array_keys($children);
|
6539
|
}
|
6540
|
|
6541
|
/**
|
6542
|
* Returns the visible children of an element.
|
6543
|
*
|
6544
|
* @param $elements
|
6545
|
* The parent element.
|
6546
|
*
|
6547
|
* @return
|
6548
|
* The array keys of the element's visible children.
|
6549
|
*/
|
6550
|
function element_get_visible_children(array $elements) {
|
6551
|
$visible_children = array();
|
6552
|
|
6553
|
foreach (element_children($elements) as $key) {
|
6554
|
$child = $elements[$key];
|
6555
|
|
6556
|
// Skip un-accessible children.
|
6557
|
if (isset($child['#access']) && !$child['#access']) {
|
6558
|
continue;
|
6559
|
}
|
6560
|
|
6561
|
// Skip value and hidden elements, since they are not rendered.
|
6562
|
if (isset($child['#type']) && in_array($child['#type'], array('value', 'hidden'))) {
|
6563
|
continue;
|
6564
|
}
|
6565
|
|
6566
|
$visible_children[$key] = $child;
|
6567
|
}
|
6568
|
|
6569
|
return array_keys($visible_children);
|
6570
|
}
|
6571
|
|
6572
|
/**
|
6573
|
* Sets HTML attributes based on element properties.
|
6574
|
*
|
6575
|
* @param $element
|
6576
|
* The renderable element to process.
|
6577
|
* @param $map
|
6578
|
* An associative array whose keys are element property names and whose values
|
6579
|
* are the HTML attribute names to set for corresponding the property; e.g.,
|
6580
|
* array('#propertyname' => 'attributename'). If both names are identical
|
6581
|
* except for the leading '#', then an attribute name value is sufficient and
|
6582
|
* no property name needs to be specified.
|
6583
|
*/
|
6584
|
function element_set_attributes(array &$element, array $map) {
|
6585
|
foreach ($map as $property => $attribute) {
|
6586
|
// If the key is numeric, the attribute name needs to be taken over.
|
6587
|
if (is_int($property)) {
|
6588
|
$property = '#' . $attribute;
|
6589
|
}
|
6590
|
// Do not overwrite already existing attributes.
|
6591
|
if (isset($element[$property]) && !isset($element['#attributes'][$attribute])) {
|
6592
|
$element['#attributes'][$attribute] = $element[$property];
|
6593
|
}
|
6594
|
}
|
6595
|
}
|
6596
|
|
6597
|
/**
|
6598
|
* Recursively computes the difference of arrays with additional index check.
|
6599
|
*
|
6600
|
* This is a version of array_diff_assoc() that supports multidimensional
|
6601
|
* arrays.
|
6602
|
*
|
6603
|
* @param array $array1
|
6604
|
* The array to compare from.
|
6605
|
* @param array $array2
|
6606
|
* The array to compare to.
|
6607
|
*
|
6608
|
* @return array
|
6609
|
* Returns an array containing all the values from array1 that are not present
|
6610
|
* in array2.
|
6611
|
*/
|
6612
|
function drupal_array_diff_assoc_recursive($array1, $array2) {
|
6613
|
$difference = array();
|
6614
|
|
6615
|
foreach ($array1 as $key => $value) {
|
6616
|
if (is_array($value)) {
|
6617
|
if (!array_key_exists($key, $array2) || !is_array($array2[$key])) {
|
6618
|
$difference[$key] = $value;
|
6619
|
}
|
6620
|
else {
|
6621
|
$new_diff = drupal_array_diff_assoc_recursive($value, $array2[$key]);
|
6622
|
if (!empty($new_diff)) {
|
6623
|
$difference[$key] = $new_diff;
|
6624
|
}
|
6625
|
}
|
6626
|
}
|
6627
|
elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
|
6628
|
$difference[$key] = $value;
|
6629
|
}
|
6630
|
}
|
6631
|
|
6632
|
return $difference;
|
6633
|
}
|
6634
|
|
6635
|
/**
|
6636
|
* Sets a value in a nested array with variable depth.
|
6637
|
*
|
6638
|
* This helper function should be used when the depth of the array element you
|
6639
|
* are changing may vary (that is, the number of parent keys is variable). It
|
6640
|
* is primarily used for form structures and renderable arrays.
|
6641
|
*
|
6642
|
* Example:
|
6643
|
* @code
|
6644
|
* // Assume you have a 'signature' element somewhere in a form. It might be:
|
6645
|
* $form['signature_settings']['signature'] = array(
|
6646
|
* '#type' => 'text_format',
|
6647
|
* '#title' => t('Signature'),
|
6648
|
* );
|
6649
|
* // Or, it might be further nested:
|
6650
|
* $form['signature_settings']['user']['signature'] = array(
|
6651
|
* '#type' => 'text_format',
|
6652
|
* '#title' => t('Signature'),
|
6653
|
* );
|
6654
|
* @endcode
|
6655
|
*
|
6656
|
* To deal with the situation, the code needs to figure out the route to the
|
6657
|
* element, given an array of parents that is either
|
6658
|
* @code array('signature_settings', 'signature') @endcode in the first case or
|
6659
|
* @code array('signature_settings', 'user', 'signature') @endcode in the second
|
6660
|
* case.
|
6661
|
*
|
6662
|
* Without this helper function the only way to set the signature element in one
|
6663
|
* line would be using eval(), which should be avoided:
|
6664
|
* @code
|
6665
|
* // Do not do this! Avoid eval().
|
6666
|
* eval('$form[\'' . implode("']['", $parents) . '\'] = $element;');
|
6667
|
* @endcode
|
6668
|
*
|
6669
|
* Instead, use this helper function:
|
6670
|
* @code
|
6671
|
* drupal_array_set_nested_value($form, $parents, $element);
|
6672
|
* @endcode
|
6673
|
*
|
6674
|
* However if the number of array parent keys is static, the value should always
|
6675
|
* be set directly rather than calling this function. For instance, for the
|
6676
|
* first example we could just do:
|
6677
|
* @code
|
6678
|
* $form['signature_settings']['signature'] = $element;
|
6679
|
* @endcode
|
6680
|
*
|
6681
|
* @param $array
|
6682
|
* A reference to the array to modify.
|
6683
|
* @param $parents
|
6684
|
* An array of parent keys, starting with the outermost key.
|
6685
|
* @param $value
|
6686
|
* The value to set.
|
6687
|
* @param $force
|
6688
|
* (Optional) If TRUE, the value is forced into the structure even if it
|
6689
|
* requires the deletion of an already existing non-array parent value. If
|
6690
|
* FALSE, PHP throws an error if trying to add into a value that is not an
|
6691
|
* array. Defaults to FALSE.
|
6692
|
*
|
6693
|
* @see drupal_array_get_nested_value()
|
6694
|
*/
|
6695
|
function drupal_array_set_nested_value(array &$array, array $parents, $value, $force = FALSE) {
|
6696
|
$ref = &$array;
|
6697
|
foreach ($parents as $parent) {
|
6698
|
// PHP auto-creates container arrays and NULL entries without error if $ref
|
6699
|
// is NULL, but throws an error if $ref is set, but not an array.
|
6700
|
if ($force && isset($ref) && !is_array($ref)) {
|
6701
|
$ref = array();
|
6702
|
}
|
6703
|
$ref = &$ref[$parent];
|
6704
|
}
|
6705
|
$ref = $value;
|
6706
|
}
|
6707
|
|
6708
|
/**
|
6709
|
* Retrieves a value from a nested array with variable depth.
|
6710
|
*
|
6711
|
* This helper function should be used when the depth of the array element being
|
6712
|
* retrieved may vary (that is, the number of parent keys is variable). It is
|
6713
|
* primarily used for form structures and renderable arrays.
|
6714
|
*
|
6715
|
* Without this helper function the only way to get a nested array value with
|
6716
|
* variable depth in one line would be using eval(), which should be avoided:
|
6717
|
* @code
|
6718
|
* // Do not do this! Avoid eval().
|
6719
|
* // May also throw a PHP notice, if the variable array keys do not exist.
|
6720
|
* eval('$value = $array[\'' . implode("']['", $parents) . "'];");
|
6721
|
* @endcode
|
6722
|
*
|
6723
|
* Instead, use this helper function:
|
6724
|
* @code
|
6725
|
* $value = drupal_array_get_nested_value($form, $parents);
|
6726
|
* @endcode
|
6727
|
*
|
6728
|
* A return value of NULL is ambiguous, and can mean either that the requested
|
6729
|
* key does not exist, or that the actual value is NULL. If it is required to
|
6730
|
* know whether the nested array key actually exists, pass a third argument that
|
6731
|
* is altered by reference:
|
6732
|
* @code
|
6733
|
* $key_exists = NULL;
|
6734
|
* $value = drupal_array_get_nested_value($form, $parents, $key_exists);
|
6735
|
* if ($key_exists) {
|
6736
|
* // ... do something with $value ...
|
6737
|
* }
|
6738
|
* @endcode
|
6739
|
*
|
6740
|
* However if the number of array parent keys is static, the value should always
|
6741
|
* be retrieved directly rather than calling this function. For instance:
|
6742
|
* @code
|
6743
|
* $value = $form['signature_settings']['signature'];
|
6744
|
* @endcode
|
6745
|
*
|
6746
|
* @param $array
|
6747
|
* The array from which to get the value.
|
6748
|
* @param $parents
|
6749
|
* An array of parent keys of the value, starting with the outermost key.
|
6750
|
* @param $key_exists
|
6751
|
* (optional) If given, an already defined variable that is altered by
|
6752
|
* reference.
|
6753
|
*
|
6754
|
* @return
|
6755
|
* The requested nested value. Possibly NULL if the value is NULL or not all
|
6756
|
* nested parent keys exist. $key_exists is altered by reference and is a
|
6757
|
* Boolean that indicates whether all nested parent keys exist (TRUE) or not
|
6758
|
* (FALSE). This allows to distinguish between the two possibilities when NULL
|
6759
|
* is returned.
|
6760
|
*
|
6761
|
* @see drupal_array_set_nested_value()
|
6762
|
*/
|
6763
|
function &drupal_array_get_nested_value(array &$array, array $parents, &$key_exists = NULL) {
|
6764
|
$ref = &$array;
|
6765
|
foreach ($parents as $parent) {
|
6766
|
if (is_array($ref) && array_key_exists($parent, $ref)) {
|
6767
|
$ref = &$ref[$parent];
|
6768
|
}
|
6769
|
else {
|
6770
|
$key_exists = FALSE;
|
6771
|
$null = NULL;
|
6772
|
return $null;
|
6773
|
}
|
6774
|
}
|
6775
|
$key_exists = TRUE;
|
6776
|
return $ref;
|
6777
|
}
|
6778
|
|
6779
|
/**
|
6780
|
* Determines whether a nested array contains the requested keys.
|
6781
|
*
|
6782
|
* This helper function should be used when the depth of the array element to be
|
6783
|
* checked may vary (that is, the number of parent keys is variable). See
|
6784
|
* drupal_array_set_nested_value() for details. It is primarily used for form
|
6785
|
* structures and renderable arrays.
|
6786
|
*
|
6787
|
* If it is required to also get the value of the checked nested key, use
|
6788
|
* drupal_array_get_nested_value() instead.
|
6789
|
*
|
6790
|
* If the number of array parent keys is static, this helper function is
|
6791
|
* unnecessary and the following code can be used instead:
|
6792
|
* @code
|
6793
|
* $value_exists = isset($form['signature_settings']['signature']);
|
6794
|
* $key_exists = array_key_exists('signature', $form['signature_settings']);
|
6795
|
* @endcode
|
6796
|
*
|
6797
|
* @param $array
|
6798
|
* The array with the value to check for.
|
6799
|
* @param $parents
|
6800
|
* An array of parent keys of the value, starting with the outermost key.
|
6801
|
*
|
6802
|
* @return
|
6803
|
* TRUE if all the parent keys exist, FALSE otherwise.
|
6804
|
*
|
6805
|
* @see drupal_array_get_nested_value()
|
6806
|
*/
|
6807
|
function drupal_array_nested_key_exists(array $array, array $parents) {
|
6808
|
// Although this function is similar to PHP's array_key_exists(), its
|
6809
|
// arguments should be consistent with drupal_array_get_nested_value().
|
6810
|
$key_exists = NULL;
|
6811
|
drupal_array_get_nested_value($array, $parents, $key_exists);
|
6812
|
return $key_exists;
|
6813
|
}
|
6814
|
|
6815
|
/**
|
6816
|
* Provides theme registration for themes across .inc files.
|
6817
|
*/
|
6818
|
function drupal_common_theme() {
|
6819
|
return array(
|
6820
|
// From theme.inc.
|
6821
|
'html' => array(
|
6822
|
'render element' => 'page',
|
6823
|
'template' => 'html',
|
6824
|
),
|
6825
|
'page' => array(
|
6826
|
'render element' => 'page',
|
6827
|
'template' => 'page',
|
6828
|
),
|
6829
|
'region' => array(
|
6830
|
'render element' => 'elements',
|
6831
|
'template' => 'region',
|
6832
|
),
|
6833
|
'status_messages' => array(
|
6834
|
'variables' => array('display' => NULL),
|
6835
|
),
|
6836
|
'link' => array(
|
6837
|
'variables' => array('text' => NULL, 'path' => NULL, 'options' => array()),
|
6838
|
),
|
6839
|
'links' => array(
|
6840
|
'variables' => array('links' => NULL, 'attributes' => array('class' => array('links')), 'heading' => array()),
|
6841
|
),
|
6842
|
'image' => array(
|
6843
|
// HTML 4 and XHTML 1.0 always require an alt attribute. The HTML 5 draft
|
6844
|
// allows the alt attribute to be omitted in some cases. Therefore,
|
6845
|
// default the alt attribute to an empty string, but allow code calling
|
6846
|
// theme('image') to pass explicit NULL for it to be omitted. Usually,
|
6847
|
// neither omission nor an empty string satisfies accessibility
|
6848
|
// requirements, so it is strongly encouraged for code calling
|
6849
|
// theme('image') to pass a meaningful value for the alt variable.
|
6850
|
// - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
|
6851
|
// - http://www.w3.org/TR/xhtml1/dtds.html
|
6852
|
// - http://dev.w3.org/html5/spec/Overview.html#alt
|
6853
|
// The title attribute is optional in all cases, so it is omitted by
|
6854
|
// default.
|
6855
|
'variables' => array('path' => NULL, 'width' => NULL, 'height' => NULL, 'alt' => '', 'title' => NULL, 'attributes' => array()),
|
6856
|
),
|
6857
|
'breadcrumb' => array(
|
6858
|
'variables' => array('breadcrumb' => NULL),
|
6859
|
),
|
6860
|
'help' => array(
|
6861
|
'variables' => array(),
|
6862
|
),
|
6863
|
'table' => array(
|
6864
|
'variables' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL, 'colgroups' => array(), 'sticky' => TRUE, 'empty' => ''),
|
6865
|
),
|
6866
|
'tablesort_indicator' => array(
|
6867
|
'variables' => array('style' => NULL),
|
6868
|
),
|
6869
|
'mark' => array(
|
6870
|
'variables' => array('type' => MARK_NEW),
|
6871
|
),
|
6872
|
'item_list' => array(
|
6873
|
'variables' => array('items' => array(), 'title' => NULL, 'type' => 'ul', 'attributes' => array()),
|
6874
|
),
|
6875
|
'more_help_link' => array(
|
6876
|
'variables' => array('url' => NULL),
|
6877
|
),
|
6878
|
'feed_icon' => array(
|
6879
|
'variables' => array('url' => NULL, 'title' => NULL),
|
6880
|
),
|
6881
|
'more_link' => array(
|
6882
|
'variables' => array('url' => NULL, 'title' => NULL)
|
6883
|
),
|
6884
|
'username' => array(
|
6885
|
'variables' => array('account' => NULL),
|
6886
|
),
|
6887
|
'progress_bar' => array(
|
6888
|
'variables' => array('percent' => NULL, 'message' => NULL),
|
6889
|
),
|
6890
|
'indentation' => array(
|
6891
|
'variables' => array('size' => 1),
|
6892
|
),
|
6893
|
'html_tag' => array(
|
6894
|
'render element' => 'element',
|
6895
|
),
|
6896
|
// From theme.maintenance.inc.
|
6897
|
'maintenance_page' => array(
|
6898
|
'variables' => array('content' => NULL, 'show_messages' => TRUE),
|
6899
|
'template' => 'maintenance-page',
|
6900
|
),
|
6901
|
'update_page' => array(
|
6902
|
'variables' => array('content' => NULL, 'show_messages' => TRUE),
|
6903
|
),
|
6904
|
'install_page' => array(
|
6905
|
'variables' => array('content' => NULL),
|
6906
|
),
|
6907
|
'task_list' => array(
|
6908
|
'variables' => array('items' => NULL, 'active' => NULL),
|
6909
|
),
|
6910
|
'authorize_message' => array(
|
6911
|
'variables' => array('message' => NULL, 'success' => TRUE),
|
6912
|
),
|
6913
|
'authorize_report' => array(
|
6914
|
'variables' => array('messages' => array()),
|
6915
|
),
|
6916
|
// From pager.inc.
|
6917
|
'pager' => array(
|
6918
|
'variables' => array('tags' => array(), 'element' => 0, 'parameters' => array(), 'quantity' => 9),
|
6919
|
),
|
6920
|
'pager_first' => array(
|
6921
|
'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
|
6922
|
),
|
6923
|
'pager_previous' => array(
|
6924
|
'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
|
6925
|
),
|
6926
|
'pager_next' => array(
|
6927
|
'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
|
6928
|
),
|
6929
|
'pager_last' => array(
|
6930
|
'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
|
6931
|
),
|
6932
|
'pager_link' => array(
|
6933
|
'variables' => array('text' => NULL, 'page_new' => NULL, 'element' => NULL, 'parameters' => array(), 'attributes' => array()),
|
6934
|
),
|
6935
|
// From menu.inc.
|
6936
|
'menu_link' => array(
|
6937
|
'render element' => 'element',
|
6938
|
),
|
6939
|
'menu_tree' => array(
|
6940
|
'render element' => 'tree',
|
6941
|
),
|
6942
|
'menu_local_task' => array(
|
6943
|
'render element' => 'element',
|
6944
|
),
|
6945
|
'menu_local_action' => array(
|
6946
|
'render element' => 'element',
|
6947
|
),
|
6948
|
'menu_local_tasks' => array(
|
6949
|
'variables' => array('primary' => array(), 'secondary' => array()),
|
6950
|
),
|
6951
|
// From form.inc.
|
6952
|
'select' => array(
|
6953
|
'render element' => 'element',
|
6954
|
),
|
6955
|
'fieldset' => array(
|
6956
|
'render element' => 'element',
|
6957
|
),
|
6958
|
'radio' => array(
|
6959
|
'render element' => 'element',
|
6960
|
),
|
6961
|
'radios' => array(
|
6962
|
'render element' => 'element',
|
6963
|
),
|
6964
|
'date' => array(
|
6965
|
'render element' => 'element',
|
6966
|
),
|
6967
|
'exposed_filters' => array(
|
6968
|
'render element' => 'form',
|
6969
|
),
|
6970
|
'checkbox' => array(
|
6971
|
'render element' => 'element',
|
6972
|
),
|
6973
|
'checkboxes' => array(
|
6974
|
'render element' => 'element',
|
6975
|
),
|
6976
|
'button' => array(
|
6977
|
'render element' => 'element',
|
6978
|
),
|
6979
|
'image_button' => array(
|
6980
|
'render element' => 'element',
|
6981
|
),
|
6982
|
'hidden' => array(
|
6983
|
'render element' => 'element',
|
6984
|
),
|
6985
|
'textfield' => array(
|
6986
|
'render element' => 'element',
|
6987
|
),
|
6988
|
'form' => array(
|
6989
|
'render element' => 'element',
|
6990
|
),
|
6991
|
'textarea' => array(
|
6992
|
'render element' => 'element',
|
6993
|
),
|
6994
|
'password' => array(
|
6995
|
'render element' => 'element',
|
6996
|
),
|
6997
|
'file' => array(
|
6998
|
'render element' => 'element',
|
6999
|
),
|
7000
|
'tableselect' => array(
|
7001
|
'render element' => 'element',
|
7002
|
),
|
7003
|
'form_element' => array(
|
7004
|
'render element' => 'element',
|
7005
|
),
|
7006
|
'form_required_marker' => array(
|
7007
|
'render element' => 'element',
|
7008
|
),
|
7009
|
'form_element_label' => array(
|
7010
|
'render element' => 'element',
|
7011
|
),
|
7012
|
'vertical_tabs' => array(
|
7013
|
'render element' => 'element',
|
7014
|
),
|
7015
|
'container' => array(
|
7016
|
'render element' => 'element',
|
7017
|
),
|
7018
|
);
|
7019
|
}
|
7020
|
|
7021
|
/**
|
7022
|
* @addtogroup schemaapi
|
7023
|
* @{
|
7024
|
*/
|
7025
|
|
7026
|
/**
|
7027
|
* Creates all tables defined in a module's hook_schema().
|
7028
|
*
|
7029
|
* Note: This function does not pass the module's schema through
|
7030
|
* hook_schema_alter(). The module's tables will be created exactly as the
|
7031
|
* module defines them.
|
7032
|
*
|
7033
|
* @param $module
|
7034
|
* The module for which the tables will be created.
|
7035
|
*/
|
7036
|
function drupal_install_schema($module) {
|
7037
|
$schema = drupal_get_schema_unprocessed($module);
|
7038
|
_drupal_schema_initialize($schema, $module, FALSE);
|
7039
|
|
7040
|
foreach ($schema as $name => $table) {
|
7041
|
db_create_table($name, $table);
|
7042
|
}
|
7043
|
}
|
7044
|
|
7045
|
/**
|
7046
|
* Removes all tables defined in a module's hook_schema().
|
7047
|
*
|
7048
|
* Note: This function does not pass the module's schema through
|
7049
|
* hook_schema_alter(). The module's tables will be created exactly as the
|
7050
|
* module defines them.
|
7051
|
*
|
7052
|
* @param $module
|
7053
|
* The module for which the tables will be removed.
|
7054
|
*
|
7055
|
* @return
|
7056
|
* An array of arrays with the following key/value pairs:
|
7057
|
* - success: a boolean indicating whether the query succeeded.
|
7058
|
* - query: the SQL query(s) executed, passed through check_plain().
|
7059
|
*/
|
7060
|
function drupal_uninstall_schema($module) {
|
7061
|
$schema = drupal_get_schema_unprocessed($module);
|
7062
|
_drupal_schema_initialize($schema, $module, FALSE);
|
7063
|
|
7064
|
foreach ($schema as $table) {
|
7065
|
if (db_table_exists($table['name'])) {
|
7066
|
db_drop_table($table['name']);
|
7067
|
}
|
7068
|
}
|
7069
|
}
|
7070
|
|
7071
|
/**
|
7072
|
* Returns the unprocessed and unaltered version of a module's schema.
|
7073
|
*
|
7074
|
* Use this function only if you explicitly need the original
|
7075
|
* specification of a schema, as it was defined in a module's
|
7076
|
* hook_schema(). No additional default values will be set,
|
7077
|
* hook_schema_alter() is not invoked and these unprocessed
|
7078
|
* definitions won't be cached.
|
7079
|
*
|
7080
|
* This function can be used to retrieve a schema specification in
|
7081
|
* hook_schema(), so it allows you to derive your tables from existing
|
7082
|
* specifications.
|
7083
|
*
|
7084
|
* It is also used by drupal_install_schema() and
|
7085
|
* drupal_uninstall_schema() to ensure that a module's tables are
|
7086
|
* created exactly as specified without any changes introduced by a
|
7087
|
* module that implements hook_schema_alter().
|
7088
|
*
|
7089
|
* @param $module
|
7090
|
* The module to which the table belongs.
|
7091
|
* @param $table
|
7092
|
* The name of the table. If not given, the module's complete schema
|
7093
|
* is returned.
|
7094
|
*/
|
7095
|
function drupal_get_schema_unprocessed($module, $table = NULL) {
|
7096
|
// Load the .install file to get hook_schema.
|
7097
|
module_load_install($module);
|
7098
|
$schema = module_invoke($module, 'schema');
|
7099
|
|
7100
|
if (isset($table) && isset($schema[$table])) {
|
7101
|
return $schema[$table];
|
7102
|
}
|
7103
|
elseif (!empty($schema)) {
|
7104
|
return $schema;
|
7105
|
}
|
7106
|
return array();
|
7107
|
}
|
7108
|
|
7109
|
/**
|
7110
|
* Fills in required default values for table definitions from hook_schema().
|
7111
|
*
|
7112
|
* @param $schema
|
7113
|
* The schema definition array as it was returned by the module's
|
7114
|
* hook_schema().
|
7115
|
* @param $module
|
7116
|
* The module for which hook_schema() was invoked.
|
7117
|
* @param $remove_descriptions
|
7118
|
* (optional) Whether to additionally remove 'description' keys of all tables
|
7119
|
* and fields to improve performance of serialize() and unserialize().
|
7120
|
* Defaults to TRUE.
|
7121
|
*/
|
7122
|
function _drupal_schema_initialize(&$schema, $module, $remove_descriptions = TRUE) {
|
7123
|
// Set the name and module key for all tables.
|
7124
|
foreach ($schema as $name => &$table) {
|
7125
|
if (empty($table['module'])) {
|
7126
|
$table['module'] = $module;
|
7127
|
}
|
7128
|
if (!isset($table['name'])) {
|
7129
|
$table['name'] = $name;
|
7130
|
}
|
7131
|
if ($remove_descriptions) {
|
7132
|
unset($table['description']);
|
7133
|
foreach ($table['fields'] as &$field) {
|
7134
|
unset($field['description']);
|
7135
|
}
|
7136
|
}
|
7137
|
}
|
7138
|
}
|
7139
|
|
7140
|
/**
|
7141
|
* Retrieves a list of fields from a table schema.
|
7142
|
*
|
7143
|
* The returned list is suitable for use in an SQL query.
|
7144
|
*
|
7145
|
* @param $table
|
7146
|
* The name of the table from which to retrieve fields.
|
7147
|
* @param
|
7148
|
* An optional prefix to to all fields.
|
7149
|
*
|
7150
|
* @return An array of fields.
|
7151
|
*/
|
7152
|
function drupal_schema_fields_sql($table, $prefix = NULL) {
|
7153
|
$schema = drupal_get_schema($table);
|
7154
|
$fields = array_keys($schema['fields']);
|
7155
|
if ($prefix) {
|
7156
|
$columns = array();
|
7157
|
foreach ($fields as $field) {
|
7158
|
$columns[] = "$prefix.$field";
|
7159
|
}
|
7160
|
return $columns;
|
7161
|
}
|
7162
|
else {
|
7163
|
return $fields;
|
7164
|
}
|
7165
|
}
|
7166
|
|
7167
|
/**
|
7168
|
* Saves (inserts or updates) a record to the database based upon the schema.
|
7169
|
*
|
7170
|
* Do not use drupal_write_record() within hook_update_N() functions, since the
|
7171
|
* database schema cannot be relied upon when a user is running a series of
|
7172
|
* updates. Instead, use db_insert() or db_update() to save the record.
|
7173
|
*
|
7174
|
* @param $table
|
7175
|
* The name of the table; this must be defined by a hook_schema()
|
7176
|
* implementation.
|
7177
|
* @param $record
|
7178
|
* An object or array representing the record to write, passed in by
|
7179
|
* reference. If inserting a new record, values not provided in $record will
|
7180
|
* be populated in $record and in the database with the default values from
|
7181
|
* the schema, as well as a single serial (auto-increment) field (if present).
|
7182
|
* If updating an existing record, only provided values are updated in the
|
7183
|
* database, and $record is not modified.
|
7184
|
* @param $primary_keys
|
7185
|
* To indicate that this is a new record to be inserted, omit this argument.
|
7186
|
* If this is an update, this argument specifies the primary keys' field
|
7187
|
* names. If there is only 1 field in the key, you may pass in a string; if
|
7188
|
* there are multiple fields in the key, pass in an array.
|
7189
|
*
|
7190
|
* @return
|
7191
|
* If the record insert or update failed, returns FALSE. If it succeeded,
|
7192
|
* returns SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
|
7193
|
*/
|
7194
|
function drupal_write_record($table, &$record, $primary_keys = array()) {
|
7195
|
// Standardize $primary_keys to an array.
|
7196
|
if (is_string($primary_keys)) {
|
7197
|
$primary_keys = array($primary_keys);
|
7198
|
}
|
7199
|
|
7200
|
$schema = drupal_get_schema($table);
|
7201
|
if (empty($schema)) {
|
7202
|
return FALSE;
|
7203
|
}
|
7204
|
|
7205
|
$object = (object) $record;
|
7206
|
$fields = array();
|
7207
|
|
7208
|
// Go through the schema to determine fields to write.
|
7209
|
foreach ($schema['fields'] as $field => $info) {
|
7210
|
if ($info['type'] == 'serial') {
|
7211
|
// Skip serial types if we are updating.
|
7212
|
if (!empty($primary_keys)) {
|
7213
|
continue;
|
7214
|
}
|
7215
|
// Track serial field so we can helpfully populate them after the query.
|
7216
|
// NOTE: Each table should come with one serial field only.
|
7217
|
$serial = $field;
|
7218
|
}
|
7219
|
|
7220
|
// Skip field if it is in $primary_keys as it is unnecessary to update a
|
7221
|
// field to the value it is already set to.
|
7222
|
if (in_array($field, $primary_keys)) {
|
7223
|
continue;
|
7224
|
}
|
7225
|
|
7226
|
if (!property_exists($object, $field)) {
|
7227
|
// Skip fields that are not provided, default values are already known
|
7228
|
// by the database.
|
7229
|
continue;
|
7230
|
}
|
7231
|
|
7232
|
// Build array of fields to update or insert.
|
7233
|
if (empty($info['serialize'])) {
|
7234
|
$fields[$field] = $object->$field;
|
7235
|
}
|
7236
|
else {
|
7237
|
$fields[$field] = serialize($object->$field);
|
7238
|
}
|
7239
|
|
7240
|
// Type cast to proper datatype, except when the value is NULL and the
|
7241
|
// column allows this.
|
7242
|
//
|
7243
|
// MySQL PDO silently casts e.g. FALSE and '' to 0 when inserting the value
|
7244
|
// into an integer column, but PostgreSQL PDO does not. Also type cast NULL
|
7245
|
// when the column does not allow this.
|
7246
|
if (isset($object->$field) || !empty($info['not null'])) {
|
7247
|
if ($info['type'] == 'int' || $info['type'] == 'serial') {
|
7248
|
$fields[$field] = (int) $fields[$field];
|
7249
|
}
|
7250
|
elseif ($info['type'] == 'float') {
|
7251
|
$fields[$field] = (float) $fields[$field];
|
7252
|
}
|
7253
|
else {
|
7254
|
$fields[$field] = (string) $fields[$field];
|
7255
|
}
|
7256
|
}
|
7257
|
}
|
7258
|
|
7259
|
if (empty($fields)) {
|
7260
|
return;
|
7261
|
}
|
7262
|
|
7263
|
// Build the SQL.
|
7264
|
if (empty($primary_keys)) {
|
7265
|
// We are doing an insert.
|
7266
|
$options = array('return' => Database::RETURN_INSERT_ID);
|
7267
|
if (isset($serial) && isset($fields[$serial])) {
|
7268
|
// If the serial column has been explicitly set with an ID, then we don't
|
7269
|
// require the database to return the last insert id.
|
7270
|
if ($fields[$serial]) {
|
7271
|
$options['return'] = Database::RETURN_AFFECTED;
|
7272
|
}
|
7273
|
// If a serial column does exist with no value (i.e. 0) then remove it as
|
7274
|
// the database will insert the correct value for us.
|
7275
|
else {
|
7276
|
unset($fields[$serial]);
|
7277
|
}
|
7278
|
}
|
7279
|
$query = db_insert($table, $options)->fields($fields);
|
7280
|
$return = SAVED_NEW;
|
7281
|
}
|
7282
|
else {
|
7283
|
$query = db_update($table)->fields($fields);
|
7284
|
foreach ($primary_keys as $key) {
|
7285
|
$query->condition($key, $object->$key);
|
7286
|
}
|
7287
|
$return = SAVED_UPDATED;
|
7288
|
}
|
7289
|
|
7290
|
// Execute the SQL.
|
7291
|
if ($query_return = $query->execute()) {
|
7292
|
if (isset($serial)) {
|
7293
|
// If the database was not told to return the last insert id, it will be
|
7294
|
// because we already know it.
|
7295
|
if (isset($options) && $options['return'] != Database::RETURN_INSERT_ID) {
|
7296
|
$object->$serial = $fields[$serial];
|
7297
|
}
|
7298
|
else {
|
7299
|
$object->$serial = $query_return;
|
7300
|
}
|
7301
|
}
|
7302
|
}
|
7303
|
// If we have a single-field primary key but got no insert ID, the
|
7304
|
// query failed. Note that we explicitly check for FALSE, because
|
7305
|
// a valid update query which doesn't change any values will return
|
7306
|
// zero (0) affected rows.
|
7307
|
elseif ($query_return === FALSE && count($primary_keys) == 1) {
|
7308
|
$return = FALSE;
|
7309
|
}
|
7310
|
|
7311
|
// If we are inserting, populate empty fields with default values.
|
7312
|
if (empty($primary_keys)) {
|
7313
|
foreach ($schema['fields'] as $field => $info) {
|
7314
|
if (isset($info['default']) && !property_exists($object, $field)) {
|
7315
|
$object->$field = $info['default'];
|
7316
|
}
|
7317
|
}
|
7318
|
}
|
7319
|
|
7320
|
// If we began with an array, convert back.
|
7321
|
if (is_array($record)) {
|
7322
|
$record = (array) $object;
|
7323
|
}
|
7324
|
|
7325
|
return $return;
|
7326
|
}
|
7327
|
|
7328
|
/**
|
7329
|
* @} End of "addtogroup schemaapi".
|
7330
|
*/
|
7331
|
|
7332
|
/**
|
7333
|
* Parses Drupal module and theme .info files.
|
7334
|
*
|
7335
|
* Info files are NOT for placing arbitrary theme and module-specific settings.
|
7336
|
* Use variable_get() and variable_set() for that.
|
7337
|
*
|
7338
|
* Information stored in a module .info file:
|
7339
|
* - name: The real name of the module for display purposes.
|
7340
|
* - description: A brief description of the module.
|
7341
|
* - dependencies: An array of shortnames of other modules this module requires.
|
7342
|
* - package: The name of the package of modules this module belongs to.
|
7343
|
*
|
7344
|
* See forum.info for an example of a module .info file.
|
7345
|
*
|
7346
|
* Information stored in a theme .info file:
|
7347
|
* - name: The real name of the theme for display purposes.
|
7348
|
* - description: Brief description.
|
7349
|
* - screenshot: Path to screenshot relative to the theme's .info file.
|
7350
|
* - engine: Theme engine; typically phptemplate.
|
7351
|
* - base: Name of a base theme, if applicable; e.g., base = zen.
|
7352
|
* - regions: Listed regions; e.g., region[left] = Left sidebar.
|
7353
|
* - features: Features available; e.g., features[] = logo.
|
7354
|
* - stylesheets: Theme stylesheets; e.g., stylesheets[all][] = my-style.css.
|
7355
|
* - scripts: Theme scripts; e.g., scripts[] = my-script.js.
|
7356
|
*
|
7357
|
* See bartik.info for an example of a theme .info file.
|
7358
|
*
|
7359
|
* @param $filename
|
7360
|
* The file we are parsing. Accepts file with relative or absolute path.
|
7361
|
*
|
7362
|
* @return
|
7363
|
* The info array.
|
7364
|
*
|
7365
|
* @see drupal_parse_info_format()
|
7366
|
*/
|
7367
|
function drupal_parse_info_file($filename) {
|
7368
|
$info = &drupal_static(__FUNCTION__, array());
|
7369
|
|
7370
|
if (!isset($info[$filename])) {
|
7371
|
if (!file_exists($filename)) {
|
7372
|
$info[$filename] = array();
|
7373
|
}
|
7374
|
else {
|
7375
|
$data = file_get_contents($filename);
|
7376
|
$info[$filename] = drupal_parse_info_format($data);
|
7377
|
}
|
7378
|
}
|
7379
|
return $info[$filename];
|
7380
|
}
|
7381
|
|
7382
|
/**
|
7383
|
* Parses data in Drupal's .info format.
|
7384
|
*
|
7385
|
* Data should be in an .ini-like format to specify values. White-space
|
7386
|
* generally doesn't matter, except inside values:
|
7387
|
* @code
|
7388
|
* key = value
|
7389
|
* key = "value"
|
7390
|
* key = 'value'
|
7391
|
* key = "multi-line
|
7392
|
* value"
|
7393
|
* key = 'multi-line
|
7394
|
* value'
|
7395
|
* key
|
7396
|
* =
|
7397
|
* 'value'
|
7398
|
* @endcode
|
7399
|
*
|
7400
|
* Arrays are created using a HTTP GET alike syntax:
|
7401
|
* @code
|
7402
|
* key[] = "numeric array"
|
7403
|
* key[index] = "associative array"
|
7404
|
* key[index][] = "nested numeric array"
|
7405
|
* key[index][index] = "nested associative array"
|
7406
|
* @endcode
|
7407
|
*
|
7408
|
* PHP constants are substituted in, but only when used as the entire value.
|
7409
|
* Comments should start with a semi-colon at the beginning of a line.
|
7410
|
*
|
7411
|
* @param $data
|
7412
|
* A string to parse.
|
7413
|
*
|
7414
|
* @return
|
7415
|
* The info array.
|
7416
|
*
|
7417
|
* @see drupal_parse_info_file()
|
7418
|
*/
|
7419
|
function drupal_parse_info_format($data) {
|
7420
|
$info = array();
|
7421
|
$constants = get_defined_constants();
|
7422
|
|
7423
|
if (preg_match_all('
|
7424
|
@^\s* # Start at the beginning of a line, ignoring leading whitespace
|
7425
|
((?:
|
7426
|
[^=;\[\]]| # Key names cannot contain equal signs, semi-colons or square brackets,
|
7427
|
\[[^\[\]]*\] # unless they are balanced and not nested
|
7428
|
)+?)
|
7429
|
\s*=\s* # Key/value pairs are separated by equal signs (ignoring white-space)
|
7430
|
(?:
|
7431
|
("(?:[^"]|(?<=\\\\)")*")| # Double-quoted string, which may contain slash-escaped quotes/slashes
|
7432
|
(\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
|
7433
|
([^\r\n]*?) # Non-quoted string
|
7434
|
)\s*$ # Stop at the next end of a line, ignoring trailing whitespace
|
7435
|
@msx', $data, $matches, PREG_SET_ORDER)) {
|
7436
|
foreach ($matches as $match) {
|
7437
|
// Fetch the key and value string.
|
7438
|
$i = 0;
|
7439
|
foreach (array('key', 'value1', 'value2', 'value3') as $var) {
|
7440
|
$$var = isset($match[++$i]) ? $match[$i] : '';
|
7441
|
}
|
7442
|
$value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
|
7443
|
|
7444
|
// Parse array syntax.
|
7445
|
$keys = preg_split('/\]?\[/', rtrim($key, ']'));
|
7446
|
$last = array_pop($keys);
|
7447
|
$parent = &$info;
|
7448
|
|
7449
|
// Create nested arrays.
|
7450
|
foreach ($keys as $key) {
|
7451
|
if ($key == '') {
|
7452
|
$key = count($parent);
|
7453
|
}
|
7454
|
if (!isset($parent[$key]) || !is_array($parent[$key])) {
|
7455
|
$parent[$key] = array();
|
7456
|
}
|
7457
|
$parent = &$parent[$key];
|
7458
|
}
|
7459
|
|
7460
|
// Handle PHP constants.
|
7461
|
if (isset($constants[$value])) {
|
7462
|
$value = $constants[$value];
|
7463
|
}
|
7464
|
|
7465
|
// Insert actual value.
|
7466
|
if ($last == '') {
|
7467
|
$last = count($parent);
|
7468
|
}
|
7469
|
$parent[$last] = $value;
|
7470
|
}
|
7471
|
}
|
7472
|
|
7473
|
return $info;
|
7474
|
}
|
7475
|
|
7476
|
/**
|
7477
|
* Returns a list of severity levels, as defined in RFC 3164.
|
7478
|
*
|
7479
|
* @return
|
7480
|
* Array of the possible severity levels for log messages.
|
7481
|
*
|
7482
|
* @see http://www.ietf.org/rfc/rfc3164.txt
|
7483
|
* @see watchdog()
|
7484
|
* @ingroup logging_severity_levels
|
7485
|
*/
|
7486
|
function watchdog_severity_levels() {
|
7487
|
return array(
|
7488
|
WATCHDOG_EMERGENCY => t('emergency'),
|
7489
|
WATCHDOG_ALERT => t('alert'),
|
7490
|
WATCHDOG_CRITICAL => t('critical'),
|
7491
|
WATCHDOG_ERROR => t('error'),
|
7492
|
WATCHDOG_WARNING => t('warning'),
|
7493
|
WATCHDOG_NOTICE => t('notice'),
|
7494
|
WATCHDOG_INFO => t('info'),
|
7495
|
WATCHDOG_DEBUG => t('debug'),
|
7496
|
);
|
7497
|
}
|
7498
|
|
7499
|
|
7500
|
/**
|
7501
|
* Explodes a string of tags into an array.
|
7502
|
*
|
7503
|
* @see drupal_implode_tags()
|
7504
|
*/
|
7505
|
function drupal_explode_tags($tags) {
|
7506
|
// This regexp allows the following types of user input:
|
7507
|
// this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
|
7508
|
$regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
|
7509
|
preg_match_all($regexp, $tags, $matches);
|
7510
|
$typed_tags = array_unique($matches[1]);
|
7511
|
|
7512
|
$tags = array();
|
7513
|
foreach ($typed_tags as $tag) {
|
7514
|
// If a user has escaped a term (to demonstrate that it is a group,
|
7515
|
// or includes a comma or quote character), we remove the escape
|
7516
|
// formatting so to save the term into the database as the user intends.
|
7517
|
$tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
|
7518
|
if ($tag != "") {
|
7519
|
$tags[] = $tag;
|
7520
|
}
|
7521
|
}
|
7522
|
|
7523
|
return $tags;
|
7524
|
}
|
7525
|
|
7526
|
/**
|
7527
|
* Implodes an array of tags into a string.
|
7528
|
*
|
7529
|
* @see drupal_explode_tags()
|
7530
|
*/
|
7531
|
function drupal_implode_tags($tags) {
|
7532
|
$encoded_tags = array();
|
7533
|
foreach ($tags as $tag) {
|
7534
|
// Commas and quotes in tag names are special cases, so encode them.
|
7535
|
if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
|
7536
|
$tag = '"' . str_replace('"', '""', $tag) . '"';
|
7537
|
}
|
7538
|
|
7539
|
$encoded_tags[] = $tag;
|
7540
|
}
|
7541
|
return implode(', ', $encoded_tags);
|
7542
|
}
|
7543
|
|
7544
|
/**
|
7545
|
* Flushes all cached data on the site.
|
7546
|
*
|
7547
|
* Empties cache tables, rebuilds the menu cache and theme registries, and
|
7548
|
* invokes a hook so that other modules' cache data can be cleared as well.
|
7549
|
*/
|
7550
|
function drupal_flush_all_caches() {
|
7551
|
// Change query-strings on css/js files to enforce reload for all users.
|
7552
|
_drupal_flush_css_js();
|
7553
|
|
7554
|
registry_rebuild();
|
7555
|
drupal_clear_css_cache();
|
7556
|
drupal_clear_js_cache();
|
7557
|
|
7558
|
// Rebuild the theme data. Note that the module data is rebuilt above, as
|
7559
|
// part of registry_rebuild().
|
7560
|
system_rebuild_theme_data();
|
7561
|
drupal_theme_rebuild();
|
7562
|
|
7563
|
entity_info_cache_clear();
|
7564
|
node_types_rebuild();
|
7565
|
// node_menu() defines menu items based on node types so it needs to come
|
7566
|
// after node types are rebuilt.
|
7567
|
menu_rebuild();
|
7568
|
|
7569
|
// Synchronize to catch any actions that were added or removed.
|
7570
|
actions_synchronize();
|
7571
|
|
7572
|
// Don't clear cache_form - in-progress form submissions may break.
|
7573
|
// Ordered so clearing the page cache will always be the last action.
|
7574
|
$core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
|
7575
|
$cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
|
7576
|
foreach ($cache_tables as $table) {
|
7577
|
cache_clear_all('*', $table, TRUE);
|
7578
|
}
|
7579
|
|
7580
|
// Rebuild the bootstrap module list. We do this here so that developers
|
7581
|
// can get new hook_boot() implementations registered without having to
|
7582
|
// write a hook_update_N() function.
|
7583
|
_system_update_bootstrap_status();
|
7584
|
}
|
7585
|
|
7586
|
/**
|
7587
|
* Changes the dummy query string added to all CSS and JavaScript files.
|
7588
|
*
|
7589
|
* Changing the dummy query string appended to CSS and JavaScript files forces
|
7590
|
* all browsers to reload fresh files.
|
7591
|
*/
|
7592
|
function _drupal_flush_css_js() {
|
7593
|
// The timestamp is converted to base 36 in order to make it more compact.
|
7594
|
variable_set('css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
|
7595
|
}
|
7596
|
|
7597
|
/**
|
7598
|
* Outputs debug information.
|
7599
|
*
|
7600
|
* The debug information is passed on to trigger_error() after being converted
|
7601
|
* to a string using _drupal_debug_message().
|
7602
|
*
|
7603
|
* @param $data
|
7604
|
* Data to be output.
|
7605
|
* @param $label
|
7606
|
* Label to prefix the data.
|
7607
|
* @param $print_r
|
7608
|
* Flag to switch between print_r() and var_export() for data conversion to
|
7609
|
* string. Set $print_r to TRUE when dealing with a recursive data structure
|
7610
|
* as var_export() will generate an error.
|
7611
|
*/
|
7612
|
function debug($data, $label = NULL, $print_r = FALSE) {
|
7613
|
// Print $data contents to string.
|
7614
|
$string = check_plain($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
|
7615
|
|
7616
|
// Display values with pre-formatting to increase readability.
|
7617
|
$string = '<pre>' . $string . '</pre>';
|
7618
|
|
7619
|
trigger_error(trim($label ? "$label: $string" : $string));
|
7620
|
}
|
7621
|
|
7622
|
/**
|
7623
|
* Parses a dependency for comparison by drupal_check_incompatibility().
|
7624
|
*
|
7625
|
* @param $dependency
|
7626
|
* A dependency string, for example 'foo (>=7.x-4.5-beta5, 3.x)'.
|
7627
|
*
|
7628
|
* @return
|
7629
|
* An associative array with three keys:
|
7630
|
* - 'name' includes the name of the thing to depend on (e.g. 'foo').
|
7631
|
* - 'original_version' contains the original version string (which can be
|
7632
|
* used in the UI for reporting incompatibilities).
|
7633
|
* - 'versions' is a list of associative arrays, each containing the keys
|
7634
|
* 'op' and 'version'. 'op' can be one of: '=', '==', '!=', '<>', '<',
|
7635
|
* '<=', '>', or '>='. 'version' is one piece like '4.5-beta3'.
|
7636
|
* Callers should pass this structure to drupal_check_incompatibility().
|
7637
|
*
|
7638
|
* @see drupal_check_incompatibility()
|
7639
|
*/
|
7640
|
function drupal_parse_dependency($dependency) {
|
7641
|
// We use named subpatterns and support every op that version_compare
|
7642
|
// supports. Also, op is optional and defaults to equals.
|
7643
|
$p_op = '(?P<operation>!=|==|=|<|<=|>|>=|<>)?';
|
7644
|
// Core version is always optional: 7.x-2.x and 2.x is treated the same.
|
7645
|
$p_core = '(?:' . preg_quote(DRUPAL_CORE_COMPATIBILITY) . '-)?';
|
7646
|
$p_major = '(?P<major>\d+)';
|
7647
|
// By setting the minor version to x, branches can be matched.
|
7648
|
$p_minor = '(?P<minor>(?:\d+|x)(?:-[A-Za-z]+\d+)?)';
|
7649
|
$value = array();
|
7650
|
$parts = explode('(', $dependency, 2);
|
7651
|
$value['name'] = trim($parts[0]);
|
7652
|
if (isset($parts[1])) {
|
7653
|
$value['original_version'] = ' (' . $parts[1];
|
7654
|
foreach (explode(',', $parts[1]) as $version) {
|
7655
|
if (preg_match("/^\s*$p_op\s*$p_core$p_major\.$p_minor/", $version, $matches)) {
|
7656
|
$op = !empty($matches['operation']) ? $matches['operation'] : '=';
|
7657
|
if ($matches['minor'] == 'x') {
|
7658
|
// Drupal considers "2.x" to mean any version that begins with
|
7659
|
// "2" (e.g. 2.0, 2.9 are all "2.x"). PHP's version_compare(),
|
7660
|
// on the other hand, treats "x" as a string; so to
|
7661
|
// version_compare(), "2.x" is considered less than 2.0. This
|
7662
|
// means that >=2.x and <2.x are handled by version_compare()
|
7663
|
// as we need, but > and <= are not.
|
7664
|
if ($op == '>' || $op == '<=') {
|
7665
|
$matches['major']++;
|
7666
|
}
|
7667
|
// Equivalence can be checked by adding two restrictions.
|
7668
|
if ($op == '=' || $op == '==') {
|
7669
|
$value['versions'][] = array('op' => '<', 'version' => ($matches['major'] + 1) . '.x');
|
7670
|
$op = '>=';
|
7671
|
}
|
7672
|
}
|
7673
|
$value['versions'][] = array('op' => $op, 'version' => $matches['major'] . '.' . $matches['minor']);
|
7674
|
}
|
7675
|
}
|
7676
|
}
|
7677
|
return $value;
|
7678
|
}
|
7679
|
|
7680
|
/**
|
7681
|
* Checks whether a version is compatible with a given dependency.
|
7682
|
*
|
7683
|
* @param $v
|
7684
|
* The parsed dependency structure from drupal_parse_dependency().
|
7685
|
* @param $current_version
|
7686
|
* The version to check against (like 4.2).
|
7687
|
*
|
7688
|
* @return
|
7689
|
* NULL if compatible, otherwise the original dependency version string that
|
7690
|
* caused the incompatibility.
|
7691
|
*
|
7692
|
* @see drupal_parse_dependency()
|
7693
|
*/
|
7694
|
function drupal_check_incompatibility($v, $current_version) {
|
7695
|
if (!empty($v['versions'])) {
|
7696
|
foreach ($v['versions'] as $required_version) {
|
7697
|
if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
|
7698
|
return $v['original_version'];
|
7699
|
}
|
7700
|
}
|
7701
|
}
|
7702
|
}
|
7703
|
|
7704
|
/**
|
7705
|
* Get the entity info array of an entity type.
|
7706
|
*
|
7707
|
* @param $entity_type
|
7708
|
* The entity type, e.g. node, for which the info shall be returned, or NULL
|
7709
|
* to return an array with info about all types.
|
7710
|
*
|
7711
|
* @see hook_entity_info()
|
7712
|
* @see hook_entity_info_alter()
|
7713
|
*/
|
7714
|
function entity_get_info($entity_type = NULL) {
|
7715
|
global $language;
|
7716
|
|
7717
|
// Use the advanced drupal_static() pattern, since this is called very often.
|
7718
|
static $drupal_static_fast;
|
7719
|
if (!isset($drupal_static_fast)) {
|
7720
|
$drupal_static_fast['entity_info'] = &drupal_static(__FUNCTION__);
|
7721
|
}
|
7722
|
$entity_info = &$drupal_static_fast['entity_info'];
|
7723
|
|
7724
|
// hook_entity_info() includes translated strings, so each language is cached
|
7725
|
// separately.
|
7726
|
$langcode = $language->language;
|
7727
|
|
7728
|
if (empty($entity_info)) {
|
7729
|
if ($cache = cache_get("entity_info:$langcode")) {
|
7730
|
$entity_info = $cache->data;
|
7731
|
}
|
7732
|
else {
|
7733
|
$entity_info = module_invoke_all('entity_info');
|
7734
|
// Merge in default values.
|
7735
|
foreach ($entity_info as $name => $data) {
|
7736
|
$entity_info[$name] += array(
|
7737
|
'fieldable' => FALSE,
|
7738
|
'controller class' => 'DrupalDefaultEntityController',
|
7739
|
'static cache' => TRUE,
|
7740
|
'field cache' => TRUE,
|
7741
|
'load hook' => $name . '_load',
|
7742
|
'bundles' => array(),
|
7743
|
'view modes' => array(),
|
7744
|
'entity keys' => array(),
|
7745
|
'translation' => array(),
|
7746
|
);
|
7747
|
$entity_info[$name]['entity keys'] += array(
|
7748
|
'revision' => '',
|
7749
|
'bundle' => '',
|
7750
|
);
|
7751
|
foreach ($entity_info[$name]['view modes'] as $view_mode => $view_mode_info) {
|
7752
|
$entity_info[$name]['view modes'][$view_mode] += array(
|
7753
|
'custom settings' => FALSE,
|
7754
|
);
|
7755
|
}
|
7756
|
// If no bundle key is provided, assume a single bundle, named after
|
7757
|
// the entity type.
|
7758
|
if (empty($entity_info[$name]['entity keys']['bundle']) && empty($entity_info[$name]['bundles'])) {
|
7759
|
$entity_info[$name]['bundles'] = array($name => array('label' => $entity_info[$name]['label']));
|
7760
|
}
|
7761
|
// Prepare entity schema fields SQL info for
|
7762
|
// DrupalEntityControllerInterface::buildQuery().
|
7763
|
if (isset($entity_info[$name]['base table'])) {
|
7764
|
$entity_info[$name]['schema_fields_sql']['base table'] = drupal_schema_fields_sql($entity_info[$name]['base table']);
|
7765
|
if (isset($entity_info[$name]['revision table'])) {
|
7766
|
$entity_info[$name]['schema_fields_sql']['revision table'] = drupal_schema_fields_sql($entity_info[$name]['revision table']);
|
7767
|
}
|
7768
|
}
|
7769
|
}
|
7770
|
// Let other modules alter the entity info.
|
7771
|
drupal_alter('entity_info', $entity_info);
|
7772
|
cache_set("entity_info:$langcode", $entity_info);
|
7773
|
}
|
7774
|
}
|
7775
|
|
7776
|
if (empty($entity_type)) {
|
7777
|
return $entity_info;
|
7778
|
}
|
7779
|
elseif (isset($entity_info[$entity_type])) {
|
7780
|
return $entity_info[$entity_type];
|
7781
|
}
|
7782
|
}
|
7783
|
|
7784
|
/**
|
7785
|
* Resets the cached information about entity types.
|
7786
|
*/
|
7787
|
function entity_info_cache_clear() {
|
7788
|
drupal_static_reset('entity_get_info');
|
7789
|
// Clear all languages.
|
7790
|
cache_clear_all('entity_info:', 'cache', TRUE);
|
7791
|
}
|
7792
|
|
7793
|
/**
|
7794
|
* Helper function to extract id, vid, and bundle name from an entity.
|
7795
|
*
|
7796
|
* @param $entity_type
|
7797
|
* The entity type; e.g. 'node' or 'user'.
|
7798
|
* @param $entity
|
7799
|
* The entity from which to extract values.
|
7800
|
*
|
7801
|
* @return
|
7802
|
* A numerically indexed array (not a hash table) containing these
|
7803
|
* elements:
|
7804
|
* - 0: Primary ID of the entity.
|
7805
|
* - 1: Revision ID of the entity, or NULL if $entity_type is not versioned.
|
7806
|
* - 2: Bundle name of the entity, or NULL if $entity_type has no bundles.
|
7807
|
*/
|
7808
|
function entity_extract_ids($entity_type, $entity) {
|
7809
|
$info = entity_get_info($entity_type);
|
7810
|
|
7811
|
// Objects being created might not have id/vid yet.
|
7812
|
$id = isset($entity->{$info['entity keys']['id']}) ? $entity->{$info['entity keys']['id']} : NULL;
|
7813
|
$vid = ($info['entity keys']['revision'] && isset($entity->{$info['entity keys']['revision']})) ? $entity->{$info['entity keys']['revision']} : NULL;
|
7814
|
|
7815
|
if (!empty($info['entity keys']['bundle'])) {
|
7816
|
// Explicitly fail for malformed entities missing the bundle property.
|
7817
|
if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
|
7818
|
throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
|
7819
|
}
|
7820
|
$bundle = $entity->{$info['entity keys']['bundle']};
|
7821
|
}
|
7822
|
else {
|
7823
|
// The entity type provides no bundle key: assume a single bundle, named
|
7824
|
// after the entity type.
|
7825
|
$bundle = $entity_type;
|
7826
|
}
|
7827
|
|
7828
|
return array($id, $vid, $bundle);
|
7829
|
}
|
7830
|
|
7831
|
/**
|
7832
|
* Helper function to assemble an object structure with initial ids.
|
7833
|
*
|
7834
|
* This function can be seen as reciprocal to entity_extract_ids().
|
7835
|
*
|
7836
|
* @param $entity_type
|
7837
|
* The entity type; e.g. 'node' or 'user'.
|
7838
|
* @param $ids
|
7839
|
* A numerically indexed array, as returned by entity_extract_ids().
|
7840
|
*
|
7841
|
* @return
|
7842
|
* An entity structure, initialized with the ids provided.
|
7843
|
*
|
7844
|
* @see entity_extract_ids()
|
7845
|
*/
|
7846
|
function entity_create_stub_entity($entity_type, $ids) {
|
7847
|
$entity = new stdClass();
|
7848
|
$info = entity_get_info($entity_type);
|
7849
|
$entity->{$info['entity keys']['id']} = $ids[0];
|
7850
|
if (!empty($info['entity keys']['revision']) && isset($ids[1])) {
|
7851
|
$entity->{$info['entity keys']['revision']} = $ids[1];
|
7852
|
}
|
7853
|
if (!empty($info['entity keys']['bundle']) && isset($ids[2])) {
|
7854
|
$entity->{$info['entity keys']['bundle']} = $ids[2];
|
7855
|
}
|
7856
|
return $entity;
|
7857
|
}
|
7858
|
|
7859
|
/**
|
7860
|
* Load entities from the database.
|
7861
|
*
|
7862
|
* The entities are stored in a static memory cache, and will not require
|
7863
|
* database access if loaded again during the same page request.
|
7864
|
*
|
7865
|
* The actual loading is done through a class that has to implement the
|
7866
|
* DrupalEntityControllerInterface interface. By default,
|
7867
|
* DrupalDefaultEntityController is used. Entity types can specify that a
|
7868
|
* different class should be used by setting the 'controller class' key in
|
7869
|
* hook_entity_info(). These classes can either implement the
|
7870
|
* DrupalEntityControllerInterface interface, or, most commonly, extend the
|
7871
|
* DrupalDefaultEntityController class. See node_entity_info() and the
|
7872
|
* NodeController in node.module as an example.
|
7873
|
*
|
7874
|
* @param $entity_type
|
7875
|
* The entity type to load, e.g. node or user.
|
7876
|
* @param $ids
|
7877
|
* An array of entity IDs, or FALSE to load all entities.
|
7878
|
* @param $conditions
|
7879
|
* (deprecated) An associative array of conditions on the base table, where
|
7880
|
* the keys are the database fields and the values are the values those
|
7881
|
* fields must have. Instead, it is preferable to use EntityFieldQuery to
|
7882
|
* retrieve a list of entity IDs loadable by this function.
|
7883
|
* @param $reset
|
7884
|
* Whether to reset the internal cache for the requested entity type.
|
7885
|
*
|
7886
|
* @return
|
7887
|
* An array of entity objects indexed by their ids. When no results are
|
7888
|
* found, an empty array is returned.
|
7889
|
*
|
7890
|
* @todo Remove $conditions in Drupal 8.
|
7891
|
*
|
7892
|
* @see hook_entity_info()
|
7893
|
* @see DrupalEntityControllerInterface
|
7894
|
* @see DrupalDefaultEntityController
|
7895
|
* @see EntityFieldQuery
|
7896
|
*/
|
7897
|
function entity_load($entity_type, $ids = FALSE, $conditions = array(), $reset = FALSE) {
|
7898
|
if ($reset) {
|
7899
|
entity_get_controller($entity_type)->resetCache();
|
7900
|
}
|
7901
|
return entity_get_controller($entity_type)->load($ids, $conditions);
|
7902
|
}
|
7903
|
|
7904
|
/**
|
7905
|
* Loads the unchanged, i.e. not modified, entity from the database.
|
7906
|
*
|
7907
|
* Unlike entity_load() this function ensures the entity is directly loaded from
|
7908
|
* the database, thus bypassing any static cache. In particular, this function
|
7909
|
* is useful to determine changes by comparing the entity being saved to the
|
7910
|
* stored entity.
|
7911
|
*
|
7912
|
* @param $entity_type
|
7913
|
* The entity type to load, e.g. node or user.
|
7914
|
* @param $id
|
7915
|
* The ID of the entity to load.
|
7916
|
*
|
7917
|
* @return
|
7918
|
* The unchanged entity, or FALSE if the entity cannot be loaded.
|
7919
|
*/
|
7920
|
function entity_load_unchanged($entity_type, $id) {
|
7921
|
entity_get_controller($entity_type)->resetCache(array($id));
|
7922
|
$result = entity_get_controller($entity_type)->load(array($id));
|
7923
|
return reset($result);
|
7924
|
}
|
7925
|
|
7926
|
/**
|
7927
|
* Gets the entity controller for an entity type.
|
7928
|
*
|
7929
|
* @return DrupalEntityControllerInterface
|
7930
|
* The entity controller object for the specified entity type.
|
7931
|
*/
|
7932
|
function entity_get_controller($entity_type) {
|
7933
|
$controllers = &drupal_static(__FUNCTION__, array());
|
7934
|
if (!isset($controllers[$entity_type])) {
|
7935
|
$type_info = entity_get_info($entity_type);
|
7936
|
$class = $type_info['controller class'];
|
7937
|
$controllers[$entity_type] = new $class($entity_type);
|
7938
|
}
|
7939
|
return $controllers[$entity_type];
|
7940
|
}
|
7941
|
|
7942
|
/**
|
7943
|
* Invoke hook_entity_prepare_view().
|
7944
|
*
|
7945
|
* If adding a new entity similar to nodes, comments or users, you should
|
7946
|
* invoke this function during the ENTITY_build_content() or
|
7947
|
* ENTITY_view_multiple() phases of rendering to allow other modules to alter
|
7948
|
* the objects during this phase. This is needed for situations where
|
7949
|
* information needs to be loaded outside of ENTITY_load() - particularly
|
7950
|
* when loading entities into one another - i.e. a user object into a node, due
|
7951
|
* to the potential for unwanted side-effects such as caching and infinite
|
7952
|
* recursion. By convention, entity_prepare_view() is called after
|
7953
|
* field_attach_prepare_view() to allow entity level hooks to act on content
|
7954
|
* loaded by field API.
|
7955
|
*
|
7956
|
* @param $entity_type
|
7957
|
* The type of entity, i.e. 'node', 'user'.
|
7958
|
* @param $entities
|
7959
|
* The entity objects which are being prepared for view, keyed by object ID.
|
7960
|
* @param $langcode
|
7961
|
* (optional) A language code to be used for rendering. Defaults to the global
|
7962
|
* content language of the current request.
|
7963
|
*
|
7964
|
* @see hook_entity_prepare_view()
|
7965
|
*/
|
7966
|
function entity_prepare_view($entity_type, $entities, $langcode = NULL) {
|
7967
|
if (!isset($langcode)) {
|
7968
|
$langcode = $GLOBALS['language_content']->language;
|
7969
|
}
|
7970
|
|
7971
|
// To ensure hooks are only run once per entity, check for an
|
7972
|
// entity_view_prepared flag and only process items without it.
|
7973
|
// @todo: resolve this more generally for both entity and field level hooks.
|
7974
|
$prepare = array();
|
7975
|
foreach ($entities as $id => $entity) {
|
7976
|
if (empty($entity->entity_view_prepared)) {
|
7977
|
// Add this entity to the items to be prepared.
|
7978
|
$prepare[$id] = $entity;
|
7979
|
|
7980
|
// Mark this item as prepared.
|
7981
|
$entity->entity_view_prepared = TRUE;
|
7982
|
}
|
7983
|
}
|
7984
|
|
7985
|
if (!empty($prepare)) {
|
7986
|
module_invoke_all('entity_prepare_view', $prepare, $entity_type, $langcode);
|
7987
|
}
|
7988
|
}
|
7989
|
|
7990
|
/**
|
7991
|
* Invoke hook_entity_view_mode_alter().
|
7992
|
*
|
7993
|
* If adding a new entity similar to nodes, comments or users, you should invoke
|
7994
|
* this function during the ENTITY_build_content() or ENTITY_view_multiple()
|
7995
|
* phases of rendering to allow other modules to alter the view mode during this
|
7996
|
* phase. This function needs to be called before field_attach_prepare_view() to
|
7997
|
* ensure that the correct content is loaded by field API.
|
7998
|
*
|
7999
|
* @param $entity_type
|
8000
|
* The type of entity, i.e. 'node', 'user'.
|
8001
|
* @param $entities
|
8002
|
* The entity objects which are being prepared for view, keyed by object ID.
|
8003
|
* @param $view_mode
|
8004
|
* The original view mode e.g. 'full', 'teaser'...
|
8005
|
* @param $langcode
|
8006
|
* (optional) A language code to be used for rendering. Defaults to the global
|
8007
|
* content language of the current request.
|
8008
|
* @return
|
8009
|
* An associative array with arrays of entities keyed by view mode.
|
8010
|
*
|
8011
|
* @see hook_entity_view_mode_alter()
|
8012
|
*/
|
8013
|
function entity_view_mode_prepare($entity_type, $entities, $view_mode, $langcode = NULL) {
|
8014
|
if (!isset($langcode)) {
|
8015
|
$langcode = $GLOBALS['language_content']->language;
|
8016
|
}
|
8017
|
|
8018
|
// To ensure hooks are never run after field_attach_prepare_view() only
|
8019
|
// process items without the entity_view_prepared flag.
|
8020
|
$entities_by_view_mode = array();
|
8021
|
foreach ($entities as $id => $entity) {
|
8022
|
$entity_view_mode = $view_mode;
|
8023
|
if (empty($entity->entity_view_prepared)) {
|
8024
|
|
8025
|
// Allow modules to change the view mode.
|
8026
|
$context = array(
|
8027
|
'entity_type' => $entity_type,
|
8028
|
'entity' => $entity,
|
8029
|
'langcode' => $langcode,
|
8030
|
);
|
8031
|
drupal_alter('entity_view_mode', $entity_view_mode, $context);
|
8032
|
}
|
8033
|
|
8034
|
$entities_by_view_mode[$entity_view_mode][$id] = $entity;
|
8035
|
}
|
8036
|
|
8037
|
return $entities_by_view_mode;
|
8038
|
}
|
8039
|
|
8040
|
/**
|
8041
|
* Returns the URI elements of an entity.
|
8042
|
*
|
8043
|
* @param $entity_type
|
8044
|
* The entity type; e.g. 'node' or 'user'.
|
8045
|
* @param $entity
|
8046
|
* The entity for which to generate a path.
|
8047
|
* @return
|
8048
|
* An array containing the 'path' and 'options' keys used to build the URI of
|
8049
|
* the entity, and matching the signature of url(). NULL if the entity has no
|
8050
|
* URI of its own.
|
8051
|
*/
|
8052
|
function entity_uri($entity_type, $entity) {
|
8053
|
$info = entity_get_info($entity_type);
|
8054
|
list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
|
8055
|
|
8056
|
// A bundle-specific callback takes precedence over the generic one for the
|
8057
|
// entity type.
|
8058
|
if (isset($info['bundles'][$bundle]['uri callback'])) {
|
8059
|
$uri_callback = $info['bundles'][$bundle]['uri callback'];
|
8060
|
}
|
8061
|
elseif (isset($info['uri callback'])) {
|
8062
|
$uri_callback = $info['uri callback'];
|
8063
|
}
|
8064
|
else {
|
8065
|
return NULL;
|
8066
|
}
|
8067
|
|
8068
|
// Invoke the callback to get the URI. If there is no callback, return NULL.
|
8069
|
if (isset($uri_callback) && function_exists($uri_callback)) {
|
8070
|
$uri = $uri_callback($entity);
|
8071
|
// Pass the entity data to url() so that alter functions do not need to
|
8072
|
// lookup this entity again.
|
8073
|
$uri['options']['entity_type'] = $entity_type;
|
8074
|
$uri['options']['entity'] = $entity;
|
8075
|
return $uri;
|
8076
|
}
|
8077
|
}
|
8078
|
|
8079
|
/**
|
8080
|
* Returns the label of an entity.
|
8081
|
*
|
8082
|
* See the 'label callback' component of the hook_entity_info() return value
|
8083
|
* for more information.
|
8084
|
*
|
8085
|
* @param $entity_type
|
8086
|
* The entity type; e.g., 'node' or 'user'.
|
8087
|
* @param $entity
|
8088
|
* The entity for which to generate the label.
|
8089
|
*
|
8090
|
* @return
|
8091
|
* The entity label, or FALSE if not found.
|
8092
|
*/
|
8093
|
function entity_label($entity_type, $entity) {
|
8094
|
$label = FALSE;
|
8095
|
$info = entity_get_info($entity_type);
|
8096
|
if (isset($info['label callback']) && function_exists($info['label callback'])) {
|
8097
|
$label = $info['label callback']($entity, $entity_type);
|
8098
|
}
|
8099
|
elseif (!empty($info['entity keys']['label']) && isset($entity->{$info['entity keys']['label']})) {
|
8100
|
$label = $entity->{$info['entity keys']['label']};
|
8101
|
}
|
8102
|
|
8103
|
return $label;
|
8104
|
}
|
8105
|
|
8106
|
/**
|
8107
|
* Returns the language of an entity.
|
8108
|
*
|
8109
|
* @param $entity_type
|
8110
|
* The entity type; e.g., 'node' or 'user'.
|
8111
|
* @param $entity
|
8112
|
* The entity for which to get the language.
|
8113
|
*
|
8114
|
* @return
|
8115
|
* A valid language code or NULL if the entity has no language support.
|
8116
|
*/
|
8117
|
function entity_language($entity_type, $entity) {
|
8118
|
$info = entity_get_info($entity_type);
|
8119
|
|
8120
|
// Invoke the callback to get the language. If there is no callback, try to
|
8121
|
// get it from a property of the entity, otherwise NULL.
|
8122
|
if (isset($info['language callback']) && function_exists($info['language callback'])) {
|
8123
|
$langcode = $info['language callback']($entity_type, $entity);
|
8124
|
}
|
8125
|
elseif (!empty($info['entity keys']['language']) && isset($entity->{$info['entity keys']['language']})) {
|
8126
|
$langcode = $entity->{$info['entity keys']['language']};
|
8127
|
}
|
8128
|
else {
|
8129
|
// The value returned in D8 would be LANGUAGE_NONE, we cannot use it here to
|
8130
|
// preserve backward compatibility. In fact this function has been
|
8131
|
// introduced very late in the D7 life cycle, mainly as the proper default
|
8132
|
// for field_attach_form(). By returning LANGUAGE_NONE when no language
|
8133
|
// information is available, we would introduce a potentially BC-breaking
|
8134
|
// API change, since field_attach_form() defaults to the default language
|
8135
|
// instead of LANGUAGE_NONE. Moreover this allows us to distinguish between
|
8136
|
// entities that have no language specified from ones that do not have
|
8137
|
// language support at all.
|
8138
|
$langcode = NULL;
|
8139
|
}
|
8140
|
|
8141
|
return $langcode;
|
8142
|
}
|
8143
|
|
8144
|
/**
|
8145
|
* Attaches field API validation to entity forms.
|
8146
|
*/
|
8147
|
function entity_form_field_validate($entity_type, $form, &$form_state) {
|
8148
|
// All field attach API functions act on an entity object, but during form
|
8149
|
// validation, we don't have one. $form_state contains the entity as it was
|
8150
|
// prior to processing the current form submission, and we must not update it
|
8151
|
// until we have fully validated the submitted input. Therefore, for
|
8152
|
// validation, act on a pseudo entity created out of the form values.
|
8153
|
$pseudo_entity = (object) $form_state['values'];
|
8154
|
field_attach_form_validate($entity_type, $pseudo_entity, $form, $form_state);
|
8155
|
}
|
8156
|
|
8157
|
/**
|
8158
|
* Copies submitted values to entity properties for simple entity forms.
|
8159
|
*
|
8160
|
* During the submission handling of an entity form's "Save", "Preview", and
|
8161
|
* possibly other buttons, the form state's entity needs to be updated with the
|
8162
|
* submitted form values. Each entity form implements its own builder function
|
8163
|
* for doing this, appropriate for the particular entity and form, whereas
|
8164
|
* modules may specify additional builder functions in $form['#entity_builders']
|
8165
|
* for copying the form values of added form elements to entity properties.
|
8166
|
* Many of the main entity builder functions can call this helper function to
|
8167
|
* re-use its logic of copying $form_state['values'][PROPERTY] values to
|
8168
|
* $entity->PROPERTY for all entries in $form_state['values'] that are not field
|
8169
|
* data, and calling field_attach_submit() to copy field data. Apart from that
|
8170
|
* this helper invokes any additional builder functions that have been specified
|
8171
|
* in $form['#entity_builders'].
|
8172
|
*
|
8173
|
* For some entity forms (e.g., forms with complex non-field data and forms that
|
8174
|
* simultaneously edit multiple entities), this behavior may be inappropriate,
|
8175
|
* so the builder function for such forms needs to implement the required
|
8176
|
* functionality instead of calling this function.
|
8177
|
*/
|
8178
|
function entity_form_submit_build_entity($entity_type, $entity, $form, &$form_state) {
|
8179
|
$info = entity_get_info($entity_type);
|
8180
|
list(, , $bundle) = entity_extract_ids($entity_type, $entity);
|
8181
|
|
8182
|
// Copy top-level form values that are not for fields to entity properties,
|
8183
|
// without changing existing entity properties that are not being edited by
|
8184
|
// this form. Copying field values must be done using field_attach_submit().
|
8185
|
$values_excluding_fields = $info['fieldable'] ? array_diff_key($form_state['values'], field_info_instances($entity_type, $bundle)) : $form_state['values'];
|
8186
|
foreach ($values_excluding_fields as $key => $value) {
|
8187
|
$entity->$key = $value;
|
8188
|
}
|
8189
|
|
8190
|
// Invoke all specified builders for copying form values to entity properties.
|
8191
|
if (isset($form['#entity_builders'])) {
|
8192
|
foreach ($form['#entity_builders'] as $function) {
|
8193
|
$function($entity_type, $entity, $form, $form_state);
|
8194
|
}
|
8195
|
}
|
8196
|
|
8197
|
// Copy field values to the entity.
|
8198
|
if ($info['fieldable']) {
|
8199
|
field_attach_submit($entity_type, $entity, $form, $form_state);
|
8200
|
}
|
8201
|
}
|
8202
|
|
8203
|
/**
|
8204
|
* Performs one or more XML-RPC request(s).
|
8205
|
*
|
8206
|
* Usage example:
|
8207
|
* @code
|
8208
|
* $result = xmlrpc('http://example.com/xmlrpc.php', array(
|
8209
|
* 'service.methodName' => array($parameter, $second, $third),
|
8210
|
* ));
|
8211
|
* @endcode
|
8212
|
*
|
8213
|
* @param $url
|
8214
|
* An absolute URL of the XML-RPC endpoint.
|
8215
|
* @param $args
|
8216
|
* An associative array whose keys are the methods to call and whose values
|
8217
|
* are the arguments to pass to the respective method. If multiple methods
|
8218
|
* are specified, a system.multicall is performed.
|
8219
|
* @param $options
|
8220
|
* (optional) An array of options to pass along to drupal_http_request().
|
8221
|
*
|
8222
|
* @return
|
8223
|
* For one request:
|
8224
|
* Either the return value of the method on success, or FALSE.
|
8225
|
* If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
|
8226
|
* For multiple requests:
|
8227
|
* An array of results. Each result will either be the result
|
8228
|
* returned by the method called, or an xmlrpc_error object if the call
|
8229
|
* failed. See xmlrpc_error().
|
8230
|
*/
|
8231
|
function xmlrpc($url, $args, $options = array()) {
|
8232
|
require_once DRUPAL_ROOT . '/includes/xmlrpc.inc';
|
8233
|
return _xmlrpc($url, $args, $options);
|
8234
|
}
|
8235
|
|
8236
|
/**
|
8237
|
* Retrieves a list of all available archivers.
|
8238
|
*
|
8239
|
* @see hook_archiver_info()
|
8240
|
* @see hook_archiver_info_alter()
|
8241
|
*/
|
8242
|
function archiver_get_info() {
|
8243
|
$archiver_info = &drupal_static(__FUNCTION__, array());
|
8244
|
|
8245
|
if (empty($archiver_info)) {
|
8246
|
$cache = cache_get('archiver_info');
|
8247
|
if ($cache === FALSE) {
|
8248
|
// Rebuild the cache and save it.
|
8249
|
$archiver_info = module_invoke_all('archiver_info');
|
8250
|
drupal_alter('archiver_info', $archiver_info);
|
8251
|
uasort($archiver_info, 'drupal_sort_weight');
|
8252
|
cache_set('archiver_info', $archiver_info);
|
8253
|
}
|
8254
|
else {
|
8255
|
$archiver_info = $cache->data;
|
8256
|
}
|
8257
|
}
|
8258
|
|
8259
|
return $archiver_info;
|
8260
|
}
|
8261
|
|
8262
|
/**
|
8263
|
* Returns a string of supported archive extensions.
|
8264
|
*
|
8265
|
* @return
|
8266
|
* A space-separated string of extensions suitable for use by the file
|
8267
|
* validation system.
|
8268
|
*/
|
8269
|
function archiver_get_extensions() {
|
8270
|
$valid_extensions = array();
|
8271
|
foreach (archiver_get_info() as $archive) {
|
8272
|
foreach ($archive['extensions'] as $extension) {
|
8273
|
foreach (explode('.', $extension) as $part) {
|
8274
|
if (!in_array($part, $valid_extensions)) {
|
8275
|
$valid_extensions[] = $part;
|
8276
|
}
|
8277
|
}
|
8278
|
}
|
8279
|
}
|
8280
|
return implode(' ', $valid_extensions);
|
8281
|
}
|
8282
|
|
8283
|
/**
|
8284
|
* Creates the appropriate archiver for the specified file.
|
8285
|
*
|
8286
|
* @param $file
|
8287
|
* The full path of the archive file. Note that stream wrapper paths are
|
8288
|
* supported, but not remote ones.
|
8289
|
*
|
8290
|
* @return
|
8291
|
* A newly created instance of the archiver class appropriate
|
8292
|
* for the specified file, already bound to that file.
|
8293
|
* If no appropriate archiver class was found, will return FALSE.
|
8294
|
*/
|
8295
|
function archiver_get_archiver($file) {
|
8296
|
// Archivers can only work on local paths
|
8297
|
$filepath = drupal_realpath($file);
|
8298
|
if (!is_file($filepath)) {
|
8299
|
throw new Exception(t('Archivers can only operate on local files: %file not supported', array('%file' => $file)));
|
8300
|
}
|
8301
|
$archiver_info = archiver_get_info();
|
8302
|
|
8303
|
foreach ($archiver_info as $implementation) {
|
8304
|
foreach ($implementation['extensions'] as $extension) {
|
8305
|
// Because extensions may be multi-part, such as .tar.gz,
|
8306
|
// we cannot use simpler approaches like substr() or pathinfo().
|
8307
|
// This method isn't quite as clean but gets the job done.
|
8308
|
// Also note that the file may not yet exist, so we cannot rely
|
8309
|
// on fileinfo() or other disk-level utilities.
|
8310
|
if (strrpos($filepath, '.' . $extension) === strlen($filepath) - strlen('.' . $extension)) {
|
8311
|
return new $implementation['class']($filepath);
|
8312
|
}
|
8313
|
}
|
8314
|
}
|
8315
|
}
|
8316
|
|
8317
|
/**
|
8318
|
* Assembles the Drupal Updater registry.
|
8319
|
*
|
8320
|
* An Updater is a class that knows how to update various parts of the Drupal
|
8321
|
* file system, for example to update modules that have newer releases, or to
|
8322
|
* install a new theme.
|
8323
|
*
|
8324
|
* @return
|
8325
|
* The Drupal Updater class registry.
|
8326
|
*
|
8327
|
* @see hook_updater_info()
|
8328
|
* @see hook_updater_info_alter()
|
8329
|
*/
|
8330
|
function drupal_get_updaters() {
|
8331
|
$updaters = &drupal_static(__FUNCTION__);
|
8332
|
if (!isset($updaters)) {
|
8333
|
$updaters = module_invoke_all('updater_info');
|
8334
|
drupal_alter('updater_info', $updaters);
|
8335
|
uasort($updaters, 'drupal_sort_weight');
|
8336
|
}
|
8337
|
return $updaters;
|
8338
|
}
|
8339
|
|
8340
|
/**
|
8341
|
* Assembles the Drupal FileTransfer registry.
|
8342
|
*
|
8343
|
* @return
|
8344
|
* The Drupal FileTransfer class registry.
|
8345
|
*
|
8346
|
* @see FileTransfer
|
8347
|
* @see hook_filetransfer_info()
|
8348
|
* @see hook_filetransfer_info_alter()
|
8349
|
*/
|
8350
|
function drupal_get_filetransfer_info() {
|
8351
|
$info = &drupal_static(__FUNCTION__);
|
8352
|
if (!isset($info)) {
|
8353
|
// Since we have to manually set the 'file path' default for each
|
8354
|
// module separately, we can't use module_invoke_all().
|
8355
|
$info = array();
|
8356
|
foreach (module_implements('filetransfer_info') as $module) {
|
8357
|
$function = $module . '_filetransfer_info';
|
8358
|
if (function_exists($function)) {
|
8359
|
$result = $function();
|
8360
|
if (isset($result) && is_array($result)) {
|
8361
|
foreach ($result as &$values) {
|
8362
|
if (empty($values['file path'])) {
|
8363
|
$values['file path'] = drupal_get_path('module', $module);
|
8364
|
}
|
8365
|
}
|
8366
|
$info = array_merge_recursive($info, $result);
|
8367
|
}
|
8368
|
}
|
8369
|
}
|
8370
|
drupal_alter('filetransfer_info', $info);
|
8371
|
uasort($info, 'drupal_sort_weight');
|
8372
|
}
|
8373
|
return $info;
|
8374
|
}
|