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