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