2 // $Id: bootstrap.inc 144 2007-03-28 07:52:20Z thierry $
6 * Functions that need to be loaded on every Drupal request.
9 define('CACHE_PERMANENT', 0);
10 define('CACHE_TEMPORARY', -1);
12 define('CACHE_DISABLED', 0);
13 define('CACHE_ENABLED', 1);
15 define('WATCHDOG_NOTICE', 0);
16 define('WATCHDOG_WARNING', 1);
17 define('WATCHDOG_ERROR', 2);
19 define('DRUPAL_BOOTSTRAP_DATABASE', 0);
20 define('DRUPAL_BOOTSTRAP_SESSION', 1);
21 define('DRUPAL_BOOTSTRAP_PAGE_CACHE', 2);
22 define('DRUPAL_BOOTSTRAP_PATH', 3);
23 define('DRUPAL_BOOTSTRAP_FULL', 4);
25 // these values should match the'role' table
26 define('DRUPAL_ANONYMOUS_RID', 1);
27 define('DRUPAL_AUTHENTICATED_RID', 2);
30 * Start the timer with the specified name. If you start and stop
31 * the same timer multiple times, the measured intervals will be
35 * The name of the timer.
37 function timer_start($name) {
40 list($usec, $sec) = explode(' ', microtime());
41 $timers[$name]['start'] = (float)$usec + (float)$sec;
42 $timers[$name]['count'] = isset($timers[$name]['count']) ? ++$timers[$name]['count'] : 1;
46 * Read the current timer value without stopping the timer.
49 * The name of the timer.
51 * The current timer value in ms.
53 function timer_read($name) {
56 list($usec, $sec) = explode(' ', microtime());
57 $stop = (float)$usec + (float)$sec;
58 $diff = round(($stop - $timers[$name]['start']) * 1000, 2);
60 return $timers[$name]['time'] + $diff;
64 * Stop the timer with the specified name.
67 * The name of the timer.
69 * A timer array. The array contains the number of times the
70 * timer has been started and stopped (count) and the accumulated
71 * timer value in ms (time).
73 function timer_stop($name) {
76 $timers[$name]['time'] = timer_read($name);
77 unset($timers[$name]['start']);
79 return $timers[$name];
83 * Find the appropriate configuration directory.
85 * Try finding a matching configuration directory by stripping the website's
86 * hostname from left to right and pathname from right to left. The first
87 * configuration file found will be used, the remaining will ignored. If no
88 * configuration file is found, return a default value '$confdir/default'.
90 * Example for a fictitious site installed at
91 * http://www.drupal.org:8080/mysite/test/ the 'settings.php' is searched in
92 * the following directories:
94 * 1. $confdir/8080.www.drupal.org.mysite.test
95 * 2. $confdir/www.drupal.org.mysite.test
96 * 3. $confdir/drupal.org.mysite.test
97 * 4. $confdir/org.mysite.test
99 * 5. $confdir/8080.www.drupal.org.mysite
100 * 6. $confdir/www.drupal.org.mysite
101 * 7. $confdir/drupal.org.mysite
102 * 8. $confdir/org.mysite
104 * 9. $confdir/8080.www.drupal.org
105 * 10. $confdir/www.drupal.org
106 * 11. $confdir/drupal.org
109 * 13. $confdir/default
111 function conf_path() {
119 $uri = explode('/', $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_FILENAME']);
120 $server = explode('.', implode('.', array_reverse(explode(':', rtrim($_SERVER['HTTP_HOST'], '.')))));
121 for ($i = count($uri) - 1; $i > 0; $i--) {
122 for ($j = count($server); $j > 0; $j--) {
123 $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
124 if (file_exists("$confdir/$dir/settings.php")) {
125 $conf = "$confdir/$dir";
130 $conf = "$confdir/default";
135 * Unsets all disallowed global variables. See $allowed for what's allowed.
137 function drupal_unset_globals() {
138 if (ini_get('register_globals')) {
139 $allowed = array('_ENV' => 1, '_GET' => 1, '_POST' => 1, '_COOKIE' => 1, '_FILES' => 1, '_SERVER' => 1, '_REQUEST' => 1, 'access_check' => 1, 'GLOBALS' => 1);
140 foreach ($GLOBALS as $key => $value) {
141 if (!isset($allowed[$key])) {
142 unset($GLOBALS[$key]);
149 * Loads the configuration and sets the base URL correctly.
151 function conf_init() {
152 global $db_url, $db_prefix, $base_url, $base_path, $base_root, $conf;
154 require_once './'. conf_path() .'/settings.php';
156 if (isset($base_url)) {
157 // Parse fixed base URL from settings.php.
158 $parts = parse_url($base_url);
159 if (!isset($parts['path'])) {
162 $base_path = $parts['path'] . '/';
163 // Build $base_root (everything until first slash after "scheme://").
164 $base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
168 $base_root = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
169 $base_url = $base_root .= '://'. $_SERVER['HTTP_HOST'];
170 if ($dir = trim(dirname($_SERVER['SCRIPT_NAME']), '\,/')) {
171 $base_path = "/$dir";
172 $base_url .= $base_path;
182 * Returns and optionally sets the filename for a system item (module,
183 * theme, etc.). The filename, whether provided, cached, or retrieved
184 * from the database, is only returned if the file exists.
187 * The type of the item (i.e. theme, theme_engine, module).
189 * The name of the item for which the filename is requested.
191 * The filename of the item if it is to be set explicitly rather
192 * than by consulting the database.
195 * The filename of the requested item.
197 function drupal_get_filename($type, $name, $filename = NULL) {
198 static $files = array();
200 if (!isset($files[$type])) {
201 $files[$type] = array();
204 if (!empty($filename) && file_exists($filename)) {
205 $files[$type][$name] = $filename;
207 elseif (isset($files[$type][$name])) {
210 elseif (($file = db_result(db_query("SELECT filename FROM {system} WHERE name = '%s' AND type = '%s'", $name, $type))) && file_exists($file)) {
211 $files[$type][$name] = $file;
214 $config = conf_path();
215 $dir = (($type == 'theme_engine') ? 'themes/engines' : "${type}s");
216 $file = (($type == 'theme_engine') ? "$name.engine" : "$name.$type");
218 foreach (array("$config/$dir/$file", "$config/$dir/$name/$file", "$dir/$file", "$dir/$name/$file") as $file) {
219 if (file_exists($file)) {
220 $files[$type][$name] = $file;
226 return $files[$type][$name];
230 * Load the persistent variable table.
232 * The variable table is composed of values that have been saved in the table
233 * with variable_set() as well as those explicitly specified in the configuration
236 function variable_init($conf = array()) {
237 // NOTE: caching the variables improves performance with 20% when serving cached pages.
238 if ($cached = cache_get('variables')) {
239 $variables = unserialize($cached->data);
242 $result = db_query('SELECT * FROM {variable}');
243 while ($variable = db_fetch_object($result)) {
244 $variables[$variable->name] = unserialize($variable->value);
246 cache_set('variables', serialize($variables));
249 foreach ($conf as $name => $value) {
250 $variables[$name] = $value;
257 * Return a persistent variable.
260 * The name of the variable to return.
262 * The default value to use if this variable has never been set.
264 * The value of the variable.
266 function variable_get($name, $default) {
269 return isset($conf[$name]) ? $conf[$name] : $default;
273 * Set a persistent variable.
276 * The name of the variable to set.
278 * The value to set. This can be any PHP data type; these functions take care
279 * of serialization as necessary.
281 function variable_set($name, $value) {
284 db_lock_table('variable');
285 db_query("DELETE FROM {variable} WHERE name = '%s'", $name);
286 db_query("INSERT INTO {variable} (name, value) VALUES ('%s', '%s')", $name, serialize($value));
289 cache_clear_all('variables');
291 $conf[$name] = $value;
295 * Unset a persistent variable.
298 * The name of the variable to undefine.
300 function variable_del($name) {
303 db_query("DELETE FROM {variable} WHERE name = '%s'", $name);
304 cache_clear_all('variables');
310 * Return data from the persistent cache.
313 * The cache ID of the data to retrieve.
315 function cache_get($key) {
318 // Garbage collection necessary when enforcing a minimum cache lifetime
319 $cache_flush = variable_get('cache_flush', 0);
320 if ($cache_flush && ($cache_flush + variable_get('cache_lifetime', 0) <= time())) {
321 // Time to flush old cache data
322 db_query("DELETE FROM {cache} WHERE expire != %d AND expire <= %d", CACHE_PERMANENT, $cache_flush);
323 variable_set('cache_flush', 0);
326 $cache = db_fetch_object(db_query("SELECT data, created, headers, expire FROM {cache} WHERE cid = '%s'", $key));
327 if (isset($cache->data)) {
328 // If the data is permanent or we're not enforcing a minimum cache lifetime
329 // always return the cached data.
330 if ($cache->expire == CACHE_PERMANENT || !variable_get('cache_lifetime', 0)) {
331 $cache->data = db_decode_blob($cache->data);
333 // If enforcing a minimum cache lifetime, validate that the data is
334 // currently valid for this user before we return it by making sure the
335 // cache entry was created before the timestamp in the current session's
336 // cache timer. The cache variable is loaded into the $user object by
337 // sess_read() in session.inc.
339 if (isset($user->cache) && ($user->cache > $cache->created)) {
340 // This cache data is too old and thus not valid for us, ignore it.
344 $cache->data = db_decode_blob($cache->data);
353 * Store data in the persistent cache.
356 * The cache ID of the data to store.
358 * The data to store in the cache. Complex data types must be serialized first.
360 * One of the following values:
361 * - CACHE_PERMANENT: Indicates that the item should never be removed unless
362 * explicitly told to using cache_clear_all() with a cache ID.
363 * - CACHE_TEMPORARY: Indicates that the item should be removed at the next
364 * general cache wipe.
365 * - A Unix timestamp: Indicates that the item should be kept at least until
366 * the given time, after which it behaves like CACHE_TEMPORARY.
368 * A string containing HTTP header information for cached pages.
370 function cache_set($cid, $data, $expire = CACHE_PERMANENT, $headers = NULL) {
371 db_lock_table('cache');
372 db_query("UPDATE {cache} SET data = %b, created = %d, expire = %d, headers = '%s' WHERE cid = '%s'", $data, time(), $expire, $headers, $cid);
373 if (!db_affected_rows()) {
374 @db_query("INSERT INTO {cache} (cid, data, created, expire, headers) VALUES ('%s', %b, %d, %d, '%s')", $cid, $data, time(), $expire, $headers);
380 * Expire data from the cache.
383 * If set, the cache ID to delete. Otherwise, all cache entries that can
384 * expire are deleted.
387 * If set to true, the $cid is treated as a substring to match rather than a
390 function cache_clear_all($cid = NULL, $wildcard = false) {
394 if (variable_get('cache_lifetime', 0)) {
395 // We store the time in the current user's $user->cache variable which
396 // will be saved into the sessions table by sess_write(). We then
397 // simulate that the cache was flushed for this user by not returning
398 // cached data that was cached before the timestamp.
399 $user->cache = time();
401 $cache_flush = variable_get('cache_flush', 0);
402 if ($cache_flush == 0) {
403 // This is the first request to clear the cache, start a timer.
404 variable_set('cache_flush', time());
406 else if (time() > ($cache_flush + variable_get('cache_lifetime', 0))) {
407 // Clear the cache for everyone, cache_flush_delay seconds have
408 // passed since the first request to clear the cache.
409 db_query("DELETE FROM {cache} WHERE expire != %d AND expire < %d", CACHE_PERMANENT, time());
410 variable_set('cache_flush', 0);
414 // No minimum cache lifetime, flush all temporary cache entries now.
415 db_query("DELETE FROM {cache} WHERE expire != %d AND expire < %d", CACHE_PERMANENT, time());
420 db_query("DELETE FROM {cache} WHERE cid LIKE '%%%s%%'", $cid);
423 db_query("DELETE FROM {cache} WHERE cid = '%s'", $cid);
429 * Retrieve the current page from the cache.
431 * Note, we do not serve cached pages when status messages are waiting (from
432 * a redirected form submission which was completed).
433 * Because the output handler is not activated, the resulting page will not
436 function page_get_cache() {
437 global $user, $base_root;
441 if (!$user->uid && $_SERVER['REQUEST_METHOD'] == 'GET' && count(drupal_set_message()) == 0) {
442 $cache = cache_get($base_root . request_uri());
453 * Call all init or exit hooks without including all modules.
456 * The name of the bootstrap hook we wish to invoke.
458 function bootstrap_invoke_all($hook) {
459 foreach (module_list(FALSE, TRUE) as $module) {
460 drupal_load('module', $module);
461 module_invoke($module, $hook);
466 * Includes a file with the provided type and name. This prevents
467 * including a theme, engine, module, etc., more than once.
470 * The type of item to load (i.e. theme, theme_engine, module).
472 * The name of the item to load.
475 * TRUE if the item is loaded or has already been loaded.
477 function drupal_load($type, $name) {
478 static $files = array();
480 if (isset($files[$type][$name])) {
484 $filename = drupal_get_filename($type, $name);
487 include_once "./$filename";
488 $files[$type][$name] = TRUE;
497 * Set HTTP headers in preparation for a page response.
499 * @see page_set_cache
501 function drupal_page_header() {
502 if (variable_get('cache', 0) && $cache = page_get_cache()) {
503 bootstrap_invoke_all('init');
504 // Set default values:
505 $date = gmdate('D, d M Y H:i:s', $cache->created) .' GMT';
506 $etag = '"'. md5($date) .'"';
508 // Check http headers:
509 $modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] == $date : NULL;
510 if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && ($timestamp = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) > 0) {
511 $modified_since = $cache->created <= $timestamp;
514 $modified_since = NULL;
516 $none_match = !empty($_SERVER['HTTP_IF_NONE_MATCH']) ? $_SERVER['HTTP_IF_NONE_MATCH'] == $etag : NULL;
518 // The type checking here is very important, be careful when changing entries.
519 if (($modified_since !== NULL || $none_match !== NULL) && $modified_since !== false && $none_match !== false) {
520 header('HTTP/1.0 304 Not Modified');
524 // Send appropriate response:
525 header("Last-Modified: $date");
526 header("ETag: $etag");
528 // Determine if the browser accepts gzipped data.
529 if (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === false && function_exists('gzencode')) {
530 // Strip the gzip header and run uncompress.
531 $cache->data = gzinflate(substr(substr($cache->data, 10), 0, -8));
533 elseif (function_exists('gzencode')) {
534 header('Content-Encoding: gzip');
537 // Send the original request's headers. We send them one after
538 // another so PHP's header() function can deal with duplicate
540 $headers = explode("\n", $cache->headers);
541 foreach ($headers as $header) {
546 bootstrap_invoke_all('exit');
550 header("Expires: Sun, 19 Nov 1978 05:00:00 GMT");
551 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
552 header("Cache-Control: no-store, no-cache, must-revalidate");
553 header("Cache-Control: post-check=0, pre-check=0", false);
554 header("Pragma: no-cache");
559 * Define the critical hooks that force modules to always be loaded.
561 function bootstrap_hooks() {
562 return array('init', 'exit');
566 * Unserializes and appends elements from a serialized string.
569 * The object to which the elements are appended.
571 * The attribute of $obj whose value should be unserialized.
573 function drupal_unpack($obj, $field = 'data') {
574 if ($obj->$field && $data = unserialize($obj->$field)) {
575 foreach ($data as $key => $value) {
576 if (!isset($obj->$key)) {
585 * Return the URI of the referring page.
587 function referer_uri() {
588 if (isset($_SERVER['HTTP_REFERER'])) {
589 return $_SERVER['HTTP_REFERER'];
594 * Encode special characters in a plain-text string for display as HTML.
596 function check_plain($text) {
597 return htmlspecialchars($text, ENT_QUOTES);
601 * Since request_uri() is only available on Apache, we generate an
602 * equivalent using other environment variables.
604 function request_uri() {
606 if (isset($_SERVER['REQUEST_URI'])) {
607 $uri = $_SERVER['REQUEST_URI'];
610 if (isset($_SERVER['argv'])) {
611 $uri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['argv'][0];
614 $uri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
622 * Log a system message.
625 * The category to which this message belongs.
627 * The message to store in the log.
629 * The severity of the message. One of the following values:
634 * A link to associate with the message.
636 function watchdog($type, $message, $severity = WATCHDOG_NOTICE, $link = NULL) {
637 global $user, $base_root;
639 $current_db = db_set_active();
641 // Note: log the exact, entire absolute URL.
642 $request_uri = $base_root . request_uri();
644 db_query("INSERT INTO {watchdog} (uid, type, message, severity, link, location, referer, hostname, timestamp) VALUES (%d, '%s', '%s', %d, '%s', '%s', '%s', '%s', %d)", $user->uid, $type, $message, $severity, $link, $request_uri, referer_uri(), $_SERVER['REMOTE_ADDR'], time());
647 db_set_active($current_db);
652 * Set a message which reflects the status of the performed operation.
654 * If the function is called with no arguments, this function returns all set
655 * messages without clearing them.
658 * The message should begin with a capital letter and always ends with a
661 * The type of the message. One of the following values are possible:
665 function drupal_set_message($message = NULL, $type = 'status') {
667 if (!isset($_SESSION['messages'])) {
668 $_SESSION['messages'] = array();
671 if (!isset($_SESSION['messages'][$type])) {
672 $_SESSION['messages'][$type] = array();
675 $_SESSION['messages'][$type][] = $message;
678 // messages not set when DB connection fails
679 return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
683 * Return all messages that have been set.
685 * As a side effect, this function clears the message queue.
687 function drupal_get_messages() {
688 if ($messages = drupal_set_message()) {
689 unset($_SESSION['messages']);
696 * Perform an access check for a given mask and rule type. Rules are usually created via admin/access/rules page.
698 function drupal_is_denied($type, $mask) {
699 $allow = db_fetch_object(db_query("SELECT * FROM {access} WHERE status = 1 AND type = '%s' AND LOWER('%s') LIKE LOWER(mask)", $type, $mask));
700 $deny = db_fetch_object(db_query("SELECT * FROM {access} WHERE status = 0 AND type = '%s' AND LOWER('%s') LIKE LOWER(mask)", $type, $mask));
702 return $deny && !$allow;
706 * A string describing a phase of Drupal to load. Each phase adds to the
707 * previous one, so invoking a later phase automatically runs the earlier
708 * phases too. The most important usage is that if you want to access
709 * Drupal database from a script without loading anything else, you can
710 * include bootstrap.inc, and call drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE).
713 * A constant. Allowed values are:
714 * DRUPAL_BOOTSTRAP_DATABASE: initialize database layer.
715 * DRUPAL_BOOTSTRAP_SESSION: initialize session handling.
716 * DRUPAL_BOOTSTRAP_PAGE_CACHE: load bootstrap.inc and module.inc, start
717 * the variable system and try to serve a page from the cache.
718 * DRUPAL_BOOTSTRAP_FULL: Drupal is fully loaded, validate and fix input
721 function drupal_bootstrap($phase) {
722 static $phases = array(DRUPAL_BOOTSTRAP_DATABASE, DRUPAL_BOOTSTRAP_SESSION, DRUPAL_BOOTSTRAP_PAGE_CACHE, DRUPAL_BOOTSTRAP_PATH, DRUPAL_BOOTSTRAP_FULL);
724 while (!is_null($current_phase = array_shift($phases))) {
725 _drupal_bootstrap($current_phase);
726 if ($phase == $current_phase) {
732 function _drupal_bootstrap($phase) {
736 case DRUPAL_BOOTSTRAP_DATABASE:
737 drupal_unset_globals();
738 // Initialize the configuration
740 // Initialize the default database.
741 require_once './includes/database.inc';
745 case DRUPAL_BOOTSTRAP_SESSION:
746 require_once './includes/session.inc';
747 session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
751 case DRUPAL_BOOTSTRAP_PAGE_CACHE:
752 require_once './includes/module.inc';
753 // Start a page timer:
756 // deny access to hosts which were banned. t() is not yet available.
757 if (drupal_is_denied('host', $_SERVER['REMOTE_ADDR'])) {
758 header('HTTP/1.0 403 Forbidden');
759 print 'Sorry, '. $_SERVER['REMOTE_ADDR']. ' has been banned.';
763 // Initialize configuration variables, using values from conf.php if available.
764 $conf = variable_init(isset($conf) ? $conf : array());
765 drupal_page_header();
768 case DRUPAL_BOOTSTRAP_PATH:
769 require_once './includes/path.inc';
770 // Initialize $_GET['q'] prior to loading modules and invoking hook_init().
774 case DRUPAL_BOOTSTRAP_FULL:
775 require_once './includes/common.inc';
776 _drupal_bootstrap_full();
782 * Enables use of the theme system without requiring database access. Since
783 * there is not database access no theme will be enabled and the default
784 * themeable functions will be called. Some themeable functions can not be used
785 * without the full Drupal API loaded. For example, theme_page() is
786 * unavailable and theme_maintenance_page() must be used in its place.
788 function drupal_maintenance_theme() {
790 require_once './includes/path.inc';
791 require_once './includes/theme.inc';
792 require_once './includes/common.inc';
793 require_once './includes/unicode.inc';