1
|
<?php
|
2
|
|
3
|
/**
|
4
|
* @file
|
5
|
* Functions that need to be loaded on every Drupal request.
|
6
|
*/
|
7
|
|
8
|
/**
|
9
|
* The current system version.
|
10
|
*/
|
11
|
define('VERSION', '7.69');
|
12
|
|
13
|
/**
|
14
|
* Core API compatibility.
|
15
|
*/
|
16
|
define('DRUPAL_CORE_COMPATIBILITY', '7.x');
|
17
|
|
18
|
/**
|
19
|
* Minimum supported version of PHP.
|
20
|
*/
|
21
|
define('DRUPAL_MINIMUM_PHP', '5.2.4');
|
22
|
|
23
|
/**
|
24
|
* Minimum recommended value of PHP memory_limit.
|
25
|
*/
|
26
|
define('DRUPAL_MINIMUM_PHP_MEMORY_LIMIT', '32M');
|
27
|
|
28
|
/**
|
29
|
* Error reporting level: display no errors.
|
30
|
*/
|
31
|
define('ERROR_REPORTING_HIDE', 0);
|
32
|
|
33
|
/**
|
34
|
* Error reporting level: display errors and warnings.
|
35
|
*/
|
36
|
define('ERROR_REPORTING_DISPLAY_SOME', 1);
|
37
|
|
38
|
/**
|
39
|
* Error reporting level: display all messages.
|
40
|
*/
|
41
|
define('ERROR_REPORTING_DISPLAY_ALL', 2);
|
42
|
|
43
|
/**
|
44
|
* Indicates that the item should never be removed unless explicitly selected.
|
45
|
*
|
46
|
* The item may be removed using cache_clear_all() with a cache ID.
|
47
|
*/
|
48
|
define('CACHE_PERMANENT', 0);
|
49
|
|
50
|
/**
|
51
|
* Indicates that the item should be removed at the next general cache wipe.
|
52
|
*/
|
53
|
define('CACHE_TEMPORARY', -1);
|
54
|
|
55
|
/**
|
56
|
* @defgroup logging_severity_levels Logging severity levels
|
57
|
* @{
|
58
|
* Logging severity levels as defined in RFC 3164.
|
59
|
*
|
60
|
* The WATCHDOG_* constant definitions correspond to the logging severity levels
|
61
|
* defined in RFC 3164, section 4.1.1. PHP supplies predefined LOG_* constants
|
62
|
* for use in the syslog() function, but their values on Windows builds do not
|
63
|
* correspond to RFC 3164. The associated PHP bug report was closed with the
|
64
|
* comment, "And it's also not a bug, as Windows just have less log levels,"
|
65
|
* and "So the behavior you're seeing is perfectly normal."
|
66
|
*
|
67
|
* @see http://www.faqs.org/rfcs/rfc3164.html
|
68
|
* @see http://bugs.php.net/bug.php?id=18090
|
69
|
* @see http://php.net/manual/function.syslog.php
|
70
|
* @see http://php.net/manual/network.constants.php
|
71
|
* @see watchdog()
|
72
|
* @see watchdog_severity_levels()
|
73
|
*/
|
74
|
|
75
|
/**
|
76
|
* Log message severity -- Emergency: system is unusable.
|
77
|
*/
|
78
|
define('WATCHDOG_EMERGENCY', 0);
|
79
|
|
80
|
/**
|
81
|
* Log message severity -- Alert: action must be taken immediately.
|
82
|
*/
|
83
|
define('WATCHDOG_ALERT', 1);
|
84
|
|
85
|
/**
|
86
|
* Log message severity -- Critical conditions.
|
87
|
*/
|
88
|
define('WATCHDOG_CRITICAL', 2);
|
89
|
|
90
|
/**
|
91
|
* Log message severity -- Error conditions.
|
92
|
*/
|
93
|
define('WATCHDOG_ERROR', 3);
|
94
|
|
95
|
/**
|
96
|
* Log message severity -- Warning conditions.
|
97
|
*/
|
98
|
define('WATCHDOG_WARNING', 4);
|
99
|
|
100
|
/**
|
101
|
* Log message severity -- Normal but significant conditions.
|
102
|
*/
|
103
|
define('WATCHDOG_NOTICE', 5);
|
104
|
|
105
|
/**
|
106
|
* Log message severity -- Informational messages.
|
107
|
*/
|
108
|
define('WATCHDOG_INFO', 6);
|
109
|
|
110
|
/**
|
111
|
* Log message severity -- Debug-level messages.
|
112
|
*/
|
113
|
define('WATCHDOG_DEBUG', 7);
|
114
|
|
115
|
/**
|
116
|
* @} End of "defgroup logging_severity_levels".
|
117
|
*/
|
118
|
|
119
|
/**
|
120
|
* First bootstrap phase: initialize configuration.
|
121
|
*/
|
122
|
define('DRUPAL_BOOTSTRAP_CONFIGURATION', 0);
|
123
|
|
124
|
/**
|
125
|
* Second bootstrap phase: try to serve a cached page.
|
126
|
*/
|
127
|
define('DRUPAL_BOOTSTRAP_PAGE_CACHE', 1);
|
128
|
|
129
|
/**
|
130
|
* Third bootstrap phase: initialize database layer.
|
131
|
*/
|
132
|
define('DRUPAL_BOOTSTRAP_DATABASE', 2);
|
133
|
|
134
|
/**
|
135
|
* Fourth bootstrap phase: initialize the variable system.
|
136
|
*/
|
137
|
define('DRUPAL_BOOTSTRAP_VARIABLES', 3);
|
138
|
|
139
|
/**
|
140
|
* Fifth bootstrap phase: initialize session handling.
|
141
|
*/
|
142
|
define('DRUPAL_BOOTSTRAP_SESSION', 4);
|
143
|
|
144
|
/**
|
145
|
* Sixth bootstrap phase: set up the page header.
|
146
|
*/
|
147
|
define('DRUPAL_BOOTSTRAP_PAGE_HEADER', 5);
|
148
|
|
149
|
/**
|
150
|
* Seventh bootstrap phase: find out language of the page.
|
151
|
*/
|
152
|
define('DRUPAL_BOOTSTRAP_LANGUAGE', 6);
|
153
|
|
154
|
/**
|
155
|
* Final bootstrap phase: Drupal is fully loaded; validate and fix input data.
|
156
|
*/
|
157
|
define('DRUPAL_BOOTSTRAP_FULL', 7);
|
158
|
|
159
|
/**
|
160
|
* Role ID for anonymous users; should match what's in the "role" table.
|
161
|
*/
|
162
|
define('DRUPAL_ANONYMOUS_RID', 1);
|
163
|
|
164
|
/**
|
165
|
* Role ID for authenticated users; should match what's in the "role" table.
|
166
|
*/
|
167
|
define('DRUPAL_AUTHENTICATED_RID', 2);
|
168
|
|
169
|
/**
|
170
|
* The number of bytes in a kilobyte.
|
171
|
*
|
172
|
* For more information, visit http://en.wikipedia.org/wiki/Kilobyte.
|
173
|
*/
|
174
|
define('DRUPAL_KILOBYTE', 1024);
|
175
|
|
176
|
/**
|
177
|
* The language code used when no language is explicitly assigned.
|
178
|
*
|
179
|
* Defined by ISO639-2 for "Undetermined".
|
180
|
*/
|
181
|
define('LANGUAGE_NONE', 'und');
|
182
|
|
183
|
/**
|
184
|
* The type of language used to define the content language.
|
185
|
*/
|
186
|
define('LANGUAGE_TYPE_CONTENT', 'language_content');
|
187
|
|
188
|
/**
|
189
|
* The type of language used to select the user interface.
|
190
|
*/
|
191
|
define('LANGUAGE_TYPE_INTERFACE', 'language');
|
192
|
|
193
|
/**
|
194
|
* The type of language used for URLs.
|
195
|
*/
|
196
|
define('LANGUAGE_TYPE_URL', 'language_url');
|
197
|
|
198
|
/**
|
199
|
* Language written left to right. Possible value of $language->direction.
|
200
|
*/
|
201
|
define('LANGUAGE_LTR', 0);
|
202
|
|
203
|
/**
|
204
|
* Language written right to left. Possible value of $language->direction.
|
205
|
*/
|
206
|
define('LANGUAGE_RTL', 1);
|
207
|
|
208
|
/**
|
209
|
* Time of the current request in seconds elapsed since the Unix Epoch.
|
210
|
*
|
211
|
* This differs from $_SERVER['REQUEST_TIME'], which is stored as a float
|
212
|
* since PHP 5.4.0. Float timestamps confuse most PHP functions
|
213
|
* (including date_create()).
|
214
|
*
|
215
|
* @see http://php.net/manual/reserved.variables.server.php
|
216
|
* @see http://php.net/manual/function.time.php
|
217
|
*/
|
218
|
define('REQUEST_TIME', (int) $_SERVER['REQUEST_TIME']);
|
219
|
|
220
|
/**
|
221
|
* Flag used to indicate that text is not sanitized, so run check_plain().
|
222
|
*
|
223
|
* @see drupal_set_title()
|
224
|
*/
|
225
|
define('CHECK_PLAIN', 0);
|
226
|
|
227
|
/**
|
228
|
* Flag used to indicate that text has already been sanitized.
|
229
|
*
|
230
|
* @see drupal_set_title()
|
231
|
*/
|
232
|
define('PASS_THROUGH', -1);
|
233
|
|
234
|
/**
|
235
|
* Signals that the registry lookup cache should be reset.
|
236
|
*/
|
237
|
define('REGISTRY_RESET_LOOKUP_CACHE', 1);
|
238
|
|
239
|
/**
|
240
|
* Signals that the registry lookup cache should be written to storage.
|
241
|
*/
|
242
|
define('REGISTRY_WRITE_LOOKUP_CACHE', 2);
|
243
|
|
244
|
/**
|
245
|
* Regular expression to match PHP function names.
|
246
|
*
|
247
|
* @see http://php.net/manual/language.functions.php
|
248
|
*/
|
249
|
define('DRUPAL_PHP_FUNCTION_PATTERN', '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*');
|
250
|
|
251
|
/**
|
252
|
* A RFC7231 Compliant date.
|
253
|
*
|
254
|
* http://tools.ietf.org/html/rfc7231#section-7.1.1.1
|
255
|
*
|
256
|
* Example: Sun, 06 Nov 1994 08:49:37 GMT
|
257
|
*
|
258
|
* This constant was introduced in PHP 7.0.19 and PHP 7.1.5 but needs to be
|
259
|
* defined by Drupal for earlier PHP versions.
|
260
|
*/
|
261
|
if (!defined('DATE_RFC7231')) {
|
262
|
define('DATE_RFC7231', 'D, d M Y H:i:s \G\M\T');
|
263
|
}
|
264
|
|
265
|
/**
|
266
|
* Provides a caching wrapper to be used in place of large array structures.
|
267
|
*
|
268
|
* This class should be extended by systems that need to cache large amounts
|
269
|
* of data and have it represented as an array to calling functions. These
|
270
|
* arrays can become very large, so ArrayAccess is used to allow different
|
271
|
* strategies to be used for caching internally (lazy loading, building caches
|
272
|
* over time etc.). This can dramatically reduce the amount of data that needs
|
273
|
* to be loaded from cache backends on each request, and memory usage from
|
274
|
* static caches of that same data.
|
275
|
*
|
276
|
* Note that array_* functions do not work with ArrayAccess. Systems using
|
277
|
* DrupalCacheArray should use this only internally. If providing API functions
|
278
|
* that return the full array, this can be cached separately or returned
|
279
|
* directly. However since DrupalCacheArray holds partial content by design, it
|
280
|
* should be a normal PHP array or otherwise contain the full structure.
|
281
|
*
|
282
|
* Note also that due to limitations in PHP prior to 5.3.4, it is impossible to
|
283
|
* write directly to the contents of nested arrays contained in this object.
|
284
|
* Only writes to the top-level array elements are possible. So if you
|
285
|
* previously had set $object['foo'] = array(1, 2, 'bar' => 'baz'), but later
|
286
|
* want to change the value of 'bar' from 'baz' to 'foobar', you cannot do so
|
287
|
* a targeted write like $object['foo']['bar'] = 'foobar'. Instead, you must
|
288
|
* overwrite the entire top-level 'foo' array with the entire set of new
|
289
|
* values: $object['foo'] = array(1, 2, 'bar' => 'foobar'). Due to this same
|
290
|
* limitation, attempts to create references to any contained data, nested or
|
291
|
* otherwise, will fail silently. So $var = &$object['foo'] will not throw an
|
292
|
* error, and $var will be populated with the contents of $object['foo'], but
|
293
|
* that data will be passed by value, not reference. For more information on
|
294
|
* the PHP limitation, see the note in the official PHP documentation at·
|
295
|
* http://php.net/manual/arrayaccess.offsetget.php on
|
296
|
* ArrayAccess::offsetGet().
|
297
|
*
|
298
|
* By default, the class accounts for caches where calling functions might
|
299
|
* request keys in the array that won't exist even after a cache rebuild. This
|
300
|
* prevents situations where a cache rebuild would be triggered over and over
|
301
|
* due to a 'missing' item. These cases are stored internally as a value of
|
302
|
* NULL. This means that the offsetGet() and offsetExists() methods
|
303
|
* must be overridden if caching an array where the top level values can
|
304
|
* legitimately be NULL, and where $object->offsetExists() needs to correctly
|
305
|
* return (equivalent to array_key_exists() vs. isset()). This should not
|
306
|
* be necessary in the majority of cases.
|
307
|
*
|
308
|
* Classes extending this class must override at least the
|
309
|
* resolveCacheMiss() method to have a working implementation.
|
310
|
*
|
311
|
* offsetSet() is not overridden by this class by default. In practice this
|
312
|
* means that assigning an offset via arrayAccess will only apply while the
|
313
|
* object is in scope and will not be written back to the persistent cache.
|
314
|
* This follows a similar pattern to static vs. persistent caching in
|
315
|
* procedural code. Extending classes may wish to alter this behavior, for
|
316
|
* example by overriding offsetSet() and adding an automatic call to persist().
|
317
|
*
|
318
|
* @see SchemaCache
|
319
|
*/
|
320
|
abstract class DrupalCacheArray implements ArrayAccess {
|
321
|
|
322
|
/**
|
323
|
* A cid to pass to cache_set() and cache_get().
|
324
|
*/
|
325
|
protected $cid;
|
326
|
|
327
|
/**
|
328
|
* A bin to pass to cache_set() and cache_get().
|
329
|
*/
|
330
|
protected $bin;
|
331
|
|
332
|
/**
|
333
|
* An array of keys to add to the cache at the end of the request.
|
334
|
*/
|
335
|
protected $keysToPersist = array();
|
336
|
|
337
|
/**
|
338
|
* Storage for the data itself.
|
339
|
*/
|
340
|
protected $storage = array();
|
341
|
|
342
|
/**
|
343
|
* Constructs a DrupalCacheArray object.
|
344
|
*
|
345
|
* @param $cid
|
346
|
* The cid for the array being cached.
|
347
|
* @param $bin
|
348
|
* The bin to cache the array.
|
349
|
*/
|
350
|
public function __construct($cid, $bin) {
|
351
|
$this->cid = $cid;
|
352
|
$this->bin = $bin;
|
353
|
|
354
|
if ($cached = cache_get($this->cid, $this->bin)) {
|
355
|
$this->storage = $cached->data;
|
356
|
}
|
357
|
}
|
358
|
|
359
|
/**
|
360
|
* Implements ArrayAccess::offsetExists().
|
361
|
*/
|
362
|
public function offsetExists($offset) {
|
363
|
return $this->offsetGet($offset) !== NULL;
|
364
|
}
|
365
|
|
366
|
/**
|
367
|
* Implements ArrayAccess::offsetGet().
|
368
|
*/
|
369
|
public function offsetGet($offset) {
|
370
|
if (isset($this->storage[$offset]) || array_key_exists($offset, $this->storage)) {
|
371
|
return $this->storage[$offset];
|
372
|
}
|
373
|
else {
|
374
|
return $this->resolveCacheMiss($offset);
|
375
|
}
|
376
|
}
|
377
|
|
378
|
/**
|
379
|
* Implements ArrayAccess::offsetSet().
|
380
|
*/
|
381
|
public function offsetSet($offset, $value) {
|
382
|
$this->storage[$offset] = $value;
|
383
|
}
|
384
|
|
385
|
/**
|
386
|
* Implements ArrayAccess::offsetUnset().
|
387
|
*/
|
388
|
public function offsetUnset($offset) {
|
389
|
unset($this->storage[$offset]);
|
390
|
}
|
391
|
|
392
|
/**
|
393
|
* Flags an offset value to be written to the persistent cache.
|
394
|
*
|
395
|
* If a value is assigned to a cache object with offsetSet(), by default it
|
396
|
* will not be written to the persistent cache unless it is flagged with this
|
397
|
* method. This allows items to be cached for the duration of a request,
|
398
|
* without necessarily writing back to the persistent cache at the end.
|
399
|
*
|
400
|
* @param $offset
|
401
|
* The array offset that was requested.
|
402
|
* @param $persist
|
403
|
* Optional boolean to specify whether the offset should be persisted or
|
404
|
* not, defaults to TRUE. When called with $persist = FALSE the offset will
|
405
|
* be unflagged so that it will not be written at the end of the request.
|
406
|
*/
|
407
|
protected function persist($offset, $persist = TRUE) {
|
408
|
$this->keysToPersist[$offset] = $persist;
|
409
|
}
|
410
|
|
411
|
/**
|
412
|
* Resolves a cache miss.
|
413
|
*
|
414
|
* When an offset is not found in the object, this is treated as a cache
|
415
|
* miss. This method allows classes implementing the interface to look up
|
416
|
* the actual value and allow it to be cached.
|
417
|
*
|
418
|
* @param $offset
|
419
|
* The offset that was requested.
|
420
|
*
|
421
|
* @return
|
422
|
* The value of the offset, or NULL if no value was found.
|
423
|
*/
|
424
|
abstract protected function resolveCacheMiss($offset);
|
425
|
|
426
|
/**
|
427
|
* Writes a value to the persistent cache immediately.
|
428
|
*
|
429
|
* @param $data
|
430
|
* The data to write to the persistent cache.
|
431
|
* @param $lock
|
432
|
* Whether to acquire a lock before writing to cache.
|
433
|
*/
|
434
|
protected function set($data, $lock = TRUE) {
|
435
|
// Lock cache writes to help avoid stampedes.
|
436
|
// To implement locking for cache misses, override __construct().
|
437
|
$lock_name = $this->cid . ':' . $this->bin;
|
438
|
if (!$lock || lock_acquire($lock_name)) {
|
439
|
if ($cached = cache_get($this->cid, $this->bin)) {
|
440
|
$data = $cached->data + $data;
|
441
|
}
|
442
|
cache_set($this->cid, $data, $this->bin);
|
443
|
if ($lock) {
|
444
|
lock_release($lock_name);
|
445
|
}
|
446
|
}
|
447
|
}
|
448
|
|
449
|
/**
|
450
|
* Destructs the DrupalCacheArray object.
|
451
|
*/
|
452
|
public function __destruct() {
|
453
|
$data = array();
|
454
|
foreach ($this->keysToPersist as $offset => $persist) {
|
455
|
if ($persist) {
|
456
|
$data[$offset] = $this->storage[$offset];
|
457
|
}
|
458
|
}
|
459
|
if (!empty($data)) {
|
460
|
$this->set($data);
|
461
|
}
|
462
|
}
|
463
|
}
|
464
|
|
465
|
/**
|
466
|
* Starts the timer with the specified name.
|
467
|
*
|
468
|
* If you start and stop the same timer multiple times, the measured intervals
|
469
|
* will be accumulated.
|
470
|
*
|
471
|
* @param $name
|
472
|
* The name of the timer.
|
473
|
*/
|
474
|
function timer_start($name) {
|
475
|
global $timers;
|
476
|
|
477
|
$timers[$name]['start'] = microtime(TRUE);
|
478
|
$timers[$name]['count'] = isset($timers[$name]['count']) ? ++$timers[$name]['count'] : 1;
|
479
|
}
|
480
|
|
481
|
/**
|
482
|
* Reads the current timer value without stopping the timer.
|
483
|
*
|
484
|
* @param $name
|
485
|
* The name of the timer.
|
486
|
*
|
487
|
* @return
|
488
|
* The current timer value in ms.
|
489
|
*/
|
490
|
function timer_read($name) {
|
491
|
global $timers;
|
492
|
|
493
|
if (isset($timers[$name]['start'])) {
|
494
|
$stop = microtime(TRUE);
|
495
|
$diff = round(($stop - $timers[$name]['start']) * 1000, 2);
|
496
|
|
497
|
if (isset($timers[$name]['time'])) {
|
498
|
$diff += $timers[$name]['time'];
|
499
|
}
|
500
|
return $diff;
|
501
|
}
|
502
|
return $timers[$name]['time'];
|
503
|
}
|
504
|
|
505
|
/**
|
506
|
* Stops the timer with the specified name.
|
507
|
*
|
508
|
* @param $name
|
509
|
* The name of the timer.
|
510
|
*
|
511
|
* @return
|
512
|
* A timer array. The array contains the number of times the timer has been
|
513
|
* started and stopped (count) and the accumulated timer value in ms (time).
|
514
|
*/
|
515
|
function timer_stop($name) {
|
516
|
global $timers;
|
517
|
|
518
|
if (isset($timers[$name]['start'])) {
|
519
|
$stop = microtime(TRUE);
|
520
|
$diff = round(($stop - $timers[$name]['start']) * 1000, 2);
|
521
|
if (isset($timers[$name]['time'])) {
|
522
|
$timers[$name]['time'] += $diff;
|
523
|
}
|
524
|
else {
|
525
|
$timers[$name]['time'] = $diff;
|
526
|
}
|
527
|
unset($timers[$name]['start']);
|
528
|
}
|
529
|
|
530
|
return $timers[$name];
|
531
|
}
|
532
|
|
533
|
/**
|
534
|
* Returns the appropriate configuration directory.
|
535
|
*
|
536
|
* Returns the configuration path based on the site's hostname, port, and
|
537
|
* pathname. See default.settings.php for examples on how the URL is converted
|
538
|
* to a directory.
|
539
|
*
|
540
|
* @param bool $require_settings
|
541
|
* Only configuration directories with an existing settings.php file
|
542
|
* will be recognized. Defaults to TRUE. During initial installation,
|
543
|
* this is set to FALSE so that Drupal can detect a matching directory,
|
544
|
* then create a new settings.php file in it.
|
545
|
* @param bool $reset
|
546
|
* Force a full search for matching directories even if one had been
|
547
|
* found previously. Defaults to FALSE.
|
548
|
*
|
549
|
* @return
|
550
|
* The path of the matching directory.
|
551
|
*
|
552
|
* @see default.settings.php
|
553
|
*/
|
554
|
function conf_path($require_settings = TRUE, $reset = FALSE) {
|
555
|
$conf = &drupal_static(__FUNCTION__, '');
|
556
|
|
557
|
if ($conf && !$reset) {
|
558
|
return $conf;
|
559
|
}
|
560
|
|
561
|
$confdir = 'sites';
|
562
|
|
563
|
$sites = array();
|
564
|
if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/sites.php')) {
|
565
|
// This will overwrite $sites with the desired mappings.
|
566
|
include(DRUPAL_ROOT . '/' . $confdir . '/sites.php');
|
567
|
}
|
568
|
|
569
|
$uri = explode('/', $_SERVER['SCRIPT_NAME'] ? $_SERVER['SCRIPT_NAME'] : $_SERVER['SCRIPT_FILENAME']);
|
570
|
$server = explode('.', implode('.', array_reverse(explode(':', rtrim($_SERVER['HTTP_HOST'], '.')))));
|
571
|
for ($i = count($uri) - 1; $i > 0; $i--) {
|
572
|
for ($j = count($server); $j > 0; $j--) {
|
573
|
$dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
|
574
|
if (isset($sites[$dir]) && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $sites[$dir])) {
|
575
|
$dir = $sites[$dir];
|
576
|
}
|
577
|
if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir . '/settings.php') || (!$require_settings && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir))) {
|
578
|
$conf = "$confdir/$dir";
|
579
|
return $conf;
|
580
|
}
|
581
|
}
|
582
|
}
|
583
|
$conf = "$confdir/default";
|
584
|
return $conf;
|
585
|
}
|
586
|
|
587
|
/**
|
588
|
* Sets appropriate server variables needed for command line scripts to work.
|
589
|
*
|
590
|
* This function can be called by command line scripts before bootstrapping
|
591
|
* Drupal, to ensure that the page loads with the desired server parameters.
|
592
|
* This is because many parts of Drupal assume that they are running in a web
|
593
|
* browser and therefore use information from the global PHP $_SERVER variable
|
594
|
* that does not get set when Drupal is run from the command line.
|
595
|
*
|
596
|
* In many cases, the default way in which this function populates the $_SERVER
|
597
|
* variable is sufficient, and it can therefore be called without passing in
|
598
|
* any input. However, command line scripts running on a multisite installation
|
599
|
* (or on any installation that has settings.php stored somewhere other than
|
600
|
* the sites/default folder) need to pass in the URL of the site to allow
|
601
|
* Drupal to detect the correct location of the settings.php file. Passing in
|
602
|
* the 'url' parameter is also required for functions like request_uri() to
|
603
|
* return the expected values.
|
604
|
*
|
605
|
* Most other parameters do not need to be passed in, but may be necessary in
|
606
|
* some cases; for example, if Drupal's ip_address() function needs to return
|
607
|
* anything but the standard localhost value ('127.0.0.1'), the command line
|
608
|
* script should pass in the desired value via the 'REMOTE_ADDR' key.
|
609
|
*
|
610
|
* @param $variables
|
611
|
* (optional) An associative array of variables within $_SERVER that should
|
612
|
* be replaced. If the special element 'url' is provided in this array, it
|
613
|
* will be used to populate some of the server defaults; it should be set to
|
614
|
* the URL of the current page request, excluding any $_GET request but
|
615
|
* including the script name (e.g., http://www.example.com/mysite/index.php).
|
616
|
*
|
617
|
* @see conf_path()
|
618
|
* @see request_uri()
|
619
|
* @see ip_address()
|
620
|
*/
|
621
|
function drupal_override_server_variables($variables = array()) {
|
622
|
// Allow the provided URL to override any existing values in $_SERVER.
|
623
|
if (isset($variables['url'])) {
|
624
|
$url = parse_url($variables['url']);
|
625
|
if (isset($url['host'])) {
|
626
|
$_SERVER['HTTP_HOST'] = $url['host'];
|
627
|
}
|
628
|
if (isset($url['path'])) {
|
629
|
$_SERVER['SCRIPT_NAME'] = $url['path'];
|
630
|
}
|
631
|
unset($variables['url']);
|
632
|
}
|
633
|
// Define default values for $_SERVER keys. These will be used if $_SERVER
|
634
|
// does not already define them and no other values are passed in to this
|
635
|
// function.
|
636
|
$defaults = array(
|
637
|
'HTTP_HOST' => 'localhost',
|
638
|
'SCRIPT_NAME' => NULL,
|
639
|
'REMOTE_ADDR' => '127.0.0.1',
|
640
|
'REQUEST_METHOD' => 'GET',
|
641
|
'SERVER_NAME' => NULL,
|
642
|
'SERVER_SOFTWARE' => NULL,
|
643
|
'HTTP_USER_AGENT' => NULL,
|
644
|
);
|
645
|
// Replace elements of the $_SERVER array, as appropriate.
|
646
|
$_SERVER = $variables + $_SERVER + $defaults;
|
647
|
}
|
648
|
|
649
|
/**
|
650
|
* Initializes the PHP environment.
|
651
|
*/
|
652
|
function drupal_environment_initialize() {
|
653
|
if (!isset($_SERVER['HTTP_REFERER'])) {
|
654
|
$_SERVER['HTTP_REFERER'] = '';
|
655
|
}
|
656
|
if (!isset($_SERVER['SERVER_PROTOCOL']) || ($_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.0' && $_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.1')) {
|
657
|
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
|
658
|
}
|
659
|
|
660
|
if (isset($_SERVER['HTTP_HOST'])) {
|
661
|
// As HTTP_HOST is user input, ensure it only contains characters allowed
|
662
|
// in hostnames. See RFC 952 (and RFC 2181).
|
663
|
// $_SERVER['HTTP_HOST'] is lowercased here per specifications.
|
664
|
$_SERVER['HTTP_HOST'] = strtolower($_SERVER['HTTP_HOST']);
|
665
|
if (!drupal_valid_http_host($_SERVER['HTTP_HOST'])) {
|
666
|
// HTTP_HOST is invalid, e.g. if containing slashes it may be an attack.
|
667
|
header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
|
668
|
exit;
|
669
|
}
|
670
|
}
|
671
|
else {
|
672
|
// Some pre-HTTP/1.1 clients will not send a Host header. Ensure the key is
|
673
|
// defined for E_ALL compliance.
|
674
|
$_SERVER['HTTP_HOST'] = '';
|
675
|
}
|
676
|
|
677
|
// When clean URLs are enabled, emulate ?q=foo/bar using REQUEST_URI. It is
|
678
|
// not possible to append the query string using mod_rewrite without the B
|
679
|
// flag (this was added in Apache 2.2.8), because mod_rewrite unescapes the
|
680
|
// path before passing it on to PHP. This is a problem when the path contains
|
681
|
// e.g. "&" or "%" that have special meanings in URLs and must be encoded.
|
682
|
$_GET['q'] = request_path();
|
683
|
|
684
|
// Enforce E_ALL, but allow users to set levels not part of E_ALL.
|
685
|
error_reporting(E_ALL | error_reporting());
|
686
|
|
687
|
// Override PHP settings required for Drupal to work properly.
|
688
|
// sites/default/default.settings.php contains more runtime settings.
|
689
|
// The .htaccess file contains settings that cannot be changed at runtime.
|
690
|
|
691
|
// Don't escape quotes when reading files from the database, disk, etc.
|
692
|
ini_set('magic_quotes_runtime', '0');
|
693
|
// Use session cookies, not transparent sessions that puts the session id in
|
694
|
// the query string.
|
695
|
ini_set('session.use_cookies', '1');
|
696
|
ini_set('session.use_only_cookies', '1');
|
697
|
ini_set('session.use_trans_sid', '0');
|
698
|
// Don't send HTTP headers using PHP's session handler.
|
699
|
// An empty string is used here to disable the cache limiter.
|
700
|
ini_set('session.cache_limiter', '');
|
701
|
// Use httponly session cookies.
|
702
|
ini_set('session.cookie_httponly', '1');
|
703
|
|
704
|
// Set sane locale settings, to ensure consistent string, dates, times and
|
705
|
// numbers handling.
|
706
|
setlocale(LC_ALL, 'C');
|
707
|
|
708
|
// PHP's built-in phar:// stream wrapper is not sufficiently secure. Override
|
709
|
// it with a more secure one, which requires PHP 5.3.3. For lower versions,
|
710
|
// unregister the built-in one without replacing it. Sites needing phar
|
711
|
// support for lower PHP versions must implement hook_stream_wrappers() to
|
712
|
// register their desired implementation.
|
713
|
if (in_array('phar', stream_get_wrappers(), TRUE)) {
|
714
|
stream_wrapper_unregister('phar');
|
715
|
if (version_compare(PHP_VERSION, '5.3.3', '>=')) {
|
716
|
include_once DRUPAL_ROOT . '/includes/file.phar.inc';
|
717
|
file_register_phar_wrapper();
|
718
|
}
|
719
|
}
|
720
|
}
|
721
|
|
722
|
/**
|
723
|
* Validates that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
|
724
|
*
|
725
|
* @return
|
726
|
* TRUE if only containing valid characters, or FALSE otherwise.
|
727
|
*/
|
728
|
function drupal_valid_http_host($host) {
|
729
|
// Limit the length of the host name to 1000 bytes to prevent DoS attacks with
|
730
|
// long host names.
|
731
|
return strlen($host) <= 1000
|
732
|
// Limit the number of subdomains and port separators to prevent DoS attacks
|
733
|
// in conf_path().
|
734
|
&& substr_count($host, '.') <= 100
|
735
|
&& substr_count($host, ':') <= 100
|
736
|
&& preg_match('/^\[?(?:[a-zA-Z0-9-:\]_]+\.?)+$/', $host);
|
737
|
}
|
738
|
|
739
|
/**
|
740
|
* Checks whether an HTTPS request is being served.
|
741
|
*
|
742
|
* @return bool
|
743
|
* TRUE if the request is HTTPS, FALSE otherwise.
|
744
|
*/
|
745
|
function drupal_is_https() {
|
746
|
return isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';
|
747
|
}
|
748
|
|
749
|
/**
|
750
|
* Sets the base URL, cookie domain, and session name from configuration.
|
751
|
*/
|
752
|
function drupal_settings_initialize() {
|
753
|
global $base_url, $base_path, $base_root;
|
754
|
|
755
|
// Export these settings.php variables to the global namespace.
|
756
|
global $databases, $cookie_domain, $conf, $installed_profile, $update_free_access, $db_url, $db_prefix, $drupal_hash_salt, $is_https, $base_secure_url, $base_insecure_url;
|
757
|
$conf = array();
|
758
|
|
759
|
if (file_exists(DRUPAL_ROOT . '/' . conf_path() . '/settings.php')) {
|
760
|
include_once DRUPAL_ROOT . '/' . conf_path() . '/settings.php';
|
761
|
}
|
762
|
$is_https = drupal_is_https();
|
763
|
|
764
|
if (isset($base_url)) {
|
765
|
// Parse fixed base URL from settings.php.
|
766
|
$parts = parse_url($base_url);
|
767
|
if (!isset($parts['path'])) {
|
768
|
$parts['path'] = '';
|
769
|
}
|
770
|
$base_path = $parts['path'] . '/';
|
771
|
// Build $base_root (everything until first slash after "scheme://").
|
772
|
$base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
|
773
|
}
|
774
|
else {
|
775
|
// Create base URL.
|
776
|
$http_protocol = $is_https ? 'https' : 'http';
|
777
|
$base_root = $http_protocol . '://' . $_SERVER['HTTP_HOST'];
|
778
|
|
779
|
$base_url = $base_root;
|
780
|
|
781
|
// $_SERVER['SCRIPT_NAME'] can, in contrast to $_SERVER['PHP_SELF'], not
|
782
|
// be modified by a visitor.
|
783
|
if ($dir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/')) {
|
784
|
$base_path = $dir;
|
785
|
$base_url .= $base_path;
|
786
|
$base_path .= '/';
|
787
|
}
|
788
|
else {
|
789
|
$base_path = '/';
|
790
|
}
|
791
|
}
|
792
|
$base_secure_url = str_replace('http://', 'https://', $base_url);
|
793
|
$base_insecure_url = str_replace('https://', 'http://', $base_url);
|
794
|
|
795
|
if ($cookie_domain) {
|
796
|
// If the user specifies the cookie domain, also use it for session name.
|
797
|
$session_name = $cookie_domain;
|
798
|
}
|
799
|
else {
|
800
|
// Otherwise use $base_url as session name, without the protocol
|
801
|
// to use the same session identifiers across HTTP and HTTPS.
|
802
|
list( , $session_name) = explode('://', $base_url, 2);
|
803
|
// HTTP_HOST can be modified by a visitor, but we already sanitized it
|
804
|
// in drupal_settings_initialize().
|
805
|
if (!empty($_SERVER['HTTP_HOST'])) {
|
806
|
$cookie_domain = $_SERVER['HTTP_HOST'];
|
807
|
// Strip leading periods, www., and port numbers from cookie domain.
|
808
|
$cookie_domain = ltrim($cookie_domain, '.');
|
809
|
if (strpos($cookie_domain, 'www.') === 0) {
|
810
|
$cookie_domain = substr($cookie_domain, 4);
|
811
|
}
|
812
|
$cookie_domain = explode(':', $cookie_domain);
|
813
|
$cookie_domain = '.' . $cookie_domain[0];
|
814
|
}
|
815
|
}
|
816
|
// Per RFC 2109, cookie domains must contain at least one dot other than the
|
817
|
// first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
|
818
|
if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
|
819
|
ini_set('session.cookie_domain', $cookie_domain);
|
820
|
}
|
821
|
// To prevent session cookies from being hijacked, a user can configure the
|
822
|
// SSL version of their website to only transfer session cookies via SSL by
|
823
|
// using PHP's session.cookie_secure setting. The browser will then use two
|
824
|
// separate session cookies for the HTTPS and HTTP versions of the site. So we
|
825
|
// must use different session identifiers for HTTPS and HTTP to prevent a
|
826
|
// cookie collision.
|
827
|
if ($is_https) {
|
828
|
ini_set('session.cookie_secure', TRUE);
|
829
|
}
|
830
|
$prefix = ini_get('session.cookie_secure') ? 'SSESS' : 'SESS';
|
831
|
session_name($prefix . substr(hash('sha256', $session_name), 0, 32));
|
832
|
}
|
833
|
|
834
|
/**
|
835
|
* Returns and optionally sets the filename for a system resource.
|
836
|
*
|
837
|
* The filename, whether provided, cached, or retrieved from the database, is
|
838
|
* only returned if the file exists.
|
839
|
*
|
840
|
* This function plays a key role in allowing Drupal's resources (modules
|
841
|
* and themes) to be located in different places depending on a site's
|
842
|
* configuration. For example, a module 'foo' may legally be located
|
843
|
* in any of these three places:
|
844
|
*
|
845
|
* modules/foo/foo.module
|
846
|
* sites/all/modules/foo/foo.module
|
847
|
* sites/example.com/modules/foo/foo.module
|
848
|
*
|
849
|
* Calling drupal_get_filename('module', 'foo') will give you one of
|
850
|
* the above, depending on where the module is located.
|
851
|
*
|
852
|
* @param $type
|
853
|
* The type of the item (theme, theme_engine, module, profile).
|
854
|
* @param $name
|
855
|
* The name of the item for which the filename is requested.
|
856
|
* @param $filename
|
857
|
* The filename of the item if it is to be set explicitly rather
|
858
|
* than by consulting the database.
|
859
|
* @param bool $trigger_error
|
860
|
* Whether to trigger an error when a file is missing or has unexpectedly
|
861
|
* moved. This defaults to TRUE, but can be set to FALSE by calling code that
|
862
|
* merely wants to check whether an item exists in the filesystem.
|
863
|
*
|
864
|
* @return
|
865
|
* The filename of the requested item or NULL if the item is not found.
|
866
|
*/
|
867
|
function drupal_get_filename($type, $name, $filename = NULL, $trigger_error = TRUE) {
|
868
|
// The $files static variable will hold the locations of all requested files.
|
869
|
// We can be sure that any file listed in this static variable actually
|
870
|
// exists as all additions have gone through a file_exists() check.
|
871
|
// The location of files will not change during the request, so do not use
|
872
|
// drupal_static().
|
873
|
static $files = array();
|
874
|
|
875
|
// Profiles are a special case: they have a fixed location and naming.
|
876
|
if ($type == 'profile') {
|
877
|
$profile_filename = "profiles/$name/$name.profile";
|
878
|
$files[$type][$name] = file_exists($profile_filename) ? $profile_filename : FALSE;
|
879
|
}
|
880
|
if (!isset($files[$type])) {
|
881
|
$files[$type] = array();
|
882
|
}
|
883
|
|
884
|
if (!empty($filename) && file_exists($filename)) {
|
885
|
// Prime the static cache with the provided filename.
|
886
|
$files[$type][$name] = $filename;
|
887
|
}
|
888
|
elseif (isset($files[$type][$name])) {
|
889
|
// This item had already been found earlier in the request, either through
|
890
|
// priming of the static cache (for example, in system_list()), through a
|
891
|
// lookup in the {system} table, or through a file scan (cached or not). Do
|
892
|
// nothing.
|
893
|
}
|
894
|
else {
|
895
|
// Look for the filename listed in the {system} table. Verify that we have
|
896
|
// an active database connection before doing so, since this function is
|
897
|
// called both before we have a database connection (i.e. during
|
898
|
// installation) and when a database connection fails.
|
899
|
$database_unavailable = TRUE;
|
900
|
try {
|
901
|
if (function_exists('db_query')) {
|
902
|
$file = db_query("SELECT filename FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
|
903
|
if ($file !== FALSE && file_exists(DRUPAL_ROOT . '/' . $file)) {
|
904
|
$files[$type][$name] = $file;
|
905
|
}
|
906
|
$database_unavailable = FALSE;
|
907
|
}
|
908
|
}
|
909
|
catch (Exception $e) {
|
910
|
// The database table may not exist because Drupal is not yet installed,
|
911
|
// the database might be down, or we may have done a non-database cache
|
912
|
// flush while $conf['page_cache_without_database'] = TRUE and
|
913
|
// $conf['page_cache_invoke_hooks'] = TRUE. We have a fallback for these
|
914
|
// cases so we hide the error completely.
|
915
|
}
|
916
|
// Fall back to searching the filesystem if the database could not find the
|
917
|
// file or the file does not exist at the path returned by the database.
|
918
|
if (!isset($files[$type][$name])) {
|
919
|
$files[$type][$name] = _drupal_get_filename_fallback($type, $name, $trigger_error, $database_unavailable);
|
920
|
}
|
921
|
}
|
922
|
|
923
|
if (isset($files[$type][$name])) {
|
924
|
return $files[$type][$name];
|
925
|
}
|
926
|
}
|
927
|
|
928
|
/**
|
929
|
* Performs a cached file system scan as a fallback when searching for a file.
|
930
|
*
|
931
|
* This function looks for the requested file by triggering a file scan,
|
932
|
* caching the new location if the file has moved and caching the miss
|
933
|
* if the file is missing. If a file had been marked as missing in a previous
|
934
|
* file scan, or if it has been marked as moved and is still in the last known
|
935
|
* location, no new file scan will be performed.
|
936
|
*
|
937
|
* @param string $type
|
938
|
* The type of the item (theme, theme_engine, module, profile).
|
939
|
* @param string $name
|
940
|
* The name of the item for which the filename is requested.
|
941
|
* @param bool $trigger_error
|
942
|
* Whether to trigger an error when a file is missing or has unexpectedly
|
943
|
* moved.
|
944
|
* @param bool $database_unavailable
|
945
|
* Whether this function is being called because the Drupal database could
|
946
|
* not be queried for the file's location.
|
947
|
*
|
948
|
* @return
|
949
|
* The filename of the requested item or NULL if the item is not found.
|
950
|
*
|
951
|
* @see drupal_get_filename()
|
952
|
*/
|
953
|
function _drupal_get_filename_fallback($type, $name, $trigger_error, $database_unavailable) {
|
954
|
$file_scans = &_drupal_file_scan_cache();
|
955
|
$filename = NULL;
|
956
|
|
957
|
// If the cache indicates that the item is missing, or we can verify that the
|
958
|
// item exists in the location the cache says it exists in, use that.
|
959
|
if (isset($file_scans[$type][$name]) && ($file_scans[$type][$name] === FALSE || file_exists($file_scans[$type][$name]))) {
|
960
|
$filename = $file_scans[$type][$name];
|
961
|
}
|
962
|
// Otherwise, perform a new file scan to find the item.
|
963
|
else {
|
964
|
$filename = _drupal_get_filename_perform_file_scan($type, $name);
|
965
|
// Update the static cache, and mark the persistent cache for updating at
|
966
|
// the end of the page request. See drupal_file_scan_write_cache().
|
967
|
$file_scans[$type][$name] = $filename;
|
968
|
$file_scans['#write_cache'] = TRUE;
|
969
|
}
|
970
|
|
971
|
// If requested, trigger a user-level warning about the missing or
|
972
|
// unexpectedly moved file. If the database was unavailable, do not trigger a
|
973
|
// warning in the latter case, though, since if the {system} table could not
|
974
|
// be queried there is no way to know if the location found here was
|
975
|
// "unexpected" or not.
|
976
|
if ($trigger_error) {
|
977
|
$error_type = $filename === FALSE ? 'missing' : 'moved';
|
978
|
if ($error_type == 'missing' || !$database_unavailable) {
|
979
|
_drupal_get_filename_fallback_trigger_error($type, $name, $error_type);
|
980
|
}
|
981
|
}
|
982
|
|
983
|
// The cache stores FALSE for files that aren't found (to be able to
|
984
|
// distinguish them from files that have not yet been searched for), but
|
985
|
// drupal_get_filename() expects NULL for these instead, so convert to NULL
|
986
|
// before returning.
|
987
|
if ($filename === FALSE) {
|
988
|
$filename = NULL;
|
989
|
}
|
990
|
return $filename;
|
991
|
}
|
992
|
|
993
|
/**
|
994
|
* Returns the current list of cached file system scan results.
|
995
|
*
|
996
|
* @return
|
997
|
* An associative array tracking the most recent file scan results for all
|
998
|
* files that have had scans performed. The keys are the type and name of the
|
999
|
* item that was searched for, and the values can be either:
|
1000
|
* - Boolean FALSE if the item was not found in the file system.
|
1001
|
* - A string pointing to the location where the item was found.
|
1002
|
*/
|
1003
|
function &_drupal_file_scan_cache() {
|
1004
|
$file_scans = &drupal_static(__FUNCTION__, array());
|
1005
|
|
1006
|
// The file scan results are stored in a persistent cache (in addition to the
|
1007
|
// static cache) but because this function can be called before the
|
1008
|
// persistent cache is available, we must merge any items that were found
|
1009
|
// earlier in the page request into the results from the persistent cache.
|
1010
|
if (!isset($file_scans['#cache_merge_done'])) {
|
1011
|
try {
|
1012
|
if (function_exists('cache_get')) {
|
1013
|
$cache = cache_get('_drupal_file_scan_cache', 'cache_bootstrap');
|
1014
|
if (!empty($cache->data)) {
|
1015
|
// File scan results from the current request should take precedence
|
1016
|
// over the results from the persistent cache, since they are newer.
|
1017
|
$file_scans = drupal_array_merge_deep($cache->data, $file_scans);
|
1018
|
}
|
1019
|
// Set a flag to indicate that the persistent cache does not need to be
|
1020
|
// merged again.
|
1021
|
$file_scans['#cache_merge_done'] = TRUE;
|
1022
|
}
|
1023
|
}
|
1024
|
catch (Exception $e) {
|
1025
|
// Hide the error.
|
1026
|
}
|
1027
|
}
|
1028
|
|
1029
|
return $file_scans;
|
1030
|
}
|
1031
|
|
1032
|
/**
|
1033
|
* Performs a file system scan to search for a system resource.
|
1034
|
*
|
1035
|
* @param $type
|
1036
|
* The type of the item (theme, theme_engine, module, profile).
|
1037
|
* @param $name
|
1038
|
* The name of the item for which the filename is requested.
|
1039
|
*
|
1040
|
* @return
|
1041
|
* The filename of the requested item or FALSE if the item is not found.
|
1042
|
*
|
1043
|
* @see drupal_get_filename()
|
1044
|
* @see _drupal_get_filename_fallback()
|
1045
|
*/
|
1046
|
function _drupal_get_filename_perform_file_scan($type, $name) {
|
1047
|
// The location of files will not change during the request, so do not use
|
1048
|
// drupal_static().
|
1049
|
static $dirs = array(), $files = array();
|
1050
|
|
1051
|
// We have a consistent directory naming: modules, themes...
|
1052
|
$dir = $type . 's';
|
1053
|
if ($type == 'theme_engine') {
|
1054
|
$dir = 'themes/engines';
|
1055
|
$extension = 'engine';
|
1056
|
}
|
1057
|
elseif ($type == 'theme') {
|
1058
|
$extension = 'info';
|
1059
|
}
|
1060
|
else {
|
1061
|
$extension = $type;
|
1062
|
}
|
1063
|
|
1064
|
// Check if we had already scanned this directory/extension combination.
|
1065
|
if (!isset($dirs[$dir][$extension])) {
|
1066
|
// Log that we have now scanned this directory/extension combination
|
1067
|
// into a static variable so as to prevent unnecessary file scans.
|
1068
|
$dirs[$dir][$extension] = TRUE;
|
1069
|
if (!function_exists('drupal_system_listing')) {
|
1070
|
require_once DRUPAL_ROOT . '/includes/common.inc';
|
1071
|
}
|
1072
|
// Scan the appropriate directories for all files with the requested
|
1073
|
// extension, not just the file we are currently looking for. This
|
1074
|
// prevents unnecessary scans from being repeated when this function is
|
1075
|
// called more than once in the same page request.
|
1076
|
$matches = drupal_system_listing("/^" . DRUPAL_PHP_FUNCTION_PATTERN . "\.$extension$/", $dir, 'name', 0);
|
1077
|
foreach ($matches as $matched_name => $file) {
|
1078
|
// Log the locations found in the file scan into a static variable.
|
1079
|
$files[$type][$matched_name] = $file->uri;
|
1080
|
}
|
1081
|
}
|
1082
|
|
1083
|
// Return the results of the file system scan, or FALSE to indicate the file
|
1084
|
// was not found.
|
1085
|
return isset($files[$type][$name]) ? $files[$type][$name] : FALSE;
|
1086
|
}
|
1087
|
|
1088
|
/**
|
1089
|
* Triggers a user-level warning for missing or unexpectedly moved files.
|
1090
|
*
|
1091
|
* @param $type
|
1092
|
* The type of the item (theme, theme_engine, module, profile).
|
1093
|
* @param $name
|
1094
|
* The name of the item for which the filename is requested.
|
1095
|
* @param $error_type
|
1096
|
* The type of the error ('missing' or 'moved').
|
1097
|
*
|
1098
|
* @see drupal_get_filename()
|
1099
|
* @see _drupal_get_filename_fallback()
|
1100
|
*/
|
1101
|
function _drupal_get_filename_fallback_trigger_error($type, $name, $error_type) {
|
1102
|
// Hide messages due to known bugs that will appear on a lot of sites.
|
1103
|
// @todo Remove this in https://www.drupal.org/node/2383823
|
1104
|
if (empty($name)) {
|
1105
|
return;
|
1106
|
}
|
1107
|
|
1108
|
// Make sure we only show any missing or moved file errors only once per
|
1109
|
// request.
|
1110
|
static $errors_triggered = array();
|
1111
|
if (empty($errors_triggered[$type][$name][$error_type])) {
|
1112
|
// Use _drupal_trigger_error_with_delayed_logging() here since these are
|
1113
|
// triggered during low-level operations that cannot necessarily be
|
1114
|
// interrupted by a watchdog() call.
|
1115
|
if ($error_type == 'missing') {
|
1116
|
_drupal_trigger_error_with_delayed_logging(format_string('The following @type is missing from the file system: %name. For information about how to fix this, see <a href="@documentation">the documentation page</a>.', array('@type' => $type, '%name' => $name, '@documentation' => 'https://www.drupal.org/node/2487215')), E_USER_WARNING);
|
1117
|
}
|
1118
|
elseif ($error_type == 'moved') {
|
1119
|
_drupal_trigger_error_with_delayed_logging(format_string('The following @type has moved within the file system: %name. In order to fix this, clear caches or put the @type back in its original location. For more information, see <a href="@documentation">the documentation page</a>.', array('@type' => $type, '%name' => $name, '@documentation' => 'https://www.drupal.org/node/2487215')), E_USER_WARNING);
|
1120
|
}
|
1121
|
$errors_triggered[$type][$name][$error_type] = TRUE;
|
1122
|
}
|
1123
|
}
|
1124
|
|
1125
|
/**
|
1126
|
* Invokes trigger_error() with logging delayed until the end of the request.
|
1127
|
*
|
1128
|
* This is an alternative to PHP's trigger_error() function which can be used
|
1129
|
* during low-level Drupal core operations that need to avoid being interrupted
|
1130
|
* by a watchdog() call.
|
1131
|
*
|
1132
|
* Normally, Drupal's error handler calls watchdog() in response to a
|
1133
|
* trigger_error() call. However, this invokes hook_watchdog() which can run
|
1134
|
* arbitrary code. If the trigger_error() happens in the middle of an
|
1135
|
* operation such as a rebuild operation which should not be interrupted by
|
1136
|
* arbitrary code, that could potentially break or trigger the rebuild again.
|
1137
|
* This function protects against that by delaying the watchdog() call until
|
1138
|
* the end of the current page request.
|
1139
|
*
|
1140
|
* This is an internal function which should only be called by low-level Drupal
|
1141
|
* core functions. It may be removed in a future Drupal 7 release.
|
1142
|
*
|
1143
|
* @param string $error_msg
|
1144
|
* The error message to trigger. As with trigger_error() itself, this is
|
1145
|
* limited to 1024 bytes; additional characters beyond that will be removed.
|
1146
|
* @param int $error_type
|
1147
|
* (optional) The type of error. This should be one of the E_USER family of
|
1148
|
* constants. As with trigger_error() itself, this defaults to E_USER_NOTICE
|
1149
|
* if not provided.
|
1150
|
*
|
1151
|
* @see _drupal_log_error()
|
1152
|
*/
|
1153
|
function _drupal_trigger_error_with_delayed_logging($error_msg, $error_type = E_USER_NOTICE) {
|
1154
|
$delay_logging = &drupal_static(__FUNCTION__, FALSE);
|
1155
|
$delay_logging = TRUE;
|
1156
|
trigger_error($error_msg, $error_type);
|
1157
|
$delay_logging = FALSE;
|
1158
|
}
|
1159
|
|
1160
|
/**
|
1161
|
* Writes the file scan cache to the persistent cache.
|
1162
|
*
|
1163
|
* This cache stores all files marked as missing or moved after a file scan
|
1164
|
* to prevent unnecessary file scans in subsequent requests. This cache is
|
1165
|
* cleared in system_list_reset() (i.e. after a module/theme rebuild).
|
1166
|
*/
|
1167
|
function drupal_file_scan_write_cache() {
|
1168
|
// Only write to the persistent cache if requested, and if we know that any
|
1169
|
// data previously in the cache was successfully loaded and merged in by
|
1170
|
// _drupal_file_scan_cache().
|
1171
|
$file_scans = &_drupal_file_scan_cache();
|
1172
|
if (isset($file_scans['#write_cache']) && isset($file_scans['#cache_merge_done'])) {
|
1173
|
unset($file_scans['#write_cache']);
|
1174
|
cache_set('_drupal_file_scan_cache', $file_scans, 'cache_bootstrap');
|
1175
|
}
|
1176
|
}
|
1177
|
|
1178
|
/**
|
1179
|
* Loads the persistent variable table.
|
1180
|
*
|
1181
|
* The variable table is composed of values that have been saved in the table
|
1182
|
* with variable_set() as well as those explicitly specified in the
|
1183
|
* configuration file.
|
1184
|
*/
|
1185
|
function variable_initialize($conf = array()) {
|
1186
|
// NOTE: caching the variables improves performance by 20% when serving
|
1187
|
// cached pages.
|
1188
|
if ($cached = cache_get('variables', 'cache_bootstrap')) {
|
1189
|
$variables = $cached->data;
|
1190
|
}
|
1191
|
else {
|
1192
|
// Cache miss. Avoid a stampede.
|
1193
|
$name = 'variable_init';
|
1194
|
if (!lock_acquire($name, 1)) {
|
1195
|
// Another request is building the variable cache.
|
1196
|
// Wait, then re-run this function.
|
1197
|
lock_wait($name);
|
1198
|
return variable_initialize($conf);
|
1199
|
}
|
1200
|
else {
|
1201
|
// Proceed with variable rebuild.
|
1202
|
$variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
|
1203
|
cache_set('variables', $variables, 'cache_bootstrap');
|
1204
|
lock_release($name);
|
1205
|
}
|
1206
|
}
|
1207
|
|
1208
|
foreach ($conf as $name => $value) {
|
1209
|
$variables[$name] = $value;
|
1210
|
}
|
1211
|
|
1212
|
return $variables;
|
1213
|
}
|
1214
|
|
1215
|
/**
|
1216
|
* Returns a persistent variable.
|
1217
|
*
|
1218
|
* Case-sensitivity of the variable_* functions depends on the database
|
1219
|
* collation used. To avoid problems, always use lower case for persistent
|
1220
|
* variable names.
|
1221
|
*
|
1222
|
* @param $name
|
1223
|
* The name of the variable to return.
|
1224
|
* @param $default
|
1225
|
* The default value to use if this variable has never been set.
|
1226
|
*
|
1227
|
* @return
|
1228
|
* The value of the variable. Unserialization is taken care of as necessary.
|
1229
|
*
|
1230
|
* @see variable_del()
|
1231
|
* @see variable_set()
|
1232
|
*/
|
1233
|
function variable_get($name, $default = NULL) {
|
1234
|
global $conf;
|
1235
|
|
1236
|
return isset($conf[$name]) ? $conf[$name] : $default;
|
1237
|
}
|
1238
|
|
1239
|
/**
|
1240
|
* Sets a persistent variable.
|
1241
|
*
|
1242
|
* Case-sensitivity of the variable_* functions depends on the database
|
1243
|
* collation used. To avoid problems, always use lower case for persistent
|
1244
|
* variable names.
|
1245
|
*
|
1246
|
* @param $name
|
1247
|
* The name of the variable to set.
|
1248
|
* @param $value
|
1249
|
* The value to set. This can be any PHP data type; these functions take care
|
1250
|
* of serialization as necessary.
|
1251
|
*
|
1252
|
* @see variable_del()
|
1253
|
* @see variable_get()
|
1254
|
*/
|
1255
|
function variable_set($name, $value) {
|
1256
|
global $conf;
|
1257
|
|
1258
|
db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();
|
1259
|
|
1260
|
cache_clear_all('variables', 'cache_bootstrap');
|
1261
|
|
1262
|
$conf[$name] = $value;
|
1263
|
}
|
1264
|
|
1265
|
/**
|
1266
|
* Unsets a persistent variable.
|
1267
|
*
|
1268
|
* Case-sensitivity of the variable_* functions depends on the database
|
1269
|
* collation used. To avoid problems, always use lower case for persistent
|
1270
|
* variable names.
|
1271
|
*
|
1272
|
* @param $name
|
1273
|
* The name of the variable to undefine.
|
1274
|
*
|
1275
|
* @see variable_get()
|
1276
|
* @see variable_set()
|
1277
|
*/
|
1278
|
function variable_del($name) {
|
1279
|
global $conf;
|
1280
|
|
1281
|
db_delete('variable')
|
1282
|
->condition('name', $name)
|
1283
|
->execute();
|
1284
|
cache_clear_all('variables', 'cache_bootstrap');
|
1285
|
|
1286
|
unset($conf[$name]);
|
1287
|
}
|
1288
|
|
1289
|
/**
|
1290
|
* Retrieves the current page from the cache.
|
1291
|
*
|
1292
|
* Note: we do not serve cached pages to authenticated users, or to anonymous
|
1293
|
* users when $_SESSION is non-empty. $_SESSION may contain status messages
|
1294
|
* from a form submission, the contents of a shopping cart, or other user-
|
1295
|
* specific content that should not be cached and displayed to other users.
|
1296
|
*
|
1297
|
* @param $check_only
|
1298
|
* (optional) Set to TRUE to only return whether a previous call found a
|
1299
|
* cache entry.
|
1300
|
*
|
1301
|
* @return
|
1302
|
* The cache object, if the page was found in the cache, NULL otherwise.
|
1303
|
*/
|
1304
|
function drupal_page_get_cache($check_only = FALSE) {
|
1305
|
global $base_root;
|
1306
|
static $cache_hit = FALSE;
|
1307
|
|
1308
|
if ($check_only) {
|
1309
|
return $cache_hit;
|
1310
|
}
|
1311
|
|
1312
|
if (drupal_page_is_cacheable()) {
|
1313
|
$cache = cache_get($base_root . request_uri(), 'cache_page');
|
1314
|
if ($cache !== FALSE) {
|
1315
|
$cache_hit = TRUE;
|
1316
|
}
|
1317
|
return $cache;
|
1318
|
}
|
1319
|
}
|
1320
|
|
1321
|
/**
|
1322
|
* Determines the cacheability of the current page.
|
1323
|
*
|
1324
|
* @param $allow_caching
|
1325
|
* Set to FALSE if you want to prevent this page from being cached.
|
1326
|
*
|
1327
|
* @return
|
1328
|
* TRUE if the current page can be cached, FALSE otherwise.
|
1329
|
*/
|
1330
|
function drupal_page_is_cacheable($allow_caching = NULL) {
|
1331
|
$allow_caching_static = &drupal_static(__FUNCTION__, TRUE);
|
1332
|
if (isset($allow_caching)) {
|
1333
|
$allow_caching_static = $allow_caching;
|
1334
|
}
|
1335
|
|
1336
|
return $allow_caching_static && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')
|
1337
|
&& !drupal_is_cli();
|
1338
|
}
|
1339
|
|
1340
|
/**
|
1341
|
* Invokes a bootstrap hook in all bootstrap modules that implement it.
|
1342
|
*
|
1343
|
* @param $hook
|
1344
|
* The name of the bootstrap hook to invoke.
|
1345
|
*
|
1346
|
* @see bootstrap_hooks()
|
1347
|
*/
|
1348
|
function bootstrap_invoke_all($hook) {
|
1349
|
// Bootstrap modules should have been loaded when this function is called, so
|
1350
|
// we don't need to tell module_list() to reset its internal list (and we
|
1351
|
// therefore leave the first parameter at its default value of FALSE). We
|
1352
|
// still pass in TRUE for the second parameter, though; in case this is the
|
1353
|
// first time during the bootstrap that module_list() is called, we want to
|
1354
|
// make sure that its internal cache is primed with the bootstrap modules
|
1355
|
// only.
|
1356
|
foreach (module_list(FALSE, TRUE) as $module) {
|
1357
|
drupal_load('module', $module);
|
1358
|
module_invoke($module, $hook);
|
1359
|
}
|
1360
|
}
|
1361
|
|
1362
|
/**
|
1363
|
* Includes a file with the provided type and name.
|
1364
|
*
|
1365
|
* This prevents including a theme, engine, module, etc., more than once.
|
1366
|
*
|
1367
|
* @param $type
|
1368
|
* The type of item to load (i.e. theme, theme_engine, module).
|
1369
|
* @param $name
|
1370
|
* The name of the item to load.
|
1371
|
*
|
1372
|
* @return
|
1373
|
* TRUE if the item is loaded or has already been loaded.
|
1374
|
*/
|
1375
|
function drupal_load($type, $name) {
|
1376
|
// Once a file is included this can't be reversed during a request so do not
|
1377
|
// use drupal_static() here.
|
1378
|
static $files = array();
|
1379
|
|
1380
|
if (isset($files[$type][$name])) {
|
1381
|
return TRUE;
|
1382
|
}
|
1383
|
|
1384
|
$filename = drupal_get_filename($type, $name);
|
1385
|
|
1386
|
if ($filename) {
|
1387
|
include_once DRUPAL_ROOT . '/' . $filename;
|
1388
|
$files[$type][$name] = TRUE;
|
1389
|
|
1390
|
return TRUE;
|
1391
|
}
|
1392
|
|
1393
|
return FALSE;
|
1394
|
}
|
1395
|
|
1396
|
/**
|
1397
|
* Sets an HTTP response header for the current page.
|
1398
|
*
|
1399
|
* Note: When sending a Content-Type header, always include a 'charset' type,
|
1400
|
* too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
|
1401
|
*
|
1402
|
* @param $name
|
1403
|
* The HTTP header name, or the special 'Status' header name.
|
1404
|
* @param $value
|
1405
|
* The HTTP header value; if equal to FALSE, the specified header is unset.
|
1406
|
* If $name is 'Status', this is expected to be a status code followed by a
|
1407
|
* reason phrase, e.g. "404 Not Found".
|
1408
|
* @param $append
|
1409
|
* Whether to append the value to an existing header or to replace it.
|
1410
|
*/
|
1411
|
function drupal_add_http_header($name, $value, $append = FALSE) {
|
1412
|
// The headers as name/value pairs.
|
1413
|
$headers = &drupal_static('drupal_http_headers', array());
|
1414
|
|
1415
|
$name_lower = strtolower($name);
|
1416
|
_drupal_set_preferred_header_name($name);
|
1417
|
|
1418
|
if ($value === FALSE) {
|
1419
|
$headers[$name_lower] = FALSE;
|
1420
|
}
|
1421
|
elseif (isset($headers[$name_lower]) && $append) {
|
1422
|
// Multiple headers with identical names may be combined using comma (RFC
|
1423
|
// 2616, section 4.2).
|
1424
|
$headers[$name_lower] .= ',' . $value;
|
1425
|
}
|
1426
|
else {
|
1427
|
$headers[$name_lower] = $value;
|
1428
|
}
|
1429
|
drupal_send_headers(array($name => $headers[$name_lower]), TRUE);
|
1430
|
}
|
1431
|
|
1432
|
/**
|
1433
|
* Gets the HTTP response headers for the current page.
|
1434
|
*
|
1435
|
* @param $name
|
1436
|
* An HTTP header name. If omitted, all headers are returned as name/value
|
1437
|
* pairs. If an array value is FALSE, the header has been unset.
|
1438
|
*
|
1439
|
* @return
|
1440
|
* A string containing the header value, or FALSE if the header has been set,
|
1441
|
* or NULL if the header has not been set.
|
1442
|
*/
|
1443
|
function drupal_get_http_header($name = NULL) {
|
1444
|
$headers = &drupal_static('drupal_http_headers', array());
|
1445
|
if (isset($name)) {
|
1446
|
$name = strtolower($name);
|
1447
|
return isset($headers[$name]) ? $headers[$name] : NULL;
|
1448
|
}
|
1449
|
else {
|
1450
|
return $headers;
|
1451
|
}
|
1452
|
}
|
1453
|
|
1454
|
/**
|
1455
|
* Sets the preferred name for the HTTP header.
|
1456
|
*
|
1457
|
* Header names are case-insensitive, but for maximum compatibility they should
|
1458
|
* follow "common form" (see RFC 2617, section 4.2).
|
1459
|
*/
|
1460
|
function _drupal_set_preferred_header_name($name = NULL) {
|
1461
|
static $header_names = array();
|
1462
|
|
1463
|
if (!isset($name)) {
|
1464
|
return $header_names;
|
1465
|
}
|
1466
|
$header_names[strtolower($name)] = $name;
|
1467
|
}
|
1468
|
|
1469
|
/**
|
1470
|
* Sends the HTTP response headers that were previously set, adding defaults.
|
1471
|
*
|
1472
|
* Headers are set in drupal_add_http_header(). Default headers are not set
|
1473
|
* if they have been replaced or unset using drupal_add_http_header().
|
1474
|
*
|
1475
|
* @param array $default_headers
|
1476
|
* (optional) An array of headers as name/value pairs.
|
1477
|
* @param bool $only_default
|
1478
|
* (optional) If TRUE and headers have already been sent, send only the
|
1479
|
* specified headers.
|
1480
|
*/
|
1481
|
function drupal_send_headers($default_headers = array(), $only_default = FALSE) {
|
1482
|
$headers_sent = &drupal_static(__FUNCTION__, FALSE);
|
1483
|
$headers = drupal_get_http_header();
|
1484
|
if ($only_default && $headers_sent) {
|
1485
|
$headers = array();
|
1486
|
}
|
1487
|
$headers_sent = TRUE;
|
1488
|
|
1489
|
$header_names = _drupal_set_preferred_header_name();
|
1490
|
foreach ($default_headers as $name => $value) {
|
1491
|
$name_lower = strtolower($name);
|
1492
|
if (!isset($headers[$name_lower])) {
|
1493
|
$headers[$name_lower] = $value;
|
1494
|
$header_names[$name_lower] = $name;
|
1495
|
}
|
1496
|
}
|
1497
|
foreach ($headers as $name_lower => $value) {
|
1498
|
if ($name_lower == 'status') {
|
1499
|
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $value);
|
1500
|
}
|
1501
|
// Skip headers that have been unset.
|
1502
|
elseif ($value !== FALSE) {
|
1503
|
header($header_names[$name_lower] . ': ' . $value);
|
1504
|
}
|
1505
|
}
|
1506
|
}
|
1507
|
|
1508
|
/**
|
1509
|
* Sets HTTP headers in preparation for a page response.
|
1510
|
*
|
1511
|
* Authenticated users are always given a 'no-cache' header, and will fetch a
|
1512
|
* fresh page on every request. This prevents authenticated users from seeing
|
1513
|
* locally cached pages.
|
1514
|
*
|
1515
|
* ETag and Last-Modified headers are not set per default for authenticated
|
1516
|
* users so that browsers do not send If-Modified-Since headers from
|
1517
|
* authenticated user pages. drupal_serve_page_from_cache() will set appropriate
|
1518
|
* ETag and Last-Modified headers for cached pages.
|
1519
|
*
|
1520
|
* @see drupal_page_set_cache()
|
1521
|
*/
|
1522
|
function drupal_page_header() {
|
1523
|
$headers_sent = &drupal_static(__FUNCTION__, FALSE);
|
1524
|
if ($headers_sent) {
|
1525
|
return TRUE;
|
1526
|
}
|
1527
|
$headers_sent = TRUE;
|
1528
|
|
1529
|
$default_headers = array(
|
1530
|
'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
|
1531
|
'Cache-Control' => 'no-cache, must-revalidate',
|
1532
|
// Prevent browsers from sniffing a response and picking a MIME type
|
1533
|
// different from the declared content-type, since that can lead to
|
1534
|
// XSS and other vulnerabilities.
|
1535
|
'X-Content-Type-Options' => 'nosniff',
|
1536
|
);
|
1537
|
drupal_send_headers($default_headers);
|
1538
|
}
|
1539
|
|
1540
|
/**
|
1541
|
* Sets HTTP headers in preparation for a cached page response.
|
1542
|
*
|
1543
|
* The headers allow as much as possible in proxies and browsers without any
|
1544
|
* particular knowledge about the pages. Modules can override these headers
|
1545
|
* using drupal_add_http_header().
|
1546
|
*
|
1547
|
* If the request is conditional (using If-Modified-Since and If-None-Match),
|
1548
|
* and the conditions match those currently in the cache, a 304 Not Modified
|
1549
|
* response is sent.
|
1550
|
*/
|
1551
|
function drupal_serve_page_from_cache(stdClass $cache) {
|
1552
|
// Negotiate whether to use compression.
|
1553
|
$page_compression = !empty($cache->data['page_compressed']);
|
1554
|
$return_compressed = $page_compression && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE;
|
1555
|
|
1556
|
// Get headers set in hook_boot(). Keys are lower-case.
|
1557
|
$hook_boot_headers = drupal_get_http_header();
|
1558
|
|
1559
|
// Headers generated in this function, that may be replaced or unset using
|
1560
|
// drupal_add_http_headers(). Keys are mixed-case.
|
1561
|
$default_headers = array();
|
1562
|
|
1563
|
foreach ($cache->data['headers'] as $name => $value) {
|
1564
|
// In the case of a 304 response, certain headers must be sent, and the
|
1565
|
// remaining may not (see RFC 2616, section 10.3.5). Do not override
|
1566
|
// headers set in hook_boot().
|
1567
|
$name_lower = strtolower($name);
|
1568
|
if (in_array($name_lower, array('content-location', 'expires', 'cache-control', 'vary')) && !isset($hook_boot_headers[$name_lower])) {
|
1569
|
drupal_add_http_header($name, $value);
|
1570
|
unset($cache->data['headers'][$name]);
|
1571
|
}
|
1572
|
}
|
1573
|
|
1574
|
// If the client sent a session cookie, a cached copy will only be served
|
1575
|
// to that one particular client due to Vary: Cookie. Thus, do not set
|
1576
|
// max-age > 0, allowing the page to be cached by external proxies, when a
|
1577
|
// session cookie is present unless the Vary header has been replaced or
|
1578
|
// unset in hook_boot().
|
1579
|
$max_age = !isset($_COOKIE[session_name()]) || isset($hook_boot_headers['vary']) ? variable_get('page_cache_maximum_age', 0) : 0;
|
1580
|
$default_headers['Cache-Control'] = 'public, max-age=' . $max_age;
|
1581
|
|
1582
|
// Entity tag should change if the output changes.
|
1583
|
$etag = '"' . $cache->created . '-' . intval($return_compressed) . '"';
|
1584
|
header('Etag: ' . $etag);
|
1585
|
|
1586
|
// See if the client has provided the required HTTP headers.
|
1587
|
$if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) : FALSE;
|
1588
|
$if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : FALSE;
|
1589
|
|
1590
|
if ($if_modified_since && $if_none_match
|
1591
|
&& $if_none_match == $etag // etag must match
|
1592
|
&& $if_modified_since == $cache->created) { // if-modified-since must match
|
1593
|
header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
|
1594
|
drupal_send_headers($default_headers);
|
1595
|
return;
|
1596
|
}
|
1597
|
|
1598
|
// Send the remaining headers.
|
1599
|
foreach ($cache->data['headers'] as $name => $value) {
|
1600
|
drupal_add_http_header($name, $value);
|
1601
|
}
|
1602
|
|
1603
|
$default_headers['Last-Modified'] = gmdate(DATE_RFC7231, $cache->created);
|
1604
|
|
1605
|
// HTTP/1.0 proxies does not support the Vary header, so prevent any caching
|
1606
|
// by sending an Expires date in the past. HTTP/1.1 clients ignores the
|
1607
|
// Expires header if a Cache-Control: max-age= directive is specified (see RFC
|
1608
|
// 2616, section 14.9.3).
|
1609
|
$default_headers['Expires'] = 'Sun, 19 Nov 1978 05:00:00 GMT';
|
1610
|
|
1611
|
drupal_send_headers($default_headers);
|
1612
|
|
1613
|
// Allow HTTP proxies to cache pages for anonymous users without a session
|
1614
|
// cookie. The Vary header is used to indicates the set of request-header
|
1615
|
// fields that fully determines whether a cache is permitted to use the
|
1616
|
// response to reply to a subsequent request for a given URL without
|
1617
|
// revalidation. If a Vary header has been set in hook_boot(), it is assumed
|
1618
|
// that the module knows how to cache the page.
|
1619
|
if (!isset($hook_boot_headers['vary']) && !variable_get('omit_vary_cookie')) {
|
1620
|
header('Vary: Cookie');
|
1621
|
}
|
1622
|
|
1623
|
if ($page_compression) {
|
1624
|
header('Vary: Accept-Encoding', FALSE);
|
1625
|
// If page_compression is enabled, the cache contains gzipped data.
|
1626
|
if ($return_compressed) {
|
1627
|
// $cache->data['body'] is already gzip'ed, so make sure
|
1628
|
// zlib.output_compression does not compress it once more.
|
1629
|
ini_set('zlib.output_compression', '0');
|
1630
|
header('Content-Encoding: gzip');
|
1631
|
}
|
1632
|
else {
|
1633
|
// The client does not support compression, so unzip the data in the
|
1634
|
// cache. Strip the gzip header and run uncompress.
|
1635
|
$cache->data['body'] = gzinflate(substr(substr($cache->data['body'], 10), 0, -8));
|
1636
|
}
|
1637
|
}
|
1638
|
|
1639
|
// Print the page.
|
1640
|
print $cache->data['body'];
|
1641
|
}
|
1642
|
|
1643
|
/**
|
1644
|
* Defines the critical hooks that force modules to always be loaded.
|
1645
|
*/
|
1646
|
function bootstrap_hooks() {
|
1647
|
return array('boot', 'exit', 'watchdog', 'language_init');
|
1648
|
}
|
1649
|
|
1650
|
/**
|
1651
|
* Unserializes and appends elements from a serialized string.
|
1652
|
*
|
1653
|
* @param $obj
|
1654
|
* The object to which the elements are appended.
|
1655
|
* @param $field
|
1656
|
* The attribute of $obj whose value should be unserialized.
|
1657
|
*/
|
1658
|
function drupal_unpack($obj, $field = 'data') {
|
1659
|
if ($obj->$field && $data = unserialize($obj->$field)) {
|
1660
|
foreach ($data as $key => $value) {
|
1661
|
if (!empty($key) && !isset($obj->$key)) {
|
1662
|
$obj->$key = $value;
|
1663
|
}
|
1664
|
}
|
1665
|
}
|
1666
|
return $obj;
|
1667
|
}
|
1668
|
|
1669
|
/**
|
1670
|
* Translates a string to the current language or to a given language.
|
1671
|
*
|
1672
|
* The t() function serves two purposes. First, at run-time it translates
|
1673
|
* user-visible text into the appropriate language. Second, various mechanisms
|
1674
|
* that figure out what text needs to be translated work off t() -- the text
|
1675
|
* inside t() calls is added to the database of strings to be translated.
|
1676
|
* These strings are expected to be in English, so the first argument should
|
1677
|
* always be in English. To enable a fully-translatable site, it is important
|
1678
|
* that all human-readable text that will be displayed on the site or sent to
|
1679
|
* a user is passed through the t() function, or a related function. See the
|
1680
|
* @link http://drupal.org/node/322729 Localization API @endlink pages for
|
1681
|
* more information, including recommendations on how to break up or not
|
1682
|
* break up strings for translation.
|
1683
|
*
|
1684
|
* @section sec_translating_vars Translating Variables
|
1685
|
* You should never use t() to translate variables, such as calling
|
1686
|
* @code t($text); @endcode, unless the text that the variable holds has been
|
1687
|
* passed through t() elsewhere (e.g., $text is one of several translated
|
1688
|
* literal strings in an array). It is especially important never to call
|
1689
|
* @code t($user_text); @endcode, where $user_text is some text that a user
|
1690
|
* entered - doing that can lead to cross-site scripting and other security
|
1691
|
* problems. However, you can use variable substitution in your string, to put
|
1692
|
* variable text such as user names or link URLs into translated text. Variable
|
1693
|
* substitution looks like this:
|
1694
|
* @code
|
1695
|
* $text = t("@name's blog", array('@name' => format_username($account)));
|
1696
|
* @endcode
|
1697
|
* Basically, you can put variables like @name into your string, and t() will
|
1698
|
* substitute their sanitized values at translation time. (See the
|
1699
|
* Localization API pages referenced above and the documentation of
|
1700
|
* format_string() for details about how to define variables in your string.)
|
1701
|
* Translators can then rearrange the string as necessary for the language
|
1702
|
* (e.g., in Spanish, it might be "blog de @name").
|
1703
|
*
|
1704
|
* @section sec_alt_funcs_install Use During Installation Phase
|
1705
|
* During the Drupal installation phase, some resources used by t() wil not be
|
1706
|
* available to code that needs localization. See st() and get_t() for
|
1707
|
* alternatives.
|
1708
|
*
|
1709
|
* @section sec_context String context
|
1710
|
* Matching source strings are normally only translated once, and the same
|
1711
|
* translation is used everywhere that has a matching string. However, in some
|
1712
|
* cases, a certain English source string needs to have multiple translations.
|
1713
|
* One example of this is the string "May", which could be used as either a
|
1714
|
* full month name or a 3-letter abbreviated month. In other languages where
|
1715
|
* the month name for May has more than 3 letters, you would need to provide
|
1716
|
* two different translations (one for the full name and one abbreviated), and
|
1717
|
* the correct form would need to be chosen, depending on how "May" is being
|
1718
|
* used. To facilitate this, the "May" string should be provided with two
|
1719
|
* different contexts in the $options parameter when calling t(). For example:
|
1720
|
* @code
|
1721
|
* t('May', array(), array('context' => 'Long month name')
|
1722
|
* t('May', array(), array('context' => 'Abbreviated month name')
|
1723
|
* @endcode
|
1724
|
* See https://localize.drupal.org/node/2109 for more information.
|
1725
|
*
|
1726
|
* @param $string
|
1727
|
* A string containing the English string to translate.
|
1728
|
* @param $args
|
1729
|
* An associative array of replacements to make after translation. Based
|
1730
|
* on the first character of the key, the value is escaped and/or themed.
|
1731
|
* See format_string() for details.
|
1732
|
* @param $options
|
1733
|
* An associative array of additional options, with the following elements:
|
1734
|
* - 'langcode' (defaults to the current language): The language code to
|
1735
|
* translate to a language other than what is used to display the page.
|
1736
|
* - 'context' (defaults to the empty context): A string giving the context
|
1737
|
* that the source string belongs to. See @ref sec_context above for more
|
1738
|
* information.
|
1739
|
*
|
1740
|
* @return
|
1741
|
* The translated string.
|
1742
|
*
|
1743
|
* @see st()
|
1744
|
* @see get_t()
|
1745
|
* @see format_string()
|
1746
|
* @ingroup sanitization
|
1747
|
*/
|
1748
|
function t($string, array $args = array(), array $options = array()) {
|
1749
|
global $language;
|
1750
|
static $custom_strings;
|
1751
|
|
1752
|
// Merge in default.
|
1753
|
if (empty($options['langcode'])) {
|
1754
|
$options['langcode'] = isset($language->language) ? $language->language : 'en';
|
1755
|
}
|
1756
|
if (empty($options['context'])) {
|
1757
|
$options['context'] = '';
|
1758
|
}
|
1759
|
|
1760
|
// First, check for an array of customized strings. If present, use the array
|
1761
|
// *instead of* database lookups. This is a high performance way to provide a
|
1762
|
// handful of string replacements. See settings.php for examples.
|
1763
|
// Cache the $custom_strings variable to improve performance.
|
1764
|
if (!isset($custom_strings[$options['langcode']])) {
|
1765
|
$custom_strings[$options['langcode']] = variable_get('locale_custom_strings_' . $options['langcode'], array());
|
1766
|
}
|
1767
|
// Custom strings work for English too, even if locale module is disabled.
|
1768
|
if (isset($custom_strings[$options['langcode']][$options['context']][$string])) {
|
1769
|
$string = $custom_strings[$options['langcode']][$options['context']][$string];
|
1770
|
}
|
1771
|
// Translate with locale module if enabled.
|
1772
|
elseif ($options['langcode'] != 'en' && function_exists('locale')) {
|
1773
|
$string = locale($string, $options['context'], $options['langcode']);
|
1774
|
}
|
1775
|
if (empty($args)) {
|
1776
|
return $string;
|
1777
|
}
|
1778
|
else {
|
1779
|
return format_string($string, $args);
|
1780
|
}
|
1781
|
}
|
1782
|
|
1783
|
/**
|
1784
|
* Formats a string for HTML display by replacing variable placeholders.
|
1785
|
*
|
1786
|
* This function replaces variable placeholders in a string with the requested
|
1787
|
* values and escapes the values so they can be safely displayed as HTML. It
|
1788
|
* should be used on any unknown text that is intended to be printed to an HTML
|
1789
|
* page (especially text that may have come from untrusted users, since in that
|
1790
|
* case it prevents cross-site scripting and other security problems).
|
1791
|
*
|
1792
|
* In most cases, you should use t() rather than calling this function
|
1793
|
* directly, since it will translate the text (on non-English-only sites) in
|
1794
|
* addition to formatting it.
|
1795
|
*
|
1796
|
* @param $string
|
1797
|
* A string containing placeholders.
|
1798
|
* @param $args
|
1799
|
* An associative array of replacements to make. Occurrences in $string of
|
1800
|
* any key in $args are replaced with the corresponding value, after optional
|
1801
|
* sanitization and formatting. The type of sanitization and formatting
|
1802
|
* depends on the first character of the key:
|
1803
|
* - @variable: Escaped to HTML using check_plain(). Use this as the default
|
1804
|
* choice for anything displayed on a page on the site.
|
1805
|
* - %variable: Escaped to HTML and formatted using drupal_placeholder(),
|
1806
|
* which makes it display as <em>emphasized</em> text.
|
1807
|
* - !variable: Inserted as is, with no sanitization or formatting. Only use
|
1808
|
* this for text that has already been prepared for HTML display (for
|
1809
|
* example, user-supplied text that has already been run through
|
1810
|
* check_plain() previously, or is expected to contain some limited HTML
|
1811
|
* tags and has already been run through filter_xss() previously).
|
1812
|
*
|
1813
|
* @see t()
|
1814
|
* @ingroup sanitization
|
1815
|
*/
|
1816
|
function format_string($string, array $args = array()) {
|
1817
|
// Transform arguments before inserting them.
|
1818
|
foreach ($args as $key => $value) {
|
1819
|
switch ($key[0]) {
|
1820
|
case '@':
|
1821
|
// Escaped only.
|
1822
|
$args[$key] = check_plain($value);
|
1823
|
break;
|
1824
|
|
1825
|
case '%':
|
1826
|
default:
|
1827
|
// Escaped and placeholder.
|
1828
|
$args[$key] = drupal_placeholder($value);
|
1829
|
break;
|
1830
|
|
1831
|
case '!':
|
1832
|
// Pass-through.
|
1833
|
}
|
1834
|
}
|
1835
|
return strtr($string, $args);
|
1836
|
}
|
1837
|
|
1838
|
/**
|
1839
|
* Encodes special characters in a plain-text string for display as HTML.
|
1840
|
*
|
1841
|
* Also validates strings as UTF-8 to prevent cross site scripting attacks on
|
1842
|
* Internet Explorer 6.
|
1843
|
*
|
1844
|
* @param string $text
|
1845
|
* The text to be checked or processed.
|
1846
|
*
|
1847
|
* @return string
|
1848
|
* An HTML safe version of $text. If $text is not valid UTF-8, an empty string
|
1849
|
* is returned and, on PHP < 5.4, a warning may be issued depending on server
|
1850
|
* configuration (see @link https://bugs.php.net/bug.php?id=47494 @endlink).
|
1851
|
*
|
1852
|
* @see drupal_validate_utf8()
|
1853
|
* @ingroup sanitization
|
1854
|
*/
|
1855
|
function check_plain($text) {
|
1856
|
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
|
1857
|
}
|
1858
|
|
1859
|
/**
|
1860
|
* Checks whether a string is valid UTF-8.
|
1861
|
*
|
1862
|
* All functions designed to filter input should use drupal_validate_utf8
|
1863
|
* to ensure they operate on valid UTF-8 strings to prevent bypass of the
|
1864
|
* filter.
|
1865
|
*
|
1866
|
* When text containing an invalid UTF-8 lead byte (0xC0 - 0xFF) is presented
|
1867
|
* as UTF-8 to Internet Explorer 6, the program may misinterpret subsequent
|
1868
|
* bytes. When these subsequent bytes are HTML control characters such as
|
1869
|
* quotes or angle brackets, parts of the text that were deemed safe by filters
|
1870
|
* end up in locations that are potentially unsafe; An onerror attribute that
|
1871
|
* is outside of a tag, and thus deemed safe by a filter, can be interpreted
|
1872
|
* by the browser as if it were inside the tag.
|
1873
|
*
|
1874
|
* The function does not return FALSE for strings containing character codes
|
1875
|
* above U+10FFFF, even though these are prohibited by RFC 3629.
|
1876
|
*
|
1877
|
* @param $text
|
1878
|
* The text to check.
|
1879
|
*
|
1880
|
* @return
|
1881
|
* TRUE if the text is valid UTF-8, FALSE if not.
|
1882
|
*/
|
1883
|
function drupal_validate_utf8($text) {
|
1884
|
if (strlen($text) == 0) {
|
1885
|
return TRUE;
|
1886
|
}
|
1887
|
// With the PCRE_UTF8 modifier 'u', preg_match() fails silently on strings
|
1888
|
// containing invalid UTF-8 byte sequences. It does not reject character
|
1889
|
// codes above U+10FFFF (represented by 4 or more octets), though.
|
1890
|
return (preg_match('/^./us', $text) == 1);
|
1891
|
}
|
1892
|
|
1893
|
/**
|
1894
|
* Returns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
|
1895
|
*
|
1896
|
* Because $_SERVER['REQUEST_URI'] is only available on Apache, we generate an
|
1897
|
* equivalent using other environment variables.
|
1898
|
*/
|
1899
|
function request_uri() {
|
1900
|
if (isset($_SERVER['REQUEST_URI'])) {
|
1901
|
$uri = $_SERVER['REQUEST_URI'];
|
1902
|
}
|
1903
|
else {
|
1904
|
if (isset($_SERVER['argv'])) {
|
1905
|
$uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
|
1906
|
}
|
1907
|
elseif (isset($_SERVER['QUERY_STRING'])) {
|
1908
|
$uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
|
1909
|
}
|
1910
|
else {
|
1911
|
$uri = $_SERVER['SCRIPT_NAME'];
|
1912
|
}
|
1913
|
}
|
1914
|
// Prevent multiple slashes to avoid cross site requests via the Form API.
|
1915
|
$uri = '/' . ltrim($uri, '/');
|
1916
|
|
1917
|
return $uri;
|
1918
|
}
|
1919
|
|
1920
|
/**
|
1921
|
* Logs an exception.
|
1922
|
*
|
1923
|
* This is a wrapper function for watchdog() which automatically decodes an
|
1924
|
* exception.
|
1925
|
*
|
1926
|
* @param $type
|
1927
|
* The category to which this message belongs.
|
1928
|
* @param $exception
|
1929
|
* The exception that is going to be logged.
|
1930
|
* @param $message
|
1931
|
* The message to store in the log. If empty, a text that contains all useful
|
1932
|
* information about the passed-in exception is used.
|
1933
|
* @param $variables
|
1934
|
* Array of variables to replace in the message on display. Defaults to the
|
1935
|
* return value of _drupal_decode_exception().
|
1936
|
* @param $severity
|
1937
|
* The severity of the message, as per RFC 3164.
|
1938
|
* @param $link
|
1939
|
* A link to associate with the message.
|
1940
|
*
|
1941
|
* @see watchdog()
|
1942
|
* @see _drupal_decode_exception()
|
1943
|
*/
|
1944
|
function watchdog_exception($type, Exception $exception, $message = NULL, $variables = array(), $severity = WATCHDOG_ERROR, $link = NULL) {
|
1945
|
|
1946
|
// Use a default value if $message is not set.
|
1947
|
if (empty($message)) {
|
1948
|
// The exception message is run through check_plain() by _drupal_decode_exception().
|
1949
|
$message = '%type: !message in %function (line %line of %file).';
|
1950
|
}
|
1951
|
// $variables must be an array so that we can add the exception information.
|
1952
|
if (!is_array($variables)) {
|
1953
|
$variables = array();
|
1954
|
}
|
1955
|
|
1956
|
require_once DRUPAL_ROOT . '/includes/errors.inc';
|
1957
|
$variables += _drupal_decode_exception($exception);
|
1958
|
watchdog($type, $message, $variables, $severity, $link);
|
1959
|
}
|
1960
|
|
1961
|
/**
|
1962
|
* Logs a system message.
|
1963
|
*
|
1964
|
* @param $type
|
1965
|
* The category to which this message belongs. Can be any string, but the
|
1966
|
* general practice is to use the name of the module calling watchdog().
|
1967
|
* @param $message
|
1968
|
* The message to store in the log. Keep $message translatable
|
1969
|
* by not concatenating dynamic values into it! Variables in the
|
1970
|
* message should be added by using placeholder strings alongside
|
1971
|
* the variables argument to declare the value of the placeholders.
|
1972
|
* See t() for documentation on how $message and $variables interact.
|
1973
|
* @param $variables
|
1974
|
* Array of variables to replace in the message on display or
|
1975
|
* NULL if message is already translated or not possible to
|
1976
|
* translate.
|
1977
|
* @param $severity
|
1978
|
* The severity of the message; one of the following values as defined in
|
1979
|
* @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
|
1980
|
* - WATCHDOG_EMERGENCY: Emergency, system is unusable.
|
1981
|
* - WATCHDOG_ALERT: Alert, action must be taken immediately.
|
1982
|
* - WATCHDOG_CRITICAL: Critical conditions.
|
1983
|
* - WATCHDOG_ERROR: Error conditions.
|
1984
|
* - WATCHDOG_WARNING: Warning conditions.
|
1985
|
* - WATCHDOG_NOTICE: (default) Normal but significant conditions.
|
1986
|
* - WATCHDOG_INFO: Informational messages.
|
1987
|
* - WATCHDOG_DEBUG: Debug-level messages.
|
1988
|
* @param $link
|
1989
|
* A link to associate with the message.
|
1990
|
*
|
1991
|
* @see watchdog_severity_levels()
|
1992
|
* @see hook_watchdog()
|
1993
|
*/
|
1994
|
function watchdog($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL) {
|
1995
|
global $user, $base_root;
|
1996
|
|
1997
|
static $in_error_state = FALSE;
|
1998
|
|
1999
|
// It is possible that the error handling will itself trigger an error. In that case, we could
|
2000
|
// end up in an infinite loop. To avoid that, we implement a simple static semaphore.
|
2001
|
if (!$in_error_state && function_exists('module_invoke_all')) {
|
2002
|
$in_error_state = TRUE;
|
2003
|
|
2004
|
// The user object may not exist in all conditions, so 0 is substituted if needed.
|
2005
|
$user_uid = isset($user->uid) ? $user->uid : 0;
|
2006
|
|
2007
|
// Prepare the fields to be logged
|
2008
|
$log_entry = array(
|
2009
|
'type' => $type,
|
2010
|
'message' => $message,
|
2011
|
'variables' => $variables,
|
2012
|
'severity' => $severity,
|
2013
|
'link' => $link,
|
2014
|
'user' => $user,
|
2015
|
'uid' => $user_uid,
|
2016
|
'request_uri' => $base_root . request_uri(),
|
2017
|
'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
|
2018
|
'ip' => ip_address(),
|
2019
|
// Request time isn't accurate for long processes, use time() instead.
|
2020
|
'timestamp' => time(),
|
2021
|
);
|
2022
|
|
2023
|
// Call the logging hooks to log/process the message
|
2024
|
module_invoke_all('watchdog', $log_entry);
|
2025
|
|
2026
|
// It is critical that the semaphore is only cleared here, in the parent
|
2027
|
// watchdog() call (not outside the loop), to prevent recursive execution.
|
2028
|
$in_error_state = FALSE;
|
2029
|
}
|
2030
|
}
|
2031
|
|
2032
|
/**
|
2033
|
* Sets a message to display to the user.
|
2034
|
*
|
2035
|
* Messages are stored in a session variable and displayed in page.tpl.php via
|
2036
|
* the $messages theme variable.
|
2037
|
*
|
2038
|
* Example usage:
|
2039
|
* @code
|
2040
|
* drupal_set_message(t('An error occurred and processing did not complete.'), 'error');
|
2041
|
* @endcode
|
2042
|
*
|
2043
|
* @param string $message
|
2044
|
* (optional) The translated message to be displayed to the user. For
|
2045
|
* consistency with other messages, it should begin with a capital letter and
|
2046
|
* end with a period.
|
2047
|
* @param string $type
|
2048
|
* (optional) The message's type. Defaults to 'status'. These values are
|
2049
|
* supported:
|
2050
|
* - 'status'
|
2051
|
* - 'warning'
|
2052
|
* - 'error'
|
2053
|
* @param bool $repeat
|
2054
|
* (optional) If this is FALSE and the message is already set, then the
|
2055
|
* message won't be repeated. Defaults to TRUE.
|
2056
|
*
|
2057
|
* @return array|null
|
2058
|
* A multidimensional array with keys corresponding to the set message types.
|
2059
|
* The indexed array values of each contain the set messages for that type.
|
2060
|
* Or, if there are no messages set, the function returns NULL.
|
2061
|
*
|
2062
|
* @see drupal_get_messages()
|
2063
|
* @see theme_status_messages()
|
2064
|
*/
|
2065
|
function drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE) {
|
2066
|
if ($message || $message === '0' || $message === 0) {
|
2067
|
if (!isset($_SESSION['messages'][$type])) {
|
2068
|
$_SESSION['messages'][$type] = array();
|
2069
|
}
|
2070
|
|
2071
|
if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
|
2072
|
$_SESSION['messages'][$type][] = $message;
|
2073
|
}
|
2074
|
|
2075
|
// Mark this page as being uncacheable.
|
2076
|
drupal_page_is_cacheable(FALSE);
|
2077
|
}
|
2078
|
|
2079
|
// Messages not set when DB connection fails.
|
2080
|
return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
|
2081
|
}
|
2082
|
|
2083
|
/**
|
2084
|
* Returns all messages that have been set with drupal_set_message().
|
2085
|
*
|
2086
|
* @param string $type
|
2087
|
* (optional) Limit the messages returned by type. Defaults to NULL, meaning
|
2088
|
* all types. These values are supported:
|
2089
|
* - NULL
|
2090
|
* - 'status'
|
2091
|
* - 'warning'
|
2092
|
* - 'error'
|
2093
|
* @param bool $clear_queue
|
2094
|
* (optional) If this is TRUE, the queue will be cleared of messages of the
|
2095
|
* type specified in the $type parameter. Otherwise the queue will be left
|
2096
|
* intact. Defaults to TRUE.
|
2097
|
*
|
2098
|
* @return array
|
2099
|
* A multidimensional array with keys corresponding to the set message types.
|
2100
|
* The indexed array values of each contain the set messages for that type.
|
2101
|
* The messages returned are limited to the type specified in the $type
|
2102
|
* parameter. If there are no messages of the specified type, an empty array
|
2103
|
* is returned.
|
2104
|
*
|
2105
|
* @see drupal_set_message()
|
2106
|
* @see theme_status_messages()
|
2107
|
*/
|
2108
|
function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
|
2109
|
if ($messages = drupal_set_message()) {
|
2110
|
if ($type) {
|
2111
|
if ($clear_queue) {
|
2112
|
unset($_SESSION['messages'][$type]);
|
2113
|
}
|
2114
|
if (isset($messages[$type])) {
|
2115
|
return array($type => $messages[$type]);
|
2116
|
}
|
2117
|
}
|
2118
|
else {
|
2119
|
if ($clear_queue) {
|
2120
|
unset($_SESSION['messages']);
|
2121
|
}
|
2122
|
return $messages;
|
2123
|
}
|
2124
|
}
|
2125
|
return array();
|
2126
|
}
|
2127
|
|
2128
|
/**
|
2129
|
* Gets the title of the current page.
|
2130
|
*
|
2131
|
* The title is displayed on the page and in the title bar.
|
2132
|
*
|
2133
|
* @return
|
2134
|
* The current page's title.
|
2135
|
*/
|
2136
|
function drupal_get_title() {
|
2137
|
$title = drupal_set_title();
|
2138
|
|
2139
|
// During a bootstrap, menu.inc is not included and thus we cannot provide a title.
|
2140
|
if (!isset($title) && function_exists('menu_get_active_title')) {
|
2141
|
$title = check_plain(menu_get_active_title());
|
2142
|
}
|
2143
|
|
2144
|
return $title;
|
2145
|
}
|
2146
|
|
2147
|
/**
|
2148
|
* Sets the title of the current page.
|
2149
|
*
|
2150
|
* The title is displayed on the page and in the title bar.
|
2151
|
*
|
2152
|
* @param $title
|
2153
|
* Optional string value to assign to the page title; or if set to NULL
|
2154
|
* (default), leaves the current title unchanged.
|
2155
|
* @param $output
|
2156
|
* Optional flag - normally should be left as CHECK_PLAIN. Only set to
|
2157
|
* PASS_THROUGH if you have already removed any possibly dangerous code
|
2158
|
* from $title using a function like check_plain() or filter_xss(). With this
|
2159
|
* flag the string will be passed through unchanged.
|
2160
|
*
|
2161
|
* @return
|
2162
|
* The updated title of the current page.
|
2163
|
*/
|
2164
|
function drupal_set_title($title = NULL, $output = CHECK_PLAIN) {
|
2165
|
$stored_title = &drupal_static(__FUNCTION__);
|
2166
|
|
2167
|
if (isset($title)) {
|
2168
|
$stored_title = ($output == PASS_THROUGH) ? $title : check_plain($title);
|
2169
|
}
|
2170
|
|
2171
|
return $stored_title;
|
2172
|
}
|
2173
|
|
2174
|
/**
|
2175
|
* Checks to see if an IP address has been blocked.
|
2176
|
*
|
2177
|
* Blocked IP addresses are stored in the database by default. However for
|
2178
|
* performance reasons we allow an override in settings.php. This allows us
|
2179
|
* to avoid querying the database at this critical stage of the bootstrap if
|
2180
|
* an administrative interface for IP address blocking is not required.
|
2181
|
*
|
2182
|
* @param $ip
|
2183
|
* IP address to check.
|
2184
|
*
|
2185
|
* @return bool
|
2186
|
* TRUE if access is denied, FALSE if access is allowed.
|
2187
|
*/
|
2188
|
function drupal_is_denied($ip) {
|
2189
|
// Because this function is called on every page request, we first check
|
2190
|
// for an array of IP addresses in settings.php before querying the
|
2191
|
// database.
|
2192
|
$blocked_ips = variable_get('blocked_ips');
|
2193
|
$denied = FALSE;
|
2194
|
if (isset($blocked_ips) && is_array($blocked_ips)) {
|
2195
|
$denied = in_array($ip, $blocked_ips);
|
2196
|
}
|
2197
|
// Only check if database.inc is loaded already. If
|
2198
|
// $conf['page_cache_without_database'] = TRUE; is set in settings.php,
|
2199
|
// then the database won't be loaded here so the IPs in the database
|
2200
|
// won't be denied. However the user asked explicitly not to use the
|
2201
|
// database and also in this case it's quite likely that the user relies
|
2202
|
// on higher performance solutions like a firewall.
|
2203
|
elseif (class_exists('Database', FALSE)) {
|
2204
|
$denied = (bool)db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField();
|
2205
|
}
|
2206
|
return $denied;
|
2207
|
}
|
2208
|
|
2209
|
/**
|
2210
|
* Handles denied users.
|
2211
|
*
|
2212
|
* @param $ip
|
2213
|
* IP address to check. Prints a message and exits if access is denied.
|
2214
|
*/
|
2215
|
function drupal_block_denied($ip) {
|
2216
|
// Deny access to blocked IP addresses - t() is not yet available.
|
2217
|
if (drupal_is_denied($ip)) {
|
2218
|
header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
|
2219
|
print 'Sorry, ' . check_plain(ip_address()) . ' has been banned.';
|
2220
|
exit();
|
2221
|
}
|
2222
|
}
|
2223
|
|
2224
|
/**
|
2225
|
* Returns a URL-safe, base64 encoded string of highly randomized bytes (over the full 8-bit range).
|
2226
|
*
|
2227
|
* @param $byte_count
|
2228
|
* The number of random bytes to fetch and base64 encode.
|
2229
|
*
|
2230
|
* @return string
|
2231
|
* The base64 encoded result will have a length of up to 4 * $byte_count.
|
2232
|
*/
|
2233
|
function drupal_random_key($byte_count = 32) {
|
2234
|
return drupal_base64_encode(drupal_random_bytes($byte_count));
|
2235
|
}
|
2236
|
|
2237
|
/**
|
2238
|
* Returns a URL-safe, base64 encoded version of the supplied string.
|
2239
|
*
|
2240
|
* @param $string
|
2241
|
* The string to convert to base64.
|
2242
|
*
|
2243
|
* @return string
|
2244
|
*/
|
2245
|
function drupal_base64_encode($string) {
|
2246
|
$data = base64_encode($string);
|
2247
|
// Modify the output so it's safe to use in URLs.
|
2248
|
return strtr($data, array('+' => '-', '/' => '_', '=' => ''));
|
2249
|
}
|
2250
|
|
2251
|
/**
|
2252
|
* Returns a string of highly randomized bytes (over the full 8-bit range).
|
2253
|
*
|
2254
|
* This function is better than simply calling mt_rand() or any other built-in
|
2255
|
* PHP function because it can return a long string of bytes (compared to < 4
|
2256
|
* bytes normally from mt_rand()) and uses the best available pseudo-random
|
2257
|
* source.
|
2258
|
*
|
2259
|
* @param $count
|
2260
|
* The number of characters (bytes) to return in the string.
|
2261
|
*/
|
2262
|
function drupal_random_bytes($count) {
|
2263
|
// $random_state does not use drupal_static as it stores random bytes.
|
2264
|
static $random_state, $bytes, $has_openssl;
|
2265
|
|
2266
|
$missing_bytes = $count - strlen($bytes);
|
2267
|
|
2268
|
if ($missing_bytes > 0) {
|
2269
|
// PHP versions prior 5.3.4 experienced openssl_random_pseudo_bytes()
|
2270
|
// locking on Windows and rendered it unusable.
|
2271
|
if (!isset($has_openssl)) {
|
2272
|
$has_openssl = version_compare(PHP_VERSION, '5.3.4', '>=') && function_exists('openssl_random_pseudo_bytes');
|
2273
|
}
|
2274
|
|
2275
|
// openssl_random_pseudo_bytes() will find entropy in a system-dependent
|
2276
|
// way.
|
2277
|
if ($has_openssl) {
|
2278
|
$bytes .= openssl_random_pseudo_bytes($missing_bytes);
|
2279
|
}
|
2280
|
|
2281
|
// Else, read directly from /dev/urandom, which is available on many *nix
|
2282
|
// systems and is considered cryptographically secure.
|
2283
|
elseif ($fh = @fopen('/dev/urandom', 'rb')) {
|
2284
|
// PHP only performs buffered reads, so in reality it will always read
|
2285
|
// at least 4096 bytes. Thus, it costs nothing extra to read and store
|
2286
|
// that much so as to speed any additional invocations.
|
2287
|
$bytes .= fread($fh, max(4096, $missing_bytes));
|
2288
|
fclose($fh);
|
2289
|
}
|
2290
|
|
2291
|
// If we couldn't get enough entropy, this simple hash-based PRNG will
|
2292
|
// generate a good set of pseudo-random bytes on any system.
|
2293
|
// Note that it may be important that our $random_state is passed
|
2294
|
// through hash() prior to being rolled into $output, that the two hash()
|
2295
|
// invocations are different, and that the extra input into the first one -
|
2296
|
// the microtime() - is prepended rather than appended. This is to avoid
|
2297
|
// directly leaking $random_state via the $output stream, which could
|
2298
|
// allow for trivial prediction of further "random" numbers.
|
2299
|
if (strlen($bytes) < $count) {
|
2300
|
// Initialize on the first call. The contents of $_SERVER includes a mix of
|
2301
|
// user-specific and system information that varies a little with each page.
|
2302
|
if (!isset($random_state)) {
|
2303
|
$random_state = print_r($_SERVER, TRUE);
|
2304
|
if (function_exists('getmypid')) {
|
2305
|
// Further initialize with the somewhat random PHP process ID.
|
2306
|
$random_state .= getmypid();
|
2307
|
}
|
2308
|
$bytes = '';
|
2309
|
}
|
2310
|
|
2311
|
do {
|
2312
|
$random_state = hash('sha256', microtime() . mt_rand() . $random_state);
|
2313
|
$bytes .= hash('sha256', mt_rand() . $random_state, TRUE);
|
2314
|
}
|
2315
|
while (strlen($bytes) < $count);
|
2316
|
}
|
2317
|
}
|
2318
|
$output = substr($bytes, 0, $count);
|
2319
|
$bytes = substr($bytes, $count);
|
2320
|
return $output;
|
2321
|
}
|
2322
|
|
2323
|
/**
|
2324
|
* Calculates a base-64 encoded, URL-safe sha-256 hmac.
|
2325
|
*
|
2326
|
* @param string $data
|
2327
|
* String to be validated with the hmac.
|
2328
|
* @param string $key
|
2329
|
* A secret string key.
|
2330
|
*
|
2331
|
* @return string
|
2332
|
* A base-64 encoded sha-256 hmac, with + replaced with -, / with _ and
|
2333
|
* any = padding characters removed.
|
2334
|
*/
|
2335
|
function drupal_hmac_base64($data, $key) {
|
2336
|
// Casting $data and $key to strings here is necessary to avoid empty string
|
2337
|
// results of the hash function if they are not scalar values. As this
|
2338
|
// function is used in security-critical contexts like token validation it is
|
2339
|
// important that it never returns an empty string.
|
2340
|
$hmac = base64_encode(hash_hmac('sha256', (string) $data, (string) $key, TRUE));
|
2341
|
// Modify the hmac so it's safe to use in URLs.
|
2342
|
return strtr($hmac, array('+' => '-', '/' => '_', '=' => ''));
|
2343
|
}
|
2344
|
|
2345
|
/**
|
2346
|
* Calculates a base-64 encoded, URL-safe sha-256 hash.
|
2347
|
*
|
2348
|
* @param $data
|
2349
|
* String to be hashed.
|
2350
|
*
|
2351
|
* @return
|
2352
|
* A base-64 encoded sha-256 hash, with + replaced with -, / with _ and
|
2353
|
* any = padding characters removed.
|
2354
|
*/
|
2355
|
function drupal_hash_base64($data) {
|
2356
|
$hash = base64_encode(hash('sha256', $data, TRUE));
|
2357
|
// Modify the hash so it's safe to use in URLs.
|
2358
|
return strtr($hash, array('+' => '-', '/' => '_', '=' => ''));
|
2359
|
}
|
2360
|
|
2361
|
/**
|
2362
|
* Merges multiple arrays, recursively, and returns the merged array.
|
2363
|
*
|
2364
|
* This function is similar to PHP's array_merge_recursive() function, but it
|
2365
|
* handles non-array values differently. When merging values that are not both
|
2366
|
* arrays, the latter value replaces the former rather than merging with it.
|
2367
|
*
|
2368
|
* Example:
|
2369
|
* @code
|
2370
|
* $link_options_1 = array('fragment' => 'x', 'attributes' => array('title' => t('X'), 'class' => array('a', 'b')));
|
2371
|
* $link_options_2 = array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('c', 'd')));
|
2372
|
*
|
2373
|
* // This results in array('fragment' => array('x', 'y'), 'attributes' => array('title' => array(t('X'), t('Y')), 'class' => array('a', 'b', 'c', 'd'))).
|
2374
|
* $incorrect = array_merge_recursive($link_options_1, $link_options_2);
|
2375
|
*
|
2376
|
* // This results in array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('a', 'b', 'c', 'd'))).
|
2377
|
* $correct = drupal_array_merge_deep($link_options_1, $link_options_2);
|
2378
|
* @endcode
|
2379
|
*
|
2380
|
* @param ...
|
2381
|
* Arrays to merge.
|
2382
|
*
|
2383
|
* @return
|
2384
|
* The merged array.
|
2385
|
*
|
2386
|
* @see drupal_array_merge_deep_array()
|
2387
|
*/
|
2388
|
function drupal_array_merge_deep() {
|
2389
|
$args = func_get_args();
|
2390
|
return drupal_array_merge_deep_array($args);
|
2391
|
}
|
2392
|
|
2393
|
/**
|
2394
|
* Merges multiple arrays, recursively, and returns the merged array.
|
2395
|
*
|
2396
|
* This function is equivalent to drupal_array_merge_deep(), except the
|
2397
|
* input arrays are passed as a single array parameter rather than a variable
|
2398
|
* parameter list.
|
2399
|
*
|
2400
|
* The following are equivalent:
|
2401
|
* - drupal_array_merge_deep($a, $b);
|
2402
|
* - drupal_array_merge_deep_array(array($a, $b));
|
2403
|
*
|
2404
|
* The following are also equivalent:
|
2405
|
* - call_user_func_array('drupal_array_merge_deep', $arrays_to_merge);
|
2406
|
* - drupal_array_merge_deep_array($arrays_to_merge);
|
2407
|
*
|
2408
|
* @see drupal_array_merge_deep()
|
2409
|
*/
|
2410
|
function drupal_array_merge_deep_array($arrays) {
|
2411
|
$result = array();
|
2412
|
|
2413
|
foreach ($arrays as $array) {
|
2414
|
foreach ($array as $key => $value) {
|
2415
|
// Renumber integer keys as array_merge_recursive() does. Note that PHP
|
2416
|
// automatically converts array keys that are integer strings (e.g., '1')
|
2417
|
// to integers.
|
2418
|
if (is_integer($key)) {
|
2419
|
$result[] = $value;
|
2420
|
}
|
2421
|
// Recurse when both values are arrays.
|
2422
|
elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
|
2423
|
$result[$key] = drupal_array_merge_deep_array(array($result[$key], $value));
|
2424
|
}
|
2425
|
// Otherwise, use the latter value, overriding any previous value.
|
2426
|
else {
|
2427
|
$result[$key] = $value;
|
2428
|
}
|
2429
|
}
|
2430
|
}
|
2431
|
|
2432
|
return $result;
|
2433
|
}
|
2434
|
|
2435
|
/**
|
2436
|
* Generates a default anonymous $user object.
|
2437
|
*
|
2438
|
* @return Object - the user object.
|
2439
|
*/
|
2440
|
function drupal_anonymous_user() {
|
2441
|
$user = variable_get('drupal_anonymous_user_object', new stdClass);
|
2442
|
$user->uid = 0;
|
2443
|
$user->hostname = ip_address();
|
2444
|
$user->roles = array();
|
2445
|
$user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
|
2446
|
$user->cache = 0;
|
2447
|
return $user;
|
2448
|
}
|
2449
|
|
2450
|
/**
|
2451
|
* Ensures Drupal is bootstrapped to the specified phase.
|
2452
|
*
|
2453
|
* In order to bootstrap Drupal from another PHP script, you can use this code:
|
2454
|
* @code
|
2455
|
* define('DRUPAL_ROOT', '/path/to/drupal');
|
2456
|
* require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
|
2457
|
* drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
|
2458
|
* @endcode
|
2459
|
*
|
2460
|
* @param int $phase
|
2461
|
* A constant telling which phase to bootstrap to. When you bootstrap to a
|
2462
|
* particular phase, all earlier phases are run automatically. Possible
|
2463
|
* values:
|
2464
|
* - DRUPAL_BOOTSTRAP_CONFIGURATION: Initializes configuration.
|
2465
|
* - DRUPAL_BOOTSTRAP_PAGE_CACHE: Tries to serve a cached page.
|
2466
|
* - DRUPAL_BOOTSTRAP_DATABASE: Initializes the database layer.
|
2467
|
* - DRUPAL_BOOTSTRAP_VARIABLES: Initializes the variable system.
|
2468
|
* - DRUPAL_BOOTSTRAP_SESSION: Initializes session handling.
|
2469
|
* - DRUPAL_BOOTSTRAP_PAGE_HEADER: Sets up the page header.
|
2470
|
* - DRUPAL_BOOTSTRAP_LANGUAGE: Finds out the language of the page.
|
2471
|
* - DRUPAL_BOOTSTRAP_FULL: Fully loads Drupal. Validates and fixes input
|
2472
|
* data.
|
2473
|
* @param boolean $new_phase
|
2474
|
* A boolean, set to FALSE if calling drupal_bootstrap from inside a
|
2475
|
* function called from drupal_bootstrap (recursion).
|
2476
|
*
|
2477
|
* @return int
|
2478
|
* The most recently completed phase.
|
2479
|
*/
|
2480
|
function drupal_bootstrap($phase = NULL, $new_phase = TRUE) {
|
2481
|
// Not drupal_static(), because does not depend on any run-time information.
|
2482
|
static $phases = array(
|
2483
|
DRUPAL_BOOTSTRAP_CONFIGURATION,
|
2484
|
DRUPAL_BOOTSTRAP_PAGE_CACHE,
|
2485
|
DRUPAL_BOOTSTRAP_DATABASE,
|
2486
|
DRUPAL_BOOTSTRAP_VARIABLES,
|
2487
|
DRUPAL_BOOTSTRAP_SESSION,
|
2488
|
DRUPAL_BOOTSTRAP_PAGE_HEADER,
|
2489
|
DRUPAL_BOOTSTRAP_LANGUAGE,
|
2490
|
DRUPAL_BOOTSTRAP_FULL,
|
2491
|
);
|
2492
|
// Not drupal_static(), because the only legitimate API to control this is to
|
2493
|
// call drupal_bootstrap() with a new phase parameter.
|
2494
|
static $final_phase;
|
2495
|
// Not drupal_static(), because it's impossible to roll back to an earlier
|
2496
|
// bootstrap state.
|
2497
|
static $stored_phase = -1;
|
2498
|
|
2499
|
if (isset($phase)) {
|
2500
|
// When not recursing, store the phase name so it's not forgotten while
|
2501
|
// recursing but take care of not going backwards.
|
2502
|
if ($new_phase && $phase >= $stored_phase) {
|
2503
|
$final_phase = $phase;
|
2504
|
}
|
2505
|
|
2506
|
// Call a phase if it has not been called before and is below the requested
|
2507
|
// phase.
|
2508
|
while ($phases && $phase > $stored_phase && $final_phase > $stored_phase) {
|
2509
|
$current_phase = array_shift($phases);
|
2510
|
|
2511
|
// This function is re-entrant. Only update the completed phase when the
|
2512
|
// current call actually resulted in a progress in the bootstrap process.
|
2513
|
if ($current_phase > $stored_phase) {
|
2514
|
$stored_phase = $current_phase;
|
2515
|
}
|
2516
|
|
2517
|
switch ($current_phase) {
|
2518
|
case DRUPAL_BOOTSTRAP_CONFIGURATION:
|
2519
|
require_once DRUPAL_ROOT . '/includes/request-sanitizer.inc';
|
2520
|
_drupal_bootstrap_configuration();
|
2521
|
break;
|
2522
|
|
2523
|
case DRUPAL_BOOTSTRAP_PAGE_CACHE:
|
2524
|
_drupal_bootstrap_page_cache();
|
2525
|
break;
|
2526
|
|
2527
|
case DRUPAL_BOOTSTRAP_DATABASE:
|
2528
|
_drupal_bootstrap_database();
|
2529
|
break;
|
2530
|
|
2531
|
case DRUPAL_BOOTSTRAP_VARIABLES:
|
2532
|
_drupal_bootstrap_variables();
|
2533
|
break;
|
2534
|
|
2535
|
case DRUPAL_BOOTSTRAP_SESSION:
|
2536
|
require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');
|
2537
|
drupal_session_initialize();
|
2538
|
break;
|
2539
|
|
2540
|
case DRUPAL_BOOTSTRAP_PAGE_HEADER:
|
2541
|
_drupal_bootstrap_page_header();
|
2542
|
break;
|
2543
|
|
2544
|
case DRUPAL_BOOTSTRAP_LANGUAGE:
|
2545
|
drupal_language_initialize();
|
2546
|
break;
|
2547
|
|
2548
|
case DRUPAL_BOOTSTRAP_FULL:
|
2549
|
require_once DRUPAL_ROOT . '/includes/common.inc';
|
2550
|
_drupal_bootstrap_full();
|
2551
|
break;
|
2552
|
}
|
2553
|
}
|
2554
|
}
|
2555
|
return $stored_phase;
|
2556
|
}
|
2557
|
|
2558
|
/**
|
2559
|
* Returns the time zone of the current user.
|
2560
|
*/
|
2561
|
function drupal_get_user_timezone() {
|
2562
|
global $user;
|
2563
|
if (variable_get('configurable_timezones', 1) && $user->uid && $user->timezone) {
|
2564
|
return $user->timezone;
|
2565
|
}
|
2566
|
else {
|
2567
|
// Ignore PHP strict notice if time zone has not yet been set in the php.ini
|
2568
|
// configuration.
|
2569
|
return variable_get('date_default_timezone', @date_default_timezone_get());
|
2570
|
}
|
2571
|
}
|
2572
|
|
2573
|
/**
|
2574
|
* Gets a salt useful for hardening against SQL injection.
|
2575
|
*
|
2576
|
* @return
|
2577
|
* A salt based on information in settings.php, not in the database.
|
2578
|
*/
|
2579
|
function drupal_get_hash_salt() {
|
2580
|
global $drupal_hash_salt, $databases;
|
2581
|
// If the $drupal_hash_salt variable is empty, a hash of the serialized
|
2582
|
// database credentials is used as a fallback salt.
|
2583
|
return empty($drupal_hash_salt) ? hash('sha256', serialize($databases)) : $drupal_hash_salt;
|
2584
|
}
|
2585
|
|
2586
|
/**
|
2587
|
* Provides custom PHP error handling.
|
2588
|
*
|
2589
|
* @param $error_level
|
2590
|
* The level of the error raised.
|
2591
|
* @param $message
|
2592
|
* The error message.
|
2593
|
* @param $filename
|
2594
|
* The filename that the error was raised in.
|
2595
|
* @param $line
|
2596
|
* The line number the error was raised at.
|
2597
|
* @param $context
|
2598
|
* An array that points to the active symbol table at the point the error
|
2599
|
* occurred.
|
2600
|
*/
|
2601
|
function _drupal_error_handler($error_level, $message, $filename, $line, $context) {
|
2602
|
require_once DRUPAL_ROOT . '/includes/errors.inc';
|
2603
|
_drupal_error_handler_real($error_level, $message, $filename, $line, $context);
|
2604
|
}
|
2605
|
|
2606
|
/**
|
2607
|
* Provides custom PHP exception handling.
|
2608
|
*
|
2609
|
* Uncaught exceptions are those not enclosed in a try/catch block. They are
|
2610
|
* always fatal: the execution of the script will stop as soon as the exception
|
2611
|
* handler exits.
|
2612
|
*
|
2613
|
* @param $exception
|
2614
|
* The exception object that was thrown.
|
2615
|
*/
|
2616
|
function _drupal_exception_handler($exception) {
|
2617
|
require_once DRUPAL_ROOT . '/includes/errors.inc';
|
2618
|
|
2619
|
try {
|
2620
|
// Log the message to the watchdog and return an error page to the user.
|
2621
|
_drupal_log_error(_drupal_decode_exception($exception), TRUE);
|
2622
|
}
|
2623
|
catch (Exception $exception2) {
|
2624
|
// Add a 500 status code in case an exception was thrown before the 500
|
2625
|
// status could be set (e.g. while loading a maintenance theme from cache).
|
2626
|
drupal_add_http_header('Status', '500 Internal Server Error');
|
2627
|
|
2628
|
// Another uncaught exception was thrown while handling the first one.
|
2629
|
// If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
|
2630
|
if (error_displayable()) {
|
2631
|
print '<h1>Additional uncaught exception thrown while handling exception.</h1>';
|
2632
|
print '<h2>Original</h2><p>' . _drupal_render_exception_safe($exception) . '</p>';
|
2633
|
print '<h2>Additional</h2><p>' . _drupal_render_exception_safe($exception2) . '</p><hr />';
|
2634
|
}
|
2635
|
}
|
2636
|
}
|
2637
|
|
2638
|
/**
|
2639
|
* Sets up the script environment and loads settings.php.
|
2640
|
*/
|
2641
|
function _drupal_bootstrap_configuration() {
|
2642
|
// Set the Drupal custom error handler.
|
2643
|
set_error_handler('_drupal_error_handler');
|
2644
|
set_exception_handler('_drupal_exception_handler');
|
2645
|
|
2646
|
drupal_environment_initialize();
|
2647
|
// Start a page timer:
|
2648
|
timer_start('page');
|
2649
|
// Initialize the configuration, including variables from settings.php.
|
2650
|
drupal_settings_initialize();
|
2651
|
|
2652
|
// Sanitize unsafe keys from the request.
|
2653
|
DrupalRequestSanitizer::sanitize();
|
2654
|
}
|
2655
|
|
2656
|
/**
|
2657
|
* Attempts to serve a page from the cache.
|
2658
|
*/
|
2659
|
function _drupal_bootstrap_page_cache() {
|
2660
|
global $user;
|
2661
|
|
2662
|
// Allow specifying special cache handlers in settings.php, like
|
2663
|
// using memcached or files for storing cache information.
|
2664
|
require_once DRUPAL_ROOT . '/includes/cache.inc';
|
2665
|
foreach (variable_get('cache_backends', array()) as $include) {
|
2666
|
require_once DRUPAL_ROOT . '/' . $include;
|
2667
|
}
|
2668
|
// Check for a cache mode force from settings.php.
|
2669
|
if (variable_get('page_cache_without_database')) {
|
2670
|
$cache_enabled = TRUE;
|
2671
|
}
|
2672
|
else {
|
2673
|
drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES, FALSE);
|
2674
|
$cache_enabled = variable_get('cache');
|
2675
|
}
|
2676
|
drupal_block_denied(ip_address());
|
2677
|
// If there is no session cookie and cache is enabled (or forced), try
|
2678
|
// to serve a cached page.
|
2679
|
if (!isset($_COOKIE[session_name()]) && $cache_enabled) {
|
2680
|
// Make sure there is a user object because its timestamp will be
|
2681
|
// checked, hook_boot might check for anonymous user etc.
|
2682
|
$user = drupal_anonymous_user();
|
2683
|
// Get the page from the cache.
|
2684
|
$cache = drupal_page_get_cache();
|
2685
|
// If there is a cached page, display it.
|
2686
|
if (is_object($cache)) {
|
2687
|
header('X-Drupal-Cache: HIT');
|
2688
|
// Restore the metadata cached with the page.
|
2689
|
$_GET['q'] = $cache->data['path'];
|
2690
|
drupal_set_title($cache->data['title'], PASS_THROUGH);
|
2691
|
date_default_timezone_set(drupal_get_user_timezone());
|
2692
|
// If the skipping of the bootstrap hooks is not enforced, call
|
2693
|
// hook_boot.
|
2694
|
if (variable_get('page_cache_invoke_hooks', TRUE)) {
|
2695
|
bootstrap_invoke_all('boot');
|
2696
|
}
|
2697
|
drupal_serve_page_from_cache($cache);
|
2698
|
// If the skipping of the bootstrap hooks is not enforced, call
|
2699
|
// hook_exit.
|
2700
|
if (variable_get('page_cache_invoke_hooks', TRUE)) {
|
2701
|
bootstrap_invoke_all('exit');
|
2702
|
}
|
2703
|
// We are done.
|
2704
|
exit;
|
2705
|
}
|
2706
|
else {
|
2707
|
header('X-Drupal-Cache: MISS');
|
2708
|
}
|
2709
|
}
|
2710
|
}
|
2711
|
|
2712
|
/**
|
2713
|
* Initializes the database system and registers autoload functions.
|
2714
|
*/
|
2715
|
function _drupal_bootstrap_database() {
|
2716
|
// Redirect the user to the installation script if Drupal has not been
|
2717
|
// installed yet (i.e., if no $databases array has been defined in the
|
2718
|
// settings.php file) and we are not already installing.
|
2719
|
if (empty($GLOBALS['databases']) && !drupal_installation_attempted()) {
|
2720
|
include_once DRUPAL_ROOT . '/includes/install.inc';
|
2721
|
install_goto('install.php');
|
2722
|
}
|
2723
|
|
2724
|
// The user agent header is used to pass a database prefix in the request when
|
2725
|
// running tests. However, for security reasons, it is imperative that we
|
2726
|
// validate we ourselves made the request.
|
2727
|
if ($test_prefix = drupal_valid_test_ua()) {
|
2728
|
// Set the test run id for use in other parts of Drupal.
|
2729
|
$test_info = &$GLOBALS['drupal_test_info'];
|
2730
|
$test_info['test_run_id'] = $test_prefix;
|
2731
|
$test_info['in_child_site'] = TRUE;
|
2732
|
|
2733
|
foreach ($GLOBALS['databases']['default'] as &$value) {
|
2734
|
// Extract the current default database prefix.
|
2735
|
if (!isset($value['prefix'])) {
|
2736
|
$current_prefix = '';
|
2737
|
}
|
2738
|
elseif (is_array($value['prefix'])) {
|
2739
|
$current_prefix = $value['prefix']['default'];
|
2740
|
}
|
2741
|
else {
|
2742
|
$current_prefix = $value['prefix'];
|
2743
|
}
|
2744
|
|
2745
|
// Remove the current database prefix and replace it by our own.
|
2746
|
$value['prefix'] = array(
|
2747
|
'default' => $current_prefix . $test_prefix,
|
2748
|
);
|
2749
|
}
|
2750
|
}
|
2751
|
|
2752
|
// Initialize the database system. Note that the connection
|
2753
|
// won't be initialized until it is actually requested.
|
2754
|
require_once DRUPAL_ROOT . '/includes/database/database.inc';
|
2755
|
|
2756
|
// Register autoload functions so that we can access classes and interfaces.
|
2757
|
// The database autoload routine comes first so that we can load the database
|
2758
|
// system without hitting the database. That is especially important during
|
2759
|
// the install or upgrade process.
|
2760
|
spl_autoload_register('drupal_autoload_class');
|
2761
|
spl_autoload_register('drupal_autoload_interface');
|
2762
|
if (version_compare(PHP_VERSION, '5.4') >= 0) {
|
2763
|
spl_autoload_register('drupal_autoload_trait');
|
2764
|
}
|
2765
|
}
|
2766
|
|
2767
|
/**
|
2768
|
* Loads system variables and all enabled bootstrap modules.
|
2769
|
*/
|
2770
|
function _drupal_bootstrap_variables() {
|
2771
|
global $conf;
|
2772
|
|
2773
|
// Initialize the lock system.
|
2774
|
require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
|
2775
|
lock_initialize();
|
2776
|
|
2777
|
// Load variables from the database, but do not overwrite variables set in settings.php.
|
2778
|
$conf = variable_initialize(isset($conf) ? $conf : array());
|
2779
|
// Load bootstrap modules.
|
2780
|
require_once DRUPAL_ROOT . '/includes/module.inc';
|
2781
|
module_load_all(TRUE);
|
2782
|
|
2783
|
// Sanitize the destination parameter (which is often used for redirects) to
|
2784
|
// prevent open redirect attacks leading to other domains. Sanitize both
|
2785
|
// $_GET['destination'] and $_REQUEST['destination'] to protect code that
|
2786
|
// relies on either, but do not sanitize $_POST to avoid interfering with
|
2787
|
// unrelated form submissions. The sanitization happens here because
|
2788
|
// url_is_external() requires the variable system to be available.
|
2789
|
if (isset($_GET['destination']) || isset($_REQUEST['destination'])) {
|
2790
|
require_once DRUPAL_ROOT . '/includes/common.inc';
|
2791
|
// If the destination is an external URL, remove it.
|
2792
|
if (isset($_GET['destination']) && url_is_external($_GET['destination'])) {
|
2793
|
unset($_GET['destination']);
|
2794
|
unset($_REQUEST['destination']);
|
2795
|
}
|
2796
|
// Use the DrupalRequestSanitizer to ensure that the destination's query
|
2797
|
// parameters are not dangerous.
|
2798
|
if (isset($_GET['destination'])) {
|
2799
|
DrupalRequestSanitizer::cleanDestination();
|
2800
|
}
|
2801
|
// If there's still something in $_REQUEST['destination'] that didn't come
|
2802
|
// from $_GET, check it too.
|
2803
|
if (isset($_REQUEST['destination']) && (!isset($_GET['destination']) || $_REQUEST['destination'] != $_GET['destination']) && url_is_external($_REQUEST['destination'])) {
|
2804
|
unset($_REQUEST['destination']);
|
2805
|
}
|
2806
|
}
|
2807
|
}
|
2808
|
|
2809
|
/**
|
2810
|
* Invokes hook_boot(), initializes locking system, and sends HTTP headers.
|
2811
|
*/
|
2812
|
function _drupal_bootstrap_page_header() {
|
2813
|
bootstrap_invoke_all('boot');
|
2814
|
|
2815
|
if (!drupal_is_cli()) {
|
2816
|
ob_start();
|
2817
|
drupal_page_header();
|
2818
|
}
|
2819
|
}
|
2820
|
|
2821
|
/**
|
2822
|
* Returns the current bootstrap phase for this Drupal process.
|
2823
|
*
|
2824
|
* The current phase is the one most recently completed by drupal_bootstrap().
|
2825
|
*
|
2826
|
* @see drupal_bootstrap()
|
2827
|
*/
|
2828
|
function drupal_get_bootstrap_phase() {
|
2829
|
return drupal_bootstrap(NULL, FALSE);
|
2830
|
}
|
2831
|
|
2832
|
/**
|
2833
|
* Returns the test prefix if this is an internal request from SimpleTest.
|
2834
|
*
|
2835
|
* @return
|
2836
|
* Either the simpletest prefix (the string "simpletest" followed by any
|
2837
|
* number of digits) or FALSE if the user agent does not contain a valid
|
2838
|
* HMAC and timestamp.
|
2839
|
*/
|
2840
|
function drupal_valid_test_ua() {
|
2841
|
// No reason to reset this.
|
2842
|
static $test_prefix;
|
2843
|
|
2844
|
if (isset($test_prefix)) {
|
2845
|
return $test_prefix;
|
2846
|
}
|
2847
|
|
2848
|
if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/^(simpletest\d+);(.+);(.+);(.+)$/", $_SERVER['HTTP_USER_AGENT'], $matches)) {
|
2849
|
list(, $prefix, $time, $salt, $hmac) = $matches;
|
2850
|
$check_string = $prefix . ';' . $time . ';' . $salt;
|
2851
|
// We use the salt from settings.php to make the HMAC key, since
|
2852
|
// the database is not yet initialized and we can't access any Drupal variables.
|
2853
|
// The file properties add more entropy not easily accessible to others.
|
2854
|
$key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
|
2855
|
$time_diff = REQUEST_TIME - $time;
|
2856
|
// Since we are making a local request a 5 second time window is allowed,
|
2857
|
// and the HMAC must match.
|
2858
|
if ($time_diff >= 0 && $time_diff <= 5 && $hmac == drupal_hmac_base64($check_string, $key)) {
|
2859
|
$test_prefix = $prefix;
|
2860
|
return $test_prefix;
|
2861
|
}
|
2862
|
}
|
2863
|
|
2864
|
$test_prefix = FALSE;
|
2865
|
return $test_prefix;
|
2866
|
}
|
2867
|
|
2868
|
/**
|
2869
|
* Generates a user agent string with a HMAC and timestamp for simpletest.
|
2870
|
*/
|
2871
|
function drupal_generate_test_ua($prefix) {
|
2872
|
static $key;
|
2873
|
|
2874
|
if (!isset($key)) {
|
2875
|
// We use the salt from settings.php to make the HMAC key, since
|
2876
|
// the database is not yet initialized and we can't access any Drupal variables.
|
2877
|
// The file properties add more entropy not easily accessible to others.
|
2878
|
$key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
|
2879
|
}
|
2880
|
// Generate a moderately secure HMAC based on the database credentials.
|
2881
|
$salt = uniqid('', TRUE);
|
2882
|
$check_string = $prefix . ';' . time() . ';' . $salt;
|
2883
|
return $check_string . ';' . drupal_hmac_base64($check_string, $key);
|
2884
|
}
|
2885
|
|
2886
|
/**
|
2887
|
* Enables use of the theme system without requiring database access.
|
2888
|
*
|
2889
|
* Loads and initializes the theme system for site installs, updates and when
|
2890
|
* the site is in maintenance mode. This also applies when the database fails.
|
2891
|
*
|
2892
|
* @see _drupal_maintenance_theme()
|
2893
|
*/
|
2894
|
function drupal_maintenance_theme() {
|
2895
|
require_once DRUPAL_ROOT . '/includes/theme.maintenance.inc';
|
2896
|
_drupal_maintenance_theme();
|
2897
|
}
|
2898
|
|
2899
|
/**
|
2900
|
* Returns a simple 404 Not Found page.
|
2901
|
*
|
2902
|
* If fast 404 pages are enabled, and this is a matching page then print a
|
2903
|
* simple 404 page and exit.
|
2904
|
*
|
2905
|
* This function is called from drupal_deliver_html_page() at the time when a
|
2906
|
* a normal 404 page is generated, but it can also optionally be called directly
|
2907
|
* from settings.php to prevent a Drupal bootstrap on these pages. See
|
2908
|
* documentation in settings.php for the benefits and drawbacks of using this.
|
2909
|
*
|
2910
|
* Paths to dynamically-generated content, such as image styles, should also be
|
2911
|
* accounted for in this function.
|
2912
|
*/
|
2913
|
function drupal_fast_404() {
|
2914
|
$exclude_paths = variable_get('404_fast_paths_exclude', FALSE);
|
2915
|
if ($exclude_paths && !preg_match($exclude_paths, $_GET['q'])) {
|
2916
|
$fast_paths = variable_get('404_fast_paths', FALSE);
|
2917
|
if ($fast_paths && preg_match($fast_paths, $_GET['q'])) {
|
2918
|
drupal_add_http_header('Status', '404 Not Found');
|
2919
|
$fast_404_html = variable_get('404_fast_html', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL "@path" was not found on this server.</p></body></html>');
|
2920
|
// Replace @path in the variable with the page path.
|
2921
|
print strtr($fast_404_html, array('@path' => check_plain(request_uri())));
|
2922
|
exit;
|
2923
|
}
|
2924
|
}
|
2925
|
}
|
2926
|
|
2927
|
/**
|
2928
|
* Returns TRUE if a Drupal installation is currently being attempted.
|
2929
|
*/
|
2930
|
function drupal_installation_attempted() {
|
2931
|
return defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'install';
|
2932
|
}
|
2933
|
|
2934
|
/**
|
2935
|
* Returns the name of the proper localization function.
|
2936
|
*
|
2937
|
* get_t() exists to support localization for code that might run during
|
2938
|
* the installation phase, when some elements of the system might not have
|
2939
|
* loaded.
|
2940
|
*
|
2941
|
* This would include implementations of hook_install(), which could run
|
2942
|
* during the Drupal installation phase, and might also be run during
|
2943
|
* non-installation time, such as while installing the module from the
|
2944
|
* module administration page.
|
2945
|
*
|
2946
|
* Example usage:
|
2947
|
* @code
|
2948
|
* $t = get_t();
|
2949
|
* $translated = $t('translate this');
|
2950
|
* @endcode
|
2951
|
*
|
2952
|
* Use t() if your code will never run during the Drupal installation phase.
|
2953
|
* Use st() if your code will only run during installation and never any other
|
2954
|
* time. Use get_t() if your code could run in either circumstance.
|
2955
|
*
|
2956
|
* @see t()
|
2957
|
* @see st()
|
2958
|
* @ingroup sanitization
|
2959
|
*/
|
2960
|
function get_t() {
|
2961
|
static $t;
|
2962
|
// This is not converted to drupal_static because there is no point in
|
2963
|
// resetting this as it can not change in the course of a request.
|
2964
|
if (!isset($t)) {
|
2965
|
$t = drupal_installation_attempted() ? 'st' : 't';
|
2966
|
}
|
2967
|
return $t;
|
2968
|
}
|
2969
|
|
2970
|
/**
|
2971
|
* Initializes all the defined language types.
|
2972
|
*/
|
2973
|
function drupal_language_initialize() {
|
2974
|
$types = language_types();
|
2975
|
|
2976
|
// Ensure the language is correctly returned, even without multilanguage
|
2977
|
// support. Also make sure we have a $language fallback, in case a language
|
2978
|
// negotiation callback needs to do a full bootstrap.
|
2979
|
// Useful for eg. XML/HTML 'lang' attributes.
|
2980
|
$default = language_default();
|
2981
|
foreach ($types as $type) {
|
2982
|
$GLOBALS[$type] = $default;
|
2983
|
}
|
2984
|
if (drupal_multilingual()) {
|
2985
|
include_once DRUPAL_ROOT . '/includes/language.inc';
|
2986
|
foreach ($types as $type) {
|
2987
|
$GLOBALS[$type] = language_initialize($type);
|
2988
|
}
|
2989
|
// Allow modules to react on language system initialization in multilingual
|
2990
|
// environments.
|
2991
|
bootstrap_invoke_all('language_init');
|
2992
|
}
|
2993
|
}
|
2994
|
|
2995
|
/**
|
2996
|
* Returns a list of the built-in language types.
|
2997
|
*
|
2998
|
* @return
|
2999
|
* An array of key-values pairs where the key is the language type and the
|
3000
|
* value is its configurability.
|
3001
|
*/
|
3002
|
function drupal_language_types() {
|
3003
|
return array(
|
3004
|
LANGUAGE_TYPE_INTERFACE => TRUE,
|
3005
|
LANGUAGE_TYPE_CONTENT => FALSE,
|
3006
|
LANGUAGE_TYPE_URL => FALSE,
|
3007
|
);
|
3008
|
}
|
3009
|
|
3010
|
/**
|
3011
|
* Returns TRUE if there is more than one language enabled.
|
3012
|
*
|
3013
|
* @return
|
3014
|
* TRUE if more than one language is enabled.
|
3015
|
*/
|
3016
|
function drupal_multilingual() {
|
3017
|
// The "language_count" variable stores the number of enabled languages to
|
3018
|
// avoid unnecessarily querying the database when building the list of
|
3019
|
// enabled languages on monolingual sites.
|
3020
|
return variable_get('language_count', 1) > 1;
|
3021
|
}
|
3022
|
|
3023
|
/**
|
3024
|
* Returns an array of the available language types.
|
3025
|
*
|
3026
|
* @return
|
3027
|
* An array of all language types where the keys of each are the language type
|
3028
|
* name and its value is its configurability (TRUE/FALSE).
|
3029
|
*/
|
3030
|
function language_types() {
|
3031
|
return array_keys(variable_get('language_types', drupal_language_types()));
|
3032
|
}
|
3033
|
|
3034
|
/**
|
3035
|
* Returns a list of installed languages, indexed by the specified key.
|
3036
|
*
|
3037
|
* @param $field
|
3038
|
* (optional) The field to index the list with.
|
3039
|
*
|
3040
|
* @return
|
3041
|
* An associative array, keyed on the values of $field.
|
3042
|
* - If $field is 'weight' or 'enabled', the array is nested, with the outer
|
3043
|
* array's values each being associative arrays with language codes as
|
3044
|
* keys and language objects as values.
|
3045
|
* - For all other values of $field, the array is only one level deep, and
|
3046
|
* the array's values are language objects.
|
3047
|
*/
|
3048
|
function language_list($field = 'language') {
|
3049
|
$languages = &drupal_static(__FUNCTION__);
|
3050
|
// Init language list
|
3051
|
if (!isset($languages)) {
|
3052
|
if (drupal_multilingual() || module_exists('locale')) {
|
3053
|
$languages['language'] = db_query('SELECT * FROM {languages} ORDER BY weight ASC, name ASC')->fetchAllAssoc('language');
|
3054
|
// Users cannot uninstall the native English language. However, we allow
|
3055
|
// it to be hidden from the installed languages. Therefore, at least one
|
3056
|
// other language must be enabled then.
|
3057
|
if (!$languages['language']['en']->enabled && !variable_get('language_native_enabled', TRUE)) {
|
3058
|
unset($languages['language']['en']);
|
3059
|
}
|
3060
|
}
|
3061
|
else {
|
3062
|
// No locale module, so use the default language only.
|
3063
|
$default = language_default();
|
3064
|
$languages['language'][$default->language] = $default;
|
3065
|
}
|
3066
|
}
|
3067
|
|
3068
|
// Return the array indexed by the right field
|
3069
|
if (!isset($languages[$field])) {
|
3070
|
$languages[$field] = array();
|
3071
|
foreach ($languages['language'] as $lang) {
|
3072
|
// Some values should be collected into an array
|
3073
|
if (in_array($field, array('enabled', 'weight'))) {
|
3074
|
$languages[$field][$lang->$field][$lang->language] = $lang;
|
3075
|
}
|
3076
|
else {
|
3077
|
$languages[$field][$lang->$field] = $lang;
|
3078
|
}
|
3079
|
}
|
3080
|
}
|
3081
|
return $languages[$field];
|
3082
|
}
|
3083
|
|
3084
|
/**
|
3085
|
* Returns the default language, as an object, or one of its properties.
|
3086
|
*
|
3087
|
* @param $property
|
3088
|
* (optional) The property of the language object to return.
|
3089
|
*
|
3090
|
* @return
|
3091
|
* Either the language object for the default language used on the site,
|
3092
|
* or the property of that object named in the $property parameter.
|
3093
|
*/
|
3094
|
function language_default($property = NULL) {
|
3095
|
$language = variable_get('language_default', (object) array('language' => 'en', 'name' => 'English', 'native' => 'English', 'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '', 'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => ''));
|
3096
|
return $property ? $language->$property : $language;
|
3097
|
}
|
3098
|
|
3099
|
/**
|
3100
|
* Returns the requested URL path of the page being viewed.
|
3101
|
*
|
3102
|
* Examples:
|
3103
|
* - http://example.com/node/306 returns "node/306".
|
3104
|
* - http://example.com/drupalfolder/node/306 returns "node/306" while
|
3105
|
* base_path() returns "/drupalfolder/".
|
3106
|
* - http://example.com/path/alias (which is a path alias for node/306) returns
|
3107
|
* "path/alias" as opposed to the internal path.
|
3108
|
* - http://example.com/index.php returns an empty string (meaning: front page).
|
3109
|
* - http://example.com/index.php?page=1 returns an empty string.
|
3110
|
*
|
3111
|
* @return
|
3112
|
* The requested Drupal URL path.
|
3113
|
*
|
3114
|
* @see current_path()
|
3115
|
*/
|
3116
|
function request_path() {
|
3117
|
static $path;
|
3118
|
|
3119
|
if (isset($path)) {
|
3120
|
return $path;
|
3121
|
}
|
3122
|
|
3123
|
if (isset($_GET['q']) && is_string($_GET['q'])) {
|
3124
|
// This is a request with a ?q=foo/bar query string. $_GET['q'] is
|
3125
|
// overwritten in drupal_path_initialize(), but request_path() is called
|
3126
|
// very early in the bootstrap process, so the original value is saved in
|
3127
|
// $path and returned in later calls.
|
3128
|
$path = $_GET['q'];
|
3129
|
}
|
3130
|
elseif (isset($_SERVER['REQUEST_URI'])) {
|
3131
|
// This request is either a clean URL, or 'index.php', or nonsense.
|
3132
|
// Extract the path from REQUEST_URI.
|
3133
|
$request_path = strtok($_SERVER['REQUEST_URI'], '?');
|
3134
|
$base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
|
3135
|
// Unescape and strip $base_path prefix, leaving q without a leading slash.
|
3136
|
$path = substr(urldecode($request_path), $base_path_len + 1);
|
3137
|
// If the path equals the script filename, either because 'index.php' was
|
3138
|
// explicitly provided in the URL, or because the server added it to
|
3139
|
// $_SERVER['REQUEST_URI'] even when it wasn't provided in the URL (some
|
3140
|
// versions of Microsoft IIS do this), the front page should be served.
|
3141
|
if ($path == basename($_SERVER['PHP_SELF'])) {
|
3142
|
$path = '';
|
3143
|
}
|
3144
|
}
|
3145
|
else {
|
3146
|
// This is the front page.
|
3147
|
$path = '';
|
3148
|
}
|
3149
|
|
3150
|
// Under certain conditions Apache's RewriteRule directive prepends the value
|
3151
|
// assigned to $_GET['q'] with a slash. Moreover we can always have a trailing
|
3152
|
// slash in place, hence we need to normalize $_GET['q'].
|
3153
|
$path = trim($path, '/');
|
3154
|
|
3155
|
return $path;
|
3156
|
}
|
3157
|
|
3158
|
/**
|
3159
|
* Returns a component of the current Drupal path.
|
3160
|
*
|
3161
|
* When viewing a page at the path "admin/structure/types", for example, arg(0)
|
3162
|
* returns "admin", arg(1) returns "structure", and arg(2) returns "types".
|
3163
|
*
|
3164
|
* Avoid use of this function where possible, as resulting code is hard to
|
3165
|
* read. In menu callback functions, attempt to use named arguments. See the
|
3166
|
* explanation in menu.inc for how to construct callbacks that take arguments.
|
3167
|
* When attempting to use this function to load an element from the current
|
3168
|
* path, e.g. loading the node on a node page, use menu_get_object() instead.
|
3169
|
*
|
3170
|
* @param $index
|
3171
|
* The index of the component, where each component is separated by a '/'
|
3172
|
* (forward-slash), and where the first component has an index of 0 (zero).
|
3173
|
* @param $path
|
3174
|
* A path to break into components. Defaults to the path of the current page.
|
3175
|
*
|
3176
|
* @return
|
3177
|
* The component specified by $index, or NULL if the specified component was
|
3178
|
* not found. If called without arguments, it returns an array containing all
|
3179
|
* the components of the current path.
|
3180
|
*/
|
3181
|
function arg($index = NULL, $path = NULL) {
|
3182
|
// Even though $arguments doesn't need to be resettable for any functional
|
3183
|
// reasons (the result of explode() does not depend on any run-time
|
3184
|
// information), it should be resettable anyway in case a module needs to
|
3185
|
// free up the memory used by it.
|
3186
|
// Use the advanced drupal_static() pattern, since this is called very often.
|
3187
|
static $drupal_static_fast;
|
3188
|
if (!isset($drupal_static_fast)) {
|
3189
|
$drupal_static_fast['arguments'] = &drupal_static(__FUNCTION__);
|
3190
|
}
|
3191
|
$arguments = &$drupal_static_fast['arguments'];
|
3192
|
|
3193
|
if (!isset($path)) {
|
3194
|
$path = $_GET['q'];
|
3195
|
}
|
3196
|
if (!isset($arguments[$path])) {
|
3197
|
$arguments[$path] = explode('/', $path);
|
3198
|
}
|
3199
|
if (!isset($index)) {
|
3200
|
return $arguments[$path];
|
3201
|
}
|
3202
|
if (isset($arguments[$path][$index])) {
|
3203
|
return $arguments[$path][$index];
|
3204
|
}
|
3205
|
}
|
3206
|
|
3207
|
/**
|
3208
|
* Returns the IP address of the client machine.
|
3209
|
*
|
3210
|
* If Drupal is behind a reverse proxy, we use the X-Forwarded-For header
|
3211
|
* instead of $_SERVER['REMOTE_ADDR'], which would be the IP address of
|
3212
|
* the proxy server, and not the client's. The actual header name can be
|
3213
|
* configured by the reverse_proxy_header variable.
|
3214
|
*
|
3215
|
* @return
|
3216
|
* IP address of client machine, adjusted for reverse proxy and/or cluster
|
3217
|
* environments.
|
3218
|
*/
|
3219
|
function ip_address() {
|
3220
|
$ip_address = &drupal_static(__FUNCTION__);
|
3221
|
|
3222
|
if (!isset($ip_address)) {
|
3223
|
$ip_address = $_SERVER['REMOTE_ADDR'];
|
3224
|
|
3225
|
if (variable_get('reverse_proxy', 0)) {
|
3226
|
$reverse_proxy_header = variable_get('reverse_proxy_header', 'HTTP_X_FORWARDED_FOR');
|
3227
|
if (!empty($_SERVER[$reverse_proxy_header])) {
|
3228
|
// If an array of known reverse proxy IPs is provided, then trust
|
3229
|
// the XFF header if request really comes from one of them.
|
3230
|
$reverse_proxy_addresses = variable_get('reverse_proxy_addresses', array());
|
3231
|
|
3232
|
// Turn XFF header into an array.
|
3233
|
$forwarded = explode(',', $_SERVER[$reverse_proxy_header]);
|
3234
|
|
3235
|
// Trim the forwarded IPs; they may have been delimited by commas and spaces.
|
3236
|
$forwarded = array_map('trim', $forwarded);
|
3237
|
|
3238
|
// Tack direct client IP onto end of forwarded array.
|
3239
|
$forwarded[] = $ip_address;
|
3240
|
|
3241
|
// Eliminate all trusted IPs.
|
3242
|
$untrusted = array_diff($forwarded, $reverse_proxy_addresses);
|
3243
|
|
3244
|
if (!empty($untrusted)) {
|
3245
|
// The right-most IP is the most specific we can trust.
|
3246
|
$ip_address = array_pop($untrusted);
|
3247
|
}
|
3248
|
else {
|
3249
|
// All IP addresses in the forwarded array are configured proxy IPs
|
3250
|
// (and thus trusted). We take the leftmost IP.
|
3251
|
$ip_address = array_shift($forwarded);
|
3252
|
}
|
3253
|
}
|
3254
|
}
|
3255
|
}
|
3256
|
|
3257
|
return $ip_address;
|
3258
|
}
|
3259
|
|
3260
|
/**
|
3261
|
* @addtogroup schemaapi
|
3262
|
* @{
|
3263
|
*/
|
3264
|
|
3265
|
/**
|
3266
|
* Gets the schema definition of a table, or the whole database schema.
|
3267
|
*
|
3268
|
* The returned schema will include any modifications made by any
|
3269
|
* module that implements hook_schema_alter(). To get the schema without
|
3270
|
* modifications, use drupal_get_schema_unprocessed().
|
3271
|
*
|
3272
|
*
|
3273
|
* @param $table
|
3274
|
* The name of the table. If not given, the schema of all tables is returned.
|
3275
|
* @param $rebuild
|
3276
|
* If true, the schema will be rebuilt instead of retrieved from the cache.
|
3277
|
*/
|
3278
|
function drupal_get_schema($table = NULL, $rebuild = FALSE) {
|
3279
|
static $schema;
|
3280
|
|
3281
|
if ($rebuild || !isset($table)) {
|
3282
|
$schema = drupal_get_complete_schema($rebuild);
|
3283
|
}
|
3284
|
elseif (!isset($schema)) {
|
3285
|
$schema = new SchemaCache();
|
3286
|
}
|
3287
|
|
3288
|
if (!isset($table)) {
|
3289
|
return $schema;
|
3290
|
}
|
3291
|
if (isset($schema[$table])) {
|
3292
|
return $schema[$table];
|
3293
|
}
|
3294
|
else {
|
3295
|
return FALSE;
|
3296
|
}
|
3297
|
}
|
3298
|
|
3299
|
/**
|
3300
|
* Extends DrupalCacheArray to allow for dynamic building of the schema cache.
|
3301
|
*/
|
3302
|
class SchemaCache extends DrupalCacheArray {
|
3303
|
|
3304
|
/**
|
3305
|
* Constructs a SchemaCache object.
|
3306
|
*/
|
3307
|
public function __construct() {
|
3308
|
// Cache by request method.
|
3309
|
parent::__construct('schema:runtime:' . ($_SERVER['REQUEST_METHOD'] == 'GET'), 'cache');
|
3310
|
}
|
3311
|
|
3312
|
/**
|
3313
|
* Overrides DrupalCacheArray::resolveCacheMiss().
|
3314
|
*/
|
3315
|
protected function resolveCacheMiss($offset) {
|
3316
|
$complete_schema = drupal_get_complete_schema();
|
3317
|
$value = isset($complete_schema[$offset]) ? $complete_schema[$offset] : NULL;
|
3318
|
$this->storage[$offset] = $value;
|
3319
|
$this->persist($offset);
|
3320
|
return $value;
|
3321
|
}
|
3322
|
}
|
3323
|
|
3324
|
/**
|
3325
|
* Gets the whole database schema.
|
3326
|
*
|
3327
|
* The returned schema will include any modifications made by any
|
3328
|
* module that implements hook_schema_alter().
|
3329
|
*
|
3330
|
* @param $rebuild
|
3331
|
* If true, the schema will be rebuilt instead of retrieved from the cache.
|
3332
|
*/
|
3333
|
function drupal_get_complete_schema($rebuild = FALSE) {
|
3334
|
static $schema = array();
|
3335
|
|
3336
|
if (empty($schema) || $rebuild) {
|
3337
|
// Try to load the schema from cache.
|
3338
|
if (!$rebuild && $cached = cache_get('schema')) {
|
3339
|
$schema = $cached->data;
|
3340
|
}
|
3341
|
// Otherwise, rebuild the schema cache.
|
3342
|
else {
|
3343
|
$schema = array();
|
3344
|
// Load the .install files to get hook_schema.
|
3345
|
// On some databases this function may be called before bootstrap has
|
3346
|
// been completed, so we force the functions we need to load just in case.
|
3347
|
if (function_exists('module_load_all_includes')) {
|
3348
|
// This function can be called very early in the bootstrap process, so
|
3349
|
// we force the module_list() cache to be refreshed to ensure that it
|
3350
|
// contains the complete list of modules before we go on to call
|
3351
|
// module_load_all_includes().
|
3352
|
module_list(TRUE);
|
3353
|
module_load_all_includes('install');
|
3354
|
}
|
3355
|
|
3356
|
require_once DRUPAL_ROOT . '/includes/common.inc';
|
3357
|
// Invoke hook_schema for all modules.
|
3358
|
foreach (module_implements('schema') as $module) {
|
3359
|
// Cast the result of hook_schema() to an array, as a NULL return value
|
3360
|
// would cause array_merge() to set the $schema variable to NULL as well.
|
3361
|
// That would break modules which use $schema further down the line.
|
3362
|
$current = (array) module_invoke($module, 'schema');
|
3363
|
// Set 'module' and 'name' keys for each table, and remove descriptions,
|
3364
|
// as they needlessly slow down cache_get() for every single request.
|
3365
|
_drupal_schema_initialize($current, $module);
|
3366
|
$schema = array_merge($schema, $current);
|
3367
|
}
|
3368
|
|
3369
|
drupal_alter('schema', $schema);
|
3370
|
// If the schema is empty, avoid saving it: some database engines require
|
3371
|
// the schema to perform queries, and this could lead to infinite loops.
|
3372
|
if (!empty($schema) && (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL)) {
|
3373
|
cache_set('schema', $schema);
|
3374
|
}
|
3375
|
if ($rebuild) {
|
3376
|
cache_clear_all('schema:', 'cache', TRUE);
|
3377
|
}
|
3378
|
}
|
3379
|
}
|
3380
|
|
3381
|
return $schema;
|
3382
|
}
|
3383
|
|
3384
|
/**
|
3385
|
* @} End of "addtogroup schemaapi".
|
3386
|
*/
|
3387
|
|
3388
|
|
3389
|
/**
|
3390
|
* @addtogroup registry
|
3391
|
* @{
|
3392
|
*/
|
3393
|
|
3394
|
/**
|
3395
|
* Confirms that an interface is available.
|
3396
|
*
|
3397
|
* This function is rarely called directly. Instead, it is registered as an
|
3398
|
* spl_autoload() handler, and PHP calls it for us when necessary.
|
3399
|
*
|
3400
|
* @param $interface
|
3401
|
* The name of the interface to check or load.
|
3402
|
*
|
3403
|
* @return
|
3404
|
* TRUE if the interface is currently available, FALSE otherwise.
|
3405
|
*/
|
3406
|
function drupal_autoload_interface($interface) {
|
3407
|
return _registry_check_code('interface', $interface);
|
3408
|
}
|
3409
|
|
3410
|
/**
|
3411
|
* Confirms that a class is available.
|
3412
|
*
|
3413
|
* This function is rarely called directly. Instead, it is registered as an
|
3414
|
* spl_autoload() handler, and PHP calls it for us when necessary.
|
3415
|
*
|
3416
|
* @param $class
|
3417
|
* The name of the class to check or load.
|
3418
|
*
|
3419
|
* @return
|
3420
|
* TRUE if the class is currently available, FALSE otherwise.
|
3421
|
*/
|
3422
|
function drupal_autoload_class($class) {
|
3423
|
return _registry_check_code('class', $class);
|
3424
|
}
|
3425
|
|
3426
|
/**
|
3427
|
* Confirms that a trait is available.
|
3428
|
*
|
3429
|
* This function is rarely called directly. Instead, it is registered as an
|
3430
|
* spl_autoload() handler, and PHP calls it for us when necessary.
|
3431
|
*
|
3432
|
* @param string $trait
|
3433
|
* The name of the trait to check or load.
|
3434
|
*
|
3435
|
* @return bool
|
3436
|
* TRUE if the trait is currently available, FALSE otherwise.
|
3437
|
*/
|
3438
|
function drupal_autoload_trait($trait) {
|
3439
|
return _registry_check_code('trait', $trait);
|
3440
|
}
|
3441
|
|
3442
|
/**
|
3443
|
* Checks for a resource in the registry.
|
3444
|
*
|
3445
|
* @param $type
|
3446
|
* The type of resource we are looking up, or one of the constants
|
3447
|
* REGISTRY_RESET_LOOKUP_CACHE or REGISTRY_WRITE_LOOKUP_CACHE, which
|
3448
|
* signal that we should reset or write the cache, respectively.
|
3449
|
* @param $name
|
3450
|
* The name of the resource, or NULL if either of the REGISTRY_* constants
|
3451
|
* is passed in.
|
3452
|
*
|
3453
|
* @return
|
3454
|
* TRUE if the resource was found, FALSE if not.
|
3455
|
* NULL if either of the REGISTRY_* constants is passed in as $type.
|
3456
|
*/
|
3457
|
function _registry_check_code($type, $name = NULL) {
|
3458
|
static $lookup_cache, $cache_update_needed;
|
3459
|
|
3460
|
if ($type == 'class' && class_exists($name) || $type == 'interface' && interface_exists($name) || $type == 'trait' && trait_exists($name)) {
|
3461
|
return TRUE;
|
3462
|
}
|
3463
|
|
3464
|
if (!isset($lookup_cache)) {
|
3465
|
$lookup_cache = array();
|
3466
|
if ($cache = cache_get('lookup_cache', 'cache_bootstrap')) {
|
3467
|
$lookup_cache = $cache->data;
|
3468
|
}
|
3469
|
}
|
3470
|
|
3471
|
// When we rebuild the registry, we need to reset this cache so
|
3472
|
// we don't keep lookups for resources that changed during the rebuild.
|
3473
|
if ($type == REGISTRY_RESET_LOOKUP_CACHE) {
|
3474
|
$cache_update_needed = TRUE;
|
3475
|
$lookup_cache = NULL;
|
3476
|
return;
|
3477
|
}
|
3478
|
|
3479
|
// Called from drupal_page_footer, we write to permanent storage if there
|
3480
|
// changes to the lookup cache for this request.
|
3481
|
if ($type == REGISTRY_WRITE_LOOKUP_CACHE) {
|
3482
|
if ($cache_update_needed) {
|
3483
|
cache_set('lookup_cache', $lookup_cache, 'cache_bootstrap');
|
3484
|
}
|
3485
|
return;
|
3486
|
}
|
3487
|
|
3488
|
// $type is either 'interface' or 'class', so we only need the first letter to
|
3489
|
// keep the cache key unique.
|
3490
|
$cache_key = $type[0] . $name;
|
3491
|
if (isset($lookup_cache[$cache_key])) {
|
3492
|
if ($lookup_cache[$cache_key]) {
|
3493
|
include_once DRUPAL_ROOT . '/' . $lookup_cache[$cache_key];
|
3494
|
}
|
3495
|
return (bool) $lookup_cache[$cache_key];
|
3496
|
}
|
3497
|
|
3498
|
// This function may get called when the default database is not active, but
|
3499
|
// there is no reason we'd ever want to not use the default database for
|
3500
|
// this query.
|
3501
|
$file = Database::getConnection('default', 'default')
|
3502
|
->select('registry', 'r', array('target' => 'default'))
|
3503
|
->fields('r', array('filename'))
|
3504
|
// Use LIKE here to make the query case-insensitive.
|
3505
|
->condition('r.name', db_like($name), 'LIKE')
|
3506
|
->condition('r.type', $type)
|
3507
|
->execute()
|
3508
|
->fetchField();
|
3509
|
|
3510
|
// Flag that we've run a lookup query and need to update the cache.
|
3511
|
$cache_update_needed = TRUE;
|
3512
|
|
3513
|
// Misses are valuable information worth caching, so cache even if
|
3514
|
// $file is FALSE.
|
3515
|
$lookup_cache[$cache_key] = $file;
|
3516
|
|
3517
|
if ($file) {
|
3518
|
include_once DRUPAL_ROOT . '/' . $file;
|
3519
|
return TRUE;
|
3520
|
}
|
3521
|
else {
|
3522
|
return FALSE;
|
3523
|
}
|
3524
|
}
|
3525
|
|
3526
|
/**
|
3527
|
* Rescans all enabled modules and rebuilds the registry.
|
3528
|
*
|
3529
|
* Rescans all code in modules or includes directories, storing the location of
|
3530
|
* each interface or class in the database.
|
3531
|
*/
|
3532
|
function registry_rebuild() {
|
3533
|
system_rebuild_module_data();
|
3534
|
registry_update();
|
3535
|
}
|
3536
|
|
3537
|
/**
|
3538
|
* Updates the registry based on the latest files listed in the database.
|
3539
|
*
|
3540
|
* This function should be used when system_rebuild_module_data() does not need
|
3541
|
* to be called, because it is already known that the list of files in the
|
3542
|
* {system} table matches those in the file system.
|
3543
|
*
|
3544
|
* @return
|
3545
|
* TRUE if the registry was rebuilt, FALSE if another thread was rebuilding
|
3546
|
* in parallel and the current thread just waited for completion.
|
3547
|
*
|
3548
|
* @see registry_rebuild()
|
3549
|
*/
|
3550
|
function registry_update() {
|
3551
|
// install_system_module() calls module_enable() which calls into this
|
3552
|
// function during initial system installation, so the lock system is neither
|
3553
|
// loaded nor does its storage exist yet.
|
3554
|
$in_installer = drupal_installation_attempted();
|
3555
|
if (!$in_installer && !lock_acquire(__FUNCTION__)) {
|
3556
|
// Another request got the lock, wait for it to finish.
|
3557
|
lock_wait(__FUNCTION__);
|
3558
|
return FALSE;
|
3559
|
}
|
3560
|
|
3561
|
require_once DRUPAL_ROOT . '/includes/registry.inc';
|
3562
|
_registry_update();
|
3563
|
|
3564
|
if (!$in_installer) {
|
3565
|
lock_release(__FUNCTION__);
|
3566
|
}
|
3567
|
return TRUE;
|
3568
|
}
|
3569
|
|
3570
|
/**
|
3571
|
* @} End of "addtogroup registry".
|
3572
|
*/
|
3573
|
|
3574
|
/**
|
3575
|
* Provides central static variable storage.
|
3576
|
*
|
3577
|
* All functions requiring a static variable to persist or cache data within
|
3578
|
* a single page request are encouraged to use this function unless it is
|
3579
|
* absolutely certain that the static variable will not need to be reset during
|
3580
|
* the page request. By centralizing static variable storage through this
|
3581
|
* function, other functions can rely on a consistent API for resetting any
|
3582
|
* other function's static variables.
|
3583
|
*
|
3584
|
* Example:
|
3585
|
* @code
|
3586
|
* function language_list($field = 'language') {
|
3587
|
* $languages = &drupal_static(__FUNCTION__);
|
3588
|
* if (!isset($languages)) {
|
3589
|
* // If this function is being called for the first time after a reset,
|
3590
|
* // query the database and execute any other code needed to retrieve
|
3591
|
* // information about the supported languages.
|
3592
|
* ...
|
3593
|
* }
|
3594
|
* if (!isset($languages[$field])) {
|
3595
|
* // If this function is being called for the first time for a particular
|
3596
|
* // index field, then execute code needed to index the information already
|
3597
|
* // available in $languages by the desired field.
|
3598
|
* ...
|
3599
|
* }
|
3600
|
* // Subsequent invocations of this function for a particular index field
|
3601
|
* // skip the above two code blocks and quickly return the already indexed
|
3602
|
* // information.
|
3603
|
* return $languages[$field];
|
3604
|
* }
|
3605
|
* function locale_translate_overview_screen() {
|
3606
|
* // When building the content for the translations overview page, make
|
3607
|
* // sure to get completely fresh information about the supported languages.
|
3608
|
* drupal_static_reset('language_list');
|
3609
|
* ...
|
3610
|
* }
|
3611
|
* @endcode
|
3612
|
*
|
3613
|
* In a few cases, a function can have certainty that there is no legitimate
|
3614
|
* use-case for resetting that function's static variable. This is rare,
|
3615
|
* because when writing a function, it's hard to forecast all the situations in
|
3616
|
* which it will be used. A guideline is that if a function's static variable
|
3617
|
* does not depend on any information outside of the function that might change
|
3618
|
* during a single page request, then it's ok to use the "static" keyword
|
3619
|
* instead of the drupal_static() function.
|
3620
|
*
|
3621
|
* Example:
|
3622
|
* @code
|
3623
|
* function actions_do(...) {
|
3624
|
* // $stack tracks the number of recursive calls.
|
3625
|
* static $stack;
|
3626
|
* $stack++;
|
3627
|
* if ($stack > variable_get('actions_max_stack', 35)) {
|
3628
|
* ...
|
3629
|
* return;
|
3630
|
* }
|
3631
|
* ...
|
3632
|
* $stack--;
|
3633
|
* }
|
3634
|
* @endcode
|
3635
|
*
|
3636
|
* In a few cases, a function needs a resettable static variable, but the
|
3637
|
* function is called many times (100+) during a single page request, so
|
3638
|
* every microsecond of execution time that can be removed from the function
|
3639
|
* counts. These functions can use a more cumbersome, but faster variant of
|
3640
|
* calling drupal_static(). It works by storing the reference returned by
|
3641
|
* drupal_static() in the calling function's own static variable, thereby
|
3642
|
* removing the need to call drupal_static() for each iteration of the function.
|
3643
|
* Conceptually, it replaces:
|
3644
|
* @code
|
3645
|
* $foo = &drupal_static(__FUNCTION__);
|
3646
|
* @endcode
|
3647
|
* with:
|
3648
|
* @code
|
3649
|
* // Unfortunately, this does not work.
|
3650
|
* static $foo = &drupal_static(__FUNCTION__);
|
3651
|
* @endcode
|
3652
|
* However, the above line of code does not work, because PHP only allows static
|
3653
|
* variables to be initializied by literal values, and does not allow static
|
3654
|
* variables to be assigned to references.
|
3655
|
* - http://php.net/manual/language.variables.scope.php#language.variables.scope.static
|
3656
|
* - http://php.net/manual/language.variables.scope.php#language.variables.scope.references
|
3657
|
* The example below shows the syntax needed to work around both limitations.
|
3658
|
* For benchmarks and more information, see http://drupal.org/node/619666.
|
3659
|
*
|
3660
|
* Example:
|
3661
|
* @code
|
3662
|
* function user_access($string, $account = NULL) {
|
3663
|
* // Use the advanced drupal_static() pattern, since this is called very often.
|
3664
|
* static $drupal_static_fast;
|
3665
|
* if (!isset($drupal_static_fast)) {
|
3666
|
* $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
|
3667
|
* }
|
3668
|
* $perm = &$drupal_static_fast['perm'];
|
3669
|
* ...
|
3670
|
* }
|
3671
|
* @endcode
|
3672
|
*
|
3673
|
* @param $name
|
3674
|
* Globally unique name for the variable. For a function with only one static,
|
3675
|
* variable, the function name (e.g. via the PHP magic __FUNCTION__ constant)
|
3676
|
* is recommended. For a function with multiple static variables add a
|
3677
|
* distinguishing suffix to the function name for each one.
|
3678
|
* @param $default_value
|
3679
|
* Optional default value.
|
3680
|
* @param $reset
|
3681
|
* TRUE to reset one or all variables(s). This parameter is only used
|
3682
|
* internally and should not be passed in; use drupal_static_reset() instead.
|
3683
|
* (This function's return value should not be used when TRUE is passed in.)
|
3684
|
*
|
3685
|
* @return
|
3686
|
* Returns a variable by reference.
|
3687
|
*
|
3688
|
* @see drupal_static_reset()
|
3689
|
*/
|
3690
|
function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
|
3691
|
static $data = array(), $default = array();
|
3692
|
// First check if dealing with a previously defined static variable.
|
3693
|
if (isset($data[$name]) || array_key_exists($name, $data)) {
|
3694
|
// Non-NULL $name and both $data[$name] and $default[$name] statics exist.
|
3695
|
if ($reset) {
|
3696
|
// Reset pre-existing static variable to its default value.
|
3697
|
$data[$name] = $default[$name];
|
3698
|
}
|
3699
|
return $data[$name];
|
3700
|
}
|
3701
|
// Neither $data[$name] nor $default[$name] static variables exist.
|
3702
|
if (isset($name)) {
|
3703
|
if ($reset) {
|
3704
|
// Reset was called before a default is set and yet a variable must be
|
3705
|
// returned.
|
3706
|
return $data;
|
3707
|
}
|
3708
|
// First call with new non-NULL $name. Initialize a new static variable.
|
3709
|
$default[$name] = $data[$name] = $default_value;
|
3710
|
return $data[$name];
|
3711
|
}
|
3712
|
// Reset all: ($name == NULL). This needs to be done one at a time so that
|
3713
|
// references returned by earlier invocations of drupal_static() also get
|
3714
|
// reset.
|
3715
|
foreach ($default as $name => $value) {
|
3716
|
$data[$name] = $value;
|
3717
|
}
|
3718
|
// As the function returns a reference, the return should always be a
|
3719
|
// variable.
|
3720
|
return $data;
|
3721
|
}
|
3722
|
|
3723
|
/**
|
3724
|
* Resets one or all centrally stored static variable(s).
|
3725
|
*
|
3726
|
* @param $name
|
3727
|
* Name of the static variable to reset. Omit to reset all variables.
|
3728
|
* Resetting all variables should only be used, for example, for running unit
|
3729
|
* tests with a clean environment.
|
3730
|
*/
|
3731
|
function drupal_static_reset($name = NULL) {
|
3732
|
drupal_static($name, NULL, TRUE);
|
3733
|
}
|
3734
|
|
3735
|
/**
|
3736
|
* Detects whether the current script is running in a command-line environment.
|
3737
|
*/
|
3738
|
function drupal_is_cli() {
|
3739
|
return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
|
3740
|
}
|
3741
|
|
3742
|
/**
|
3743
|
* Formats text for emphasized display in a placeholder inside a sentence.
|
3744
|
*
|
3745
|
* Used automatically by format_string().
|
3746
|
*
|
3747
|
* @param $text
|
3748
|
* The text to format (plain-text).
|
3749
|
*
|
3750
|
* @return
|
3751
|
* The formatted text (html).
|
3752
|
*/
|
3753
|
function drupal_placeholder($text) {
|
3754
|
return '<em class="placeholder">' . check_plain($text) . '</em>';
|
3755
|
}
|
3756
|
|
3757
|
/**
|
3758
|
* Registers a function for execution on shutdown.
|
3759
|
*
|
3760
|
* Wrapper for register_shutdown_function() that catches thrown exceptions to
|
3761
|
* avoid "Exception thrown without a stack frame in Unknown".
|
3762
|
*
|
3763
|
* @param $callback
|
3764
|
* The shutdown function to register.
|
3765
|
* @param ...
|
3766
|
* Additional arguments to pass to the shutdown function.
|
3767
|
*
|
3768
|
* @return
|
3769
|
* Array of shutdown functions to be executed.
|
3770
|
*
|
3771
|
* @see register_shutdown_function()
|
3772
|
* @ingroup php_wrappers
|
3773
|
*/
|
3774
|
function &drupal_register_shutdown_function($callback = NULL) {
|
3775
|
// We cannot use drupal_static() here because the static cache is reset during
|
3776
|
// batch processing, which breaks batch handling.
|
3777
|
static $callbacks = array();
|
3778
|
|
3779
|
if (isset($callback)) {
|
3780
|
// Only register the internal shutdown function once.
|
3781
|
if (empty($callbacks)) {
|
3782
|
register_shutdown_function('_drupal_shutdown_function');
|
3783
|
}
|
3784
|
$args = func_get_args();
|
3785
|
array_shift($args);
|
3786
|
// Save callback and arguments
|
3787
|
$callbacks[] = array('callback' => $callback, 'arguments' => $args);
|
3788
|
}
|
3789
|
return $callbacks;
|
3790
|
}
|
3791
|
|
3792
|
/**
|
3793
|
* Executes registered shutdown functions.
|
3794
|
*/
|
3795
|
function _drupal_shutdown_function() {
|
3796
|
$callbacks = &drupal_register_shutdown_function();
|
3797
|
|
3798
|
// Set the CWD to DRUPAL_ROOT as it is not guaranteed to be the same as it
|
3799
|
// was in the normal context of execution.
|
3800
|
chdir(DRUPAL_ROOT);
|
3801
|
|
3802
|
try {
|
3803
|
// Manually iterate over the array instead of using a foreach loop.
|
3804
|
// A foreach operates on a copy of the array, so any shutdown functions that
|
3805
|
// were added from other shutdown functions would never be called.
|
3806
|
while ($callback = current($callbacks)) {
|
3807
|
call_user_func_array($callback['callback'], $callback['arguments']);
|
3808
|
next($callbacks);
|
3809
|
}
|
3810
|
}
|
3811
|
catch (Exception $exception) {
|
3812
|
// If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
|
3813
|
require_once DRUPAL_ROOT . '/includes/errors.inc';
|
3814
|
if (error_displayable()) {
|
3815
|
print '<h1>Uncaught exception thrown in shutdown function.</h1>';
|
3816
|
print '<p>' . _drupal_render_exception_safe($exception) . '</p><hr />';
|
3817
|
}
|
3818
|
}
|
3819
|
}
|
3820
|
|
3821
|
/**
|
3822
|
* Compares the memory required for an operation to the available memory.
|
3823
|
*
|
3824
|
* @param $required
|
3825
|
* The memory required for the operation, expressed as a number of bytes with
|
3826
|
* optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8bytes,
|
3827
|
* 9mbytes).
|
3828
|
* @param $memory_limit
|
3829
|
* (optional) The memory limit for the operation, expressed as a number of
|
3830
|
* bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G,
|
3831
|
* 6GiB, 8bytes, 9mbytes). If no value is passed, the current PHP
|
3832
|
* memory_limit will be used. Defaults to NULL.
|
3833
|
*
|
3834
|
* @return
|
3835
|
* TRUE if there is sufficient memory to allow the operation, or FALSE
|
3836
|
* otherwise.
|
3837
|
*/
|
3838
|
function drupal_check_memory_limit($required, $memory_limit = NULL) {
|
3839
|
if (!isset($memory_limit)) {
|
3840
|
$memory_limit = ini_get('memory_limit');
|
3841
|
}
|
3842
|
|
3843
|
// There is sufficient memory if:
|
3844
|
// - No memory limit is set.
|
3845
|
// - The memory limit is set to unlimited (-1).
|
3846
|
// - The memory limit is greater than the memory required for the operation.
|
3847
|
return ((!$memory_limit) || ($memory_limit == -1) || (parse_size($memory_limit) >= parse_size($required)));
|
3848
|
}
|
3849
|
|
3850
|
/**
|
3851
|
* Invalidates a PHP file from any active opcode caches.
|
3852
|
*
|
3853
|
* If the opcode cache does not support the invalidation of individual files,
|
3854
|
* the entire cache will be flushed.
|
3855
|
*
|
3856
|
* @param string $filepath
|
3857
|
* The absolute path of the PHP file to invalidate.
|
3858
|
*/
|
3859
|
function drupal_clear_opcode_cache($filepath) {
|
3860
|
if (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50300) {
|
3861
|
// Below PHP 5.3, clearstatcache does not accept any function parameters.
|
3862
|
clearstatcache();
|
3863
|
}
|
3864
|
else {
|
3865
|
clearstatcache(TRUE, $filepath);
|
3866
|
}
|
3867
|
|
3868
|
// Zend OPcache.
|
3869
|
if (function_exists('opcache_invalidate')) {
|
3870
|
opcache_invalidate($filepath, TRUE);
|
3871
|
}
|
3872
|
// APC.
|
3873
|
if (function_exists('apc_delete_file')) {
|
3874
|
// apc_delete_file() throws a PHP warning in case the specified file was
|
3875
|
// not compiled yet.
|
3876
|
// @see http://php.net/apc-delete-file
|
3877
|
@apc_delete_file($filepath);
|
3878
|
}
|
3879
|
}
|