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