[ Index ]
 

Code source de Drupal 5.3

Accédez au Source d'autres logiciels libres

Classes | Fonctions | Variables | Constantes | Tables

title

Body

[fermer]

/includes/ -> bootstrap.inc (source)

   1  <?php
   2  // $Id: bootstrap.inc,v 1.145.2.6 2007/07/26 19:16:45 drumm Exp $
   3  
   4  /**
   5   * @file
   6   * Functions that need to be loaded on every Drupal request.
   7   */
   8  
   9  /**
  10   * Indicates that the item should never be removed unless explicitly told to
  11   * using cache_clear_all() with a cache ID.
  12   */
  13  define('CACHE_PERMANENT', 0);
  14  
  15  /**
  16   * Indicates that the item should be removed at the next general cache wipe.
  17   */
  18  define('CACHE_TEMPORARY', -1);
  19  
  20  /**
  21   * Indicates that page caching is disabled.
  22   */
  23  define('CACHE_DISABLED', 0);
  24  
  25  /**
  26   * Indicates that page caching is enabled, using "normal" mode.
  27   */
  28  define('CACHE_NORMAL', 1);
  29  
  30  /**
  31   * Indicates that page caching is using "aggressive" mode. This bypasses
  32   * loading any modules for additional speed, which may break functionality in
  33   * modules that expect to be run on each page load.
  34   */
  35  define('CACHE_AGGRESSIVE', 2);
  36  
  37  /**
  38   * Indicates a notice-level watchdog event; these are normally notifications
  39   * of normal system events that have occurred and can usually be safely ignored.
  40   */
  41  define('WATCHDOG_NOTICE', 0);
  42  
  43  /**
  44   * Indicates a warning-level watchdog event; this can be triggered by an error
  45   * in a module that does not impact the overall functionality of the site.
  46   */
  47  define('WATCHDOG_WARNING', 1);
  48  
  49  /**
  50   * Indicates an error-level watchdog event; could be indicative of an attempt
  51   * to compromise the security of the site, or a serious system error.
  52   */
  53  define('WATCHDOG_ERROR', 2);
  54  
  55  /**
  56   * First bootstrap phase: initialize configuration.
  57   */
  58  define('DRUPAL_BOOTSTRAP_CONFIGURATION', 0);
  59  
  60  /**
  61   * Second bootstrap phase: try to call a non-database cache
  62   * fetch routine.
  63   */
  64  define('DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE', 1);
  65  
  66  /**
  67   * Third bootstrap phase: initialize database layer.
  68   */
  69  define('DRUPAL_BOOTSTRAP_DATABASE', 2);
  70  
  71  /**
  72   * Fourth bootstrap phase: identify and reject banned hosts.
  73   */
  74  define('DRUPAL_BOOTSTRAP_ACCESS', 3);
  75  
  76  /**
  77   * Fifth bootstrap phase: initialize session handling.
  78   */
  79  define('DRUPAL_BOOTSTRAP_SESSION', 4);
  80  
  81  /**
  82   * Sixth bootstrap phase: load bootstrap.inc and module.inc, start
  83   * the variable system and try to serve a page from the cache.
  84   */
  85  define('DRUPAL_BOOTSTRAP_LATE_PAGE_CACHE', 5);
  86  
  87  /**
  88   * Seventh bootstrap phase: set $_GET['q'] to Drupal path of request.
  89   */
  90  define('DRUPAL_BOOTSTRAP_PATH', 6);
  91  
  92  /**
  93   * Final bootstrap phase: Drupal is fully loaded; validate and fix
  94   * input data.
  95   */
  96  define('DRUPAL_BOOTSTRAP_FULL', 7);
  97  
  98  /**
  99   * Role ID for anonymous users; should match what's in the "role" table.
 100   */
 101  define('DRUPAL_ANONYMOUS_RID', 1);
 102  
 103  /**
 104   * Role ID for authenticated users; should match what's in the "role" table.
 105   */
 106  define('DRUPAL_AUTHENTICATED_RID', 2);
 107  
 108  /**
 109   * Start the timer with the specified name. If you start and stop
 110   * the same timer multiple times, the measured intervals will be
 111   * accumulated.
 112   *
 113   * @param name
 114   *   The name of the timer.
 115   */
 116  function timer_start($name) {
 117    global $timers;
 118  
 119    list($usec, $sec) = explode(' ', microtime());
 120    $timers[$name]['start'] = (float)$usec + (float)$sec;
 121    $timers[$name]['count'] = isset($timers[$name]['count']) ? ++$timers[$name]['count'] : 1;
 122  }
 123  
 124  /**
 125   * Read the current timer value without stopping the timer.
 126   *
 127   * @param name
 128   *   The name of the timer.
 129   * @return
 130   *   The current timer value in ms.
 131   */
 132  function timer_read($name) {
 133    global $timers;
 134  
 135    if (isset($timers[$name]['start'])) {
 136      list($usec, $sec) = explode(' ', microtime());
 137      $stop = (float)$usec + (float)$sec;
 138      $diff = round(($stop - $timers[$name]['start']) * 1000, 2);
 139  
 140      if (isset($timers[$name]['time'])) {
 141        $diff += $timers[$name]['time'];
 142      }
 143      return $diff;
 144    }
 145  }
 146  
 147  /**
 148   * Stop the timer with the specified name.
 149   *
 150   * @param name
 151   *   The name of the timer.
 152   * @return
 153   *   A timer array. The array contains the number of times the
 154   *   timer has been started and stopped (count) and the accumulated
 155   *   timer value in ms (time).
 156   */
 157  function timer_stop($name) {
 158    global $timers;
 159  
 160    $timers[$name]['time'] = timer_read($name);
 161    unset($timers[$name]['start']);
 162  
 163    return $timers[$name];
 164  }
 165  
 166  /**
 167   * Find the appropriate configuration directory.
 168   *
 169   * Try finding a matching configuration directory by stripping the website's
 170   * hostname from left to right and pathname from right to left. The first
 171   * configuration file found will be used; the remaining will ignored. If no
 172   * configuration file is found, return a default value '$confdir/default'.
 173   *
 174   * Example for a fictitious site installed at
 175   * http://www.drupal.org:8080/mysite/test/ the 'settings.php' is searched in
 176   * the following directories:
 177   *
 178   *  1. $confdir/8080.www.drupal.org.mysite.test
 179   *  2. $confdir/www.drupal.org.mysite.test
 180   *  3. $confdir/drupal.org.mysite.test
 181   *  4. $confdir/org.mysite.test
 182   *
 183   *  5. $confdir/8080.www.drupal.org.mysite
 184   *  6. $confdir/www.drupal.org.mysite
 185   *  7. $confdir/drupal.org.mysite
 186   *  8. $confdir/org.mysite
 187   *
 188   *  9. $confdir/8080.www.drupal.org
 189   * 10. $confdir/www.drupal.org
 190   * 11. $confdir/drupal.org
 191   * 12. $confdir/org
 192   *
 193   * 13. $confdir/default
 194   */
 195  function conf_path() {
 196    static $conf = '';
 197  
 198    if ($conf) {
 199      return $conf;
 200    }
 201  
 202    $confdir = 'sites';
 203    $uri = explode('/', $_SERVER['SCRIPT_NAME'] ? $_SERVER['SCRIPT_NAME'] : $_SERVER['SCRIPT_FILENAME']);
 204    $server = explode('.', implode('.', array_reverse(explode(':', rtrim($_SERVER['HTTP_HOST'], '.')))));
 205    for ($i = count($uri) - 1; $i > 0; $i--) {
 206      for ($j = count($server); $j > 0; $j--) {
 207        $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
 208        if (file_exists("$confdir/$dir/settings.php")) {
 209          $conf = "$confdir/$dir";
 210          return $conf;
 211        }
 212      }
 213    }
 214    $conf = "$confdir/default";
 215    return $conf;
 216  }
 217  
 218  /**
 219   * Unsets all disallowed global variables. See $allowed for what's allowed.
 220   */
 221  function drupal_unset_globals() {
 222    if (ini_get('register_globals')) {
 223      $allowed = array('_ENV' => 1, '_GET' => 1, '_POST' => 1, '_COOKIE' => 1, '_FILES' => 1, '_SERVER' => 1, '_REQUEST' => 1, 'access_check' => 1, 'GLOBALS' => 1);
 224      foreach ($GLOBALS as $key => $value) {
 225        if (!isset($allowed[$key])) {
 226          unset($GLOBALS[$key]);
 227        }
 228      }
 229    }
 230  }
 231  
 232  /**
 233   * Loads the configuration and sets the base URL, cookie domain, and
 234   * session name correctly.
 235   */
 236  function conf_init() {
 237    global $base_url, $base_path, $base_root;
 238  
 239    // Export the following settings.php variables to the global namespace
 240    global $db_url, $db_prefix, $cookie_domain, $conf, $installed_profile;
 241    $conf = array();
 242  
 243    include_once './'. conf_path() .'/settings.php';
 244  
 245    if (isset($base_url)) {
 246      // Parse fixed base URL from settings.php.
 247      $parts = parse_url($base_url);
 248      if (!isset($parts['path'])) {
 249        $parts['path'] = '';
 250      }
 251      $base_path = $parts['path'] . '/';
 252      // Build $base_root (everything until first slash after "scheme://").
 253      $base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
 254    }
 255    else {
 256      // Create base URL
 257      $base_root = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
 258  
 259      // As $_SERVER['HTTP_HOST'] is user input, ensure it only contains
 260      // characters allowed in hostnames.
 261      $base_url = $base_root .= '://'. preg_replace('/[^a-z0-9-:._]/i', '', $_SERVER['HTTP_HOST']);
 262  
 263      // $_SERVER['SCRIPT_NAME'] can, in contrast to $_SERVER['PHP_SELF'], not
 264      // be modified by a visitor.
 265      if ($dir = trim(dirname($_SERVER['SCRIPT_NAME']), '\,/')) {
 266        $base_path = "/$dir";
 267        $base_url .= $base_path;
 268        $base_path .= '/';
 269      }
 270      else {
 271        $base_path = '/';
 272      }
 273    }
 274  
 275    if (!$cookie_domain) {
 276      // If the $cookie_domain is empty, try to use the session.cookie_domain.
 277      $cookie_domain = ini_get('session.cookie_domain');
 278    }
 279    if ($cookie_domain) {
 280      // If the user specifies the cookie domain, also use it for session name.
 281      $session_name = $cookie_domain;
 282    }
 283    else {
 284      // Otherwise use $base_url as session name, without the protocol
 285      // to use the same session identifiers across http and https.
 286      list( , $session_name) = explode('://', $base_url, 2);
 287      // We try to set the cookie domain to the hostname.
 288      // We escape the hostname because it can be modified by a visitor.
 289      if (!empty($_SERVER['HTTP_HOST'])) {
 290        $cookie_domain = check_plain($_SERVER['HTTP_HOST']);
 291      }
 292    }
 293    // Strip leading periods, www., and port numbers from cookie domain.
 294    $cookie_domain = ltrim($cookie_domain, '.');
 295    if (strpos($cookie_domain, 'www.') === 0) {
 296      $cookie_domain = substr($cookie_domain, 4);
 297    }
 298    $cookie_domain = explode(':', $cookie_domain);
 299    $cookie_domain = '.'. $cookie_domain[0];
 300    // Per RFC 2109, cookie domains must contain at least one dot other than the
 301    // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
 302    if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
 303      ini_set('session.cookie_domain', $cookie_domain);
 304    }
 305    session_name('SESS'. md5($session_name));
 306  }
 307  
 308  /**
 309   * Returns and optionally sets the filename for a system item (module,
 310   * theme, etc.). The filename, whether provided, cached, or retrieved
 311   * from the database, is only returned if the file exists.
 312   *
 313   * This function plays a key role in allowing Drupal's resources (modules
 314   * and themes) to be located in different places depending on a site's
 315   * configuration. For example, a module 'foo' may legally be be located
 316   * in any of these three places:
 317   *
 318   * modules/foo/foo.module
 319   * sites/all/modules/foo/foo.module
 320   * sites/example.com/modules/foo/foo.module
 321   *
 322   * Calling drupal_get_filename('module', 'foo') will give you one of
 323   * the above, depending on where the module is located.
 324   *
 325   * @param $type
 326   *   The type of the item (i.e. theme, theme_engine, module).
 327   * @param $name
 328   *   The name of the item for which the filename is requested.
 329   * @param $filename
 330   *   The filename of the item if it is to be set explicitly rather
 331   *   than by consulting the database.
 332   *
 333   * @return
 334   *   The filename of the requested item.
 335   */
 336  function drupal_get_filename($type, $name, $filename = NULL) {
 337    static $files = array();
 338    global $active_db;
 339  
 340    if (!isset($files[$type])) {
 341      $files[$type] = array();
 342    }
 343  
 344    if (!empty($filename) && file_exists($filename)) {
 345      $files[$type][$name] = $filename;
 346    }
 347    elseif (isset($files[$type][$name])) {
 348      // nothing
 349    }
 350    // Verify that we have an active database connection, before querying
 351    // the database.  This is required because this function is called both
 352    // before we have a database connection (i.e. during installation) and
 353    // when a database connection fails.
 354    elseif ($active_db && (($file = db_result(db_query("SELECT filename FROM {system} WHERE name = '%s' AND type = '%s'", $name, $type))) && file_exists($file))) {
 355      $files[$type][$name] = $file;
 356    }
 357    else {
 358      // Fallback to searching the filesystem if the database connection is
 359      // not established or the requested file is not found.
 360      $config = conf_path();
 361      $dir = (($type == 'theme_engine') ? 'themes/engines' : "$type}s");
 362      $file = (($type == 'theme_engine') ? "$name.engine" : "$name.$type");
 363  
 364      foreach (array("$config/$dir/$file", "$config/$dir/$name/$file", "$dir/$file", "$dir/$name/$file") as $file) {
 365        if (file_exists($file)) {
 366          $files[$type][$name] = $file;
 367          break;
 368        }
 369      }
 370    }
 371  
 372    return $files[$type][$name];
 373  }
 374  
 375  /**
 376   * Load the persistent variable table.
 377   *
 378   * The variable table is composed of values that have been saved in the table
 379   * with variable_set() as well as those explicitly specified in the configuration
 380   * file.
 381   */
 382  function variable_init($conf = array()) {
 383    // NOTE: caching the variables improves performance by 20% when serving cached pages.
 384    if ($cached = cache_get('variables', 'cache')) {
 385      $variables = unserialize($cached->data);
 386    }
 387    else {
 388      $result = db_query('SELECT * FROM {variable}');
 389      while ($variable = db_fetch_object($result)) {
 390        $variables[$variable->name] = unserialize($variable->value);
 391      }
 392      cache_set('variables', 'cache', serialize($variables));
 393    }
 394  
 395    foreach ($conf as $name => $value) {
 396      $variables[$name] = $value;
 397    }
 398  
 399    return $variables;
 400  }
 401  
 402  /**
 403   * Return a persistent variable.
 404   *
 405   * @param $name
 406   *   The name of the variable to return.
 407   * @param $default
 408   *   The default value to use if this variable has never been set.
 409   * @return
 410   *   The value of the variable.
 411   */
 412  function variable_get($name, $default) {
 413    global $conf;
 414  
 415    return isset($conf[$name]) ? $conf[$name] : $default;
 416  }
 417  
 418  /**
 419   * Set a persistent variable.
 420   *
 421   * @param $name
 422   *   The name of the variable to set.
 423   * @param $value
 424   *   The value to set. This can be any PHP data type; these functions take care
 425   *   of serialization as necessary.
 426   */
 427  function variable_set($name, $value) {
 428    global $conf;
 429  
 430    db_lock_table('variable');
 431    db_query("DELETE FROM {variable} WHERE name = '%s'", $name);
 432    db_query("INSERT INTO {variable} (name, value) VALUES ('%s', '%s')", $name, serialize($value));
 433    db_unlock_tables();
 434  
 435    cache_clear_all('variables', 'cache');
 436  
 437    $conf[$name] = $value;
 438  }
 439  
 440  /**
 441   * Unset a persistent variable.
 442   *
 443   * @param $name
 444   *   The name of the variable to undefine.
 445   */
 446  function variable_del($name) {
 447    global $conf;
 448  
 449    db_query("DELETE FROM {variable} WHERE name = '%s'", $name);
 450    cache_clear_all('variables', 'cache');
 451  
 452    unset($conf[$name]);
 453  }
 454  
 455  /**
 456   * Retrieve the current page from the cache.
 457   *
 458   * Note: we do not serve cached pages when status messages are waiting (from
 459   * a redirected form submission which was completed).
 460   */
 461  function page_get_cache() {
 462    global $user, $base_root;
 463  
 464    $cache = NULL;
 465  
 466    if (!$user->uid && $_SERVER['REQUEST_METHOD'] == 'GET' && count(drupal_set_message()) == 0) {
 467      $cache = cache_get($base_root . request_uri(), 'cache_page');
 468  
 469      if (empty($cache)) {
 470        ob_start();
 471      }
 472    }
 473  
 474    return $cache;
 475  }
 476  
 477  /**
 478   * Call all init or exit hooks without including all modules.
 479   *
 480   * @param $hook
 481   *   The name of the bootstrap hook we wish to invoke.
 482   */
 483  function bootstrap_invoke_all($hook) {
 484    foreach (module_list(TRUE, TRUE) as $module) {
 485      drupal_load('module', $module);
 486      module_invoke($module, $hook);
 487   }
 488  }
 489  
 490  /**
 491   * Includes a file with the provided type and name. This prevents
 492   * including a theme, engine, module, etc., more than once.
 493   *
 494   * @param $type
 495   *   The type of item to load (i.e. theme, theme_engine, module).
 496   * @param $name
 497   *   The name of the item to load.
 498   *
 499   * @return
 500   *   TRUE if the item is loaded or has already been loaded.
 501   */
 502  function drupal_load($type, $name) {
 503    static $files = array();
 504  
 505    if (isset($files[$type][$name])) {
 506      return TRUE;
 507    }
 508  
 509    $filename = drupal_get_filename($type, $name);
 510  
 511    if ($filename) {
 512      include_once "./$filename";
 513      $files[$type][$name] = TRUE;
 514  
 515      return TRUE;
 516    }
 517  
 518    return FALSE;
 519  }
 520  
 521  /**
 522   * Set HTTP headers in preparation for a page response.
 523   *
 524   * Authenticated users are always given a 'no-cache' header, and will
 525   * fetch a fresh page on every request.  This prevents authenticated
 526   * users seeing locally cached pages that show them as logged out.
 527   *
 528   * @see page_set_cache
 529   */
 530  function drupal_page_header() {
 531    header("Expires: Sun, 19 Nov 1978 05:00:00 GMT");
 532    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
 533    header("Cache-Control: store, no-cache, must-revalidate");
 534    header("Cache-Control: post-check=0, pre-check=0", FALSE);
 535  }
 536  
 537  /**
 538   * Set HTTP headers in preparation for a cached page response.
 539   *
 540   * The general approach here is that anonymous users can keep a local
 541   * cache of the page, but must revalidate it on every request.  Then,
 542   * they are given a '304 Not Modified' response as long as they stay
 543   * logged out and the page has not been modified.
 544   *
 545   */
 546  function drupal_page_cache_header($cache) {
 547    // Set default values:
 548    $last_modified = gmdate('D, d M Y H:i:s', $cache->created) .' GMT';
 549    $etag = '"'.md5($last_modified).'"';
 550  
 551    // See if the client has provided the required HTTP headers:
 552    $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) : FALSE;
 553    $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : FALSE;
 554  
 555    if ($if_modified_since && $if_none_match
 556        && $if_none_match == $etag // etag must match
 557        && $if_modified_since == $last_modified) {  // if-modified-since must match
 558      header('HTTP/1.1 304 Not Modified');
 559      // All 304 responses must send an etag if the 200 response for the same object contained an etag
 560      header("Etag: $etag");
 561      exit();
 562    }
 563  
 564    // Send appropriate response:
 565    header("Last-Modified: $last_modified");
 566    header("ETag: $etag");
 567  
 568    // The following headers force validation of cache:
 569    header("Expires: Sun, 19 Nov 1978 05:00:00 GMT");
 570    header("Cache-Control: must-revalidate");
 571  
 572    // Determine if the browser accepts gzipped data.
 573    if (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === FALSE && function_exists('gzencode')) {
 574      // Strip the gzip header and run uncompress.
 575      $cache->data = gzinflate(substr(substr($cache->data, 10), 0, -8));
 576    }
 577    elseif (function_exists('gzencode')) {
 578      header('Content-Encoding: gzip');
 579    }
 580  
 581    // Send the original request's headers. We send them one after
 582    // another so PHP's header() function can deal with duplicate
 583    // headers.
 584    $headers = explode("\n", $cache->headers);
 585    foreach ($headers as $header) {
 586      header($header);
 587    }
 588  
 589    print $cache->data;
 590  }
 591  
 592  /**
 593   * Define the critical hooks that force modules to always be loaded.
 594   */
 595  function bootstrap_hooks() {
 596    return array('init', 'exit');
 597  }
 598  
 599  /**
 600   * Unserializes and appends elements from a serialized string.
 601   *
 602   * @param $obj
 603   *   The object to which the elements are appended.
 604   * @param $field
 605   *   The attribute of $obj whose value should be unserialized.
 606   */
 607  function drupal_unpack($obj, $field = 'data') {
 608    if ($obj->$field && $data = unserialize($obj->$field)) {
 609      foreach ($data as $key => $value) {
 610        if (!isset($obj->$key)) {
 611          $obj->$key = $value;
 612        }
 613      }
 614    }
 615    return $obj;
 616  }
 617  
 618  /**
 619   * Return the URI of the referring page.
 620   */
 621  function referer_uri() {
 622    if (isset($_SERVER['HTTP_REFERER'])) {
 623      return $_SERVER['HTTP_REFERER'];
 624    }
 625  }
 626  
 627  /**
 628   * Encode special characters in a plain-text string for display as HTML.
 629   */
 630  function check_plain($text) {
 631    return htmlspecialchars($text, ENT_QUOTES);
 632  }
 633  
 634  /**
 635   * Since $_SERVER['REQUEST_URI'] is only available on Apache, we
 636   * generate an equivalent using other environment variables.
 637   */
 638  function request_uri() {
 639  
 640    if (isset($_SERVER['REQUEST_URI'])) {
 641      $uri = $_SERVER['REQUEST_URI'];
 642    }
 643    else {
 644      if (isset($_SERVER['argv'])) {
 645        $uri = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['argv'][0];
 646      }
 647      else {
 648        $uri = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
 649      }
 650    }
 651  
 652    return $uri;
 653  }
 654  
 655  /**
 656   * Log a system message.
 657   *
 658   * @param $type
 659   *   The category to which this message belongs.
 660   * @param $message
 661   *   The message to store in the log.
 662   * @param $severity
 663   *   The severity of the message. One of the following values:
 664   *   - WATCHDOG_NOTICE
 665   *   - WATCHDOG_WARNING
 666   *   - WATCHDOG_ERROR
 667   * @param $link
 668   *   A link to associate with the message.
 669   */
 670  function watchdog($type, $message, $severity = WATCHDOG_NOTICE, $link = NULL) {
 671    global $user, $base_root;
 672  
 673    $current_db = db_set_active();
 674  
 675    // Note: log the exact, entire absolute URL.
 676    $request_uri = $base_root . request_uri();
 677  
 678    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());
 679  
 680    if ($current_db) {
 681      db_set_active($current_db);
 682    }
 683  }
 684  
 685  /**
 686   * Set a message which reflects the status of the performed operation.
 687   *
 688   * If the function is called with no arguments, this function returns all set
 689   * messages without clearing them.
 690   *
 691   * @param $message
 692   *   The message should begin with a capital letter and always ends with a
 693   *   period '.'.
 694   * @param $type
 695   *   The type of the message. One of the following values are possible:
 696   *   - 'status'
 697   *   - 'error'
 698   */
 699  function drupal_set_message($message = NULL, $type = 'status') {
 700    if ($message) {
 701      if (!isset($_SESSION['messages'])) {
 702        $_SESSION['messages'] = array();
 703      }
 704  
 705      if (!isset($_SESSION['messages'][$type])) {
 706        $_SESSION['messages'][$type] = array();
 707      }
 708  
 709      $_SESSION['messages'][$type][] = $message;
 710    }
 711  
 712    // messages not set when DB connection fails
 713    return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
 714  }
 715  
 716  /**
 717   * Return all messages that have been set.
 718   *
 719   * @param $type
 720   *   (optional) Only return messages of this type.
 721   * @param $clear_queue
 722   *   (optional) Set to FALSE if you do not want to clear the messages queue
 723   * @return
 724   *   An associative array, the key is the message type, the value an array
 725   *   of messages. If the $type parameter is passed, you get only that type,
 726   *   or an empty array if there are no such messages. If $type is not passed,
 727   *   all message types are returned, or an empty array if none exist.
 728   */
 729  function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
 730    if ($messages = drupal_set_message()) {
 731      if ($type) {
 732        if ($clear_queue) {
 733           unset($_SESSION['messages'][$type]);
 734        }
 735        if (isset($messages[$type])) {
 736          return array($type => $messages[$type]);
 737        }
 738      }
 739      else {
 740        if ($clear_queue) {
 741           unset($_SESSION['messages']);
 742        }
 743        return $messages;
 744      }
 745    }
 746    return array();
 747  }
 748  
 749  /**
 750   * Perform an access check for a given mask and rule type. Rules are usually
 751   * created via admin/user/rules page.
 752   *
 753   * If any allow rule matches, access is allowed. Otherwise, if any deny rule
 754   * matches, access is denied.  If no rule matches, access is allowed.
 755   *
 756   * @param $type string
 757   *   Type of access to check: Allowed values are:
 758   *     - 'host': host name or IP address
 759   *     - 'mail': e-mail address
 760   *     - 'user': username
 761   * @param $mask string
 762   *   String or mask to test: '_' matches any character, '%' matches any
 763   *   number of characters.
 764   * @return bool
 765   *   TRUE if access is denied, FALSE if access is allowed.
 766   */
 767  function drupal_is_denied($type, $mask) {
 768    // Because this function is called for every page request, both cached
 769    // and non-cached pages, we tried to optimize it as much as possible.
 770    // We deny access if the only matching records in the {access} table have
 771    // status 0. If any have status 1, or if there are no matching records,
 772    // we allow access. So, select matching records in decreasing order of
 773    // 'status', returning NOT(status) for the first. If any have status 1,
 774    // they come first, and we return NOT(status) = 0 (allowed). Otherwise,
 775    // if we have some with status 0, we return 1 (denied). If no matching
 776    // records, we get no return from db_result, so we return (bool)NULL = 0
 777    // (allowed).
 778    // The use of ORDER BY / LIMIT is more efficient than "MAX(status) = 0"
 779    // in PostgreSQL <= 8.0.
 780    return (bool) db_result(db_query_range("SELECT CASE WHEN status=1 THEN 0 ELSE 1 END FROM {access} WHERE type = '%s' AND LOWER('%s') LIKE LOWER(mask) ORDER BY status DESC", $type, $mask, 0, 1));
 781  }
 782  
 783  /**
 784   * Generates a default anonymous $user object.
 785   *
 786   * @return Object - the user object.
 787   */
 788  function drupal_anonymous_user($session = '') {
 789    $user = new stdClass();
 790    $user->uid = 0;
 791    $user->hostname = $_SERVER['REMOTE_ADDR'];
 792    $user->roles = array();
 793    $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
 794    $user->session = $session;
 795    $user->cache = 0;
 796    return $user;
 797  }
 798  
 799  /**
 800   * A string describing a phase of Drupal to load. Each phase adds to the
 801   * previous one, so invoking a later phase automatically runs the earlier
 802   * phases too. The most important usage is that if you want to access the
 803   * Drupal database from a script without loading anything else, you can
 804   * include bootstrap.inc, and call drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE).
 805   *
 806   * @param $phase
 807   *   A constant. Allowed values are:
 808   *     DRUPAL_BOOTSTRAP_CONFIGURATION: initialize configuration.
 809   *     DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE: try to call a non-database cache fetch routine.
 810   *     DRUPAL_BOOTSTRAP_DATABASE: initialize database layer.
 811   *     DRUPAL_BOOTSTRAP_ACCESS: identify and reject banned hosts.
 812   *     DRUPAL_BOOTSTRAP_SESSION: initialize session handling.
 813   *     DRUPAL_BOOTSTRAP_LATE_PAGE_CACHE: load bootstrap.inc and module.inc, start
 814   *       the variable system and try to serve a page from the cache.
 815   *     DRUPAL_BOOTSTRAP_PATH: set $_GET['q'] to Drupal path of request.
 816   *     DRUPAL_BOOTSTRAP_FULL: Drupal is fully loaded, validate and fix input data.
 817   */
 818  function drupal_bootstrap($phase) {
 819    static $phases = array(DRUPAL_BOOTSTRAP_CONFIGURATION, DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE, DRUPAL_BOOTSTRAP_DATABASE, DRUPAL_BOOTSTRAP_ACCESS, DRUPAL_BOOTSTRAP_SESSION, DRUPAL_BOOTSTRAP_LATE_PAGE_CACHE, DRUPAL_BOOTSTRAP_PATH, DRUPAL_BOOTSTRAP_FULL);
 820  
 821    while (!is_null($current_phase = array_shift($phases))) {
 822      _drupal_bootstrap($current_phase);
 823      if ($phase == $current_phase) {
 824        return;
 825      }
 826    }
 827  }
 828  
 829  function _drupal_bootstrap($phase) {
 830    global $conf;
 831  
 832    switch ($phase) {
 833  
 834      case DRUPAL_BOOTSTRAP_CONFIGURATION:
 835        drupal_unset_globals();
 836        // Initialize the configuration
 837        conf_init();
 838        break;
 839  
 840      case DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE:
 841        _drupal_cache_init($phase);
 842        break;
 843  
 844      case DRUPAL_BOOTSTRAP_DATABASE:
 845        // Initialize the default database.
 846        require_once  './includes/database.inc';
 847        db_set_active();
 848        break;
 849  
 850      case DRUPAL_BOOTSTRAP_ACCESS:
 851        // Deny access to hosts which were banned - t() is not yet available.
 852        if (drupal_is_denied('host', $_SERVER['REMOTE_ADDR'])) {
 853          header('HTTP/1.1 403 Forbidden');
 854          print 'Sorry, '. $_SERVER['REMOTE_ADDR']. ' has been banned.';
 855          exit();
 856        }
 857        break;
 858  
 859      case DRUPAL_BOOTSTRAP_SESSION:
 860        require_once variable_get('session_inc', './includes/session.inc');
 861        session_set_save_handler('sess_open', 'sess_close', 'sess_read', 'sess_write', 'sess_destroy_sid', 'sess_gc');
 862        session_start();
 863        break;
 864  
 865      case DRUPAL_BOOTSTRAP_LATE_PAGE_CACHE:
 866        // Initialize configuration variables, using values from settings.php if available.
 867        $conf = variable_init(isset($conf) ? $conf : array());
 868  
 869        _drupal_cache_init($phase);
 870  
 871        // Start a page timer:
 872        timer_start('page');
 873  
 874        drupal_page_header();
 875        break;
 876  
 877      case DRUPAL_BOOTSTRAP_PATH:
 878        require_once  './includes/path.inc';
 879        // Initialize $_GET['q'] prior to loading modules and invoking hook_init().
 880        drupal_init_path();
 881        break;
 882  
 883      case DRUPAL_BOOTSTRAP_FULL:
 884        require_once  './includes/common.inc';
 885        _drupal_bootstrap_full();
 886        break;
 887    }
 888  }
 889  
 890  /**
 891   * Initialize the caching strategy, which loads at different stages within
 892   * Drupal's bootstrap process.
 893   */
 894  function _drupal_cache_init($phase) {
 895    require_once variable_get('cache_inc', './includes/cache.inc');
 896  
 897    if ($phase == DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE && variable_get('page_cache_fastpath', 0)) {
 898      if (page_cache_fastpath()) {
 899        exit();
 900      }
 901    }
 902    elseif ($phase == DRUPAL_BOOTSTRAP_LATE_PAGE_CACHE) {
 903      if ($cache = page_get_cache()) {
 904        if (variable_get('cache', CACHE_DISABLED) == CACHE_AGGRESSIVE) {
 905          drupal_page_cache_header($cache);
 906          exit();
 907        }
 908        elseif (variable_get('cache', CACHE_DISABLED) == CACHE_NORMAL) {
 909          require_once  './includes/module.inc';
 910          bootstrap_invoke_all('init');
 911          drupal_page_cache_header($cache);
 912          bootstrap_invoke_all('exit');
 913          exit();
 914        }
 915      }
 916      require_once  './includes/module.inc';
 917    }
 918  }
 919  
 920  /**
 921   * Enables use of the theme system without requiring database access. Since
 922   * there is not database access no theme will be enabled and the default
 923   * themeable functions will be called. Some themeable functions can not be used
 924   * without the full Drupal API loaded. For example, theme_page() is
 925   * unavailable and theme_maintenance_page() must be used in its place.
 926   */
 927  function drupal_maintenance_theme() {
 928    global $theme;
 929    require_once  './includes/path.inc';
 930    require_once  './includes/theme.inc';
 931    require_once  './includes/common.inc';
 932    require_once  './includes/unicode.inc';
 933    require_once  './modules/filter/filter.module';
 934    unicode_check();
 935    drupal_add_css(drupal_get_path('module', 'system') .'/defaults.css', 'module');
 936    drupal_add_css(drupal_get_path('module', 'system') .'/system.css', 'module');
 937    $theme = '';
 938  }
 939  
 940  /**
 941   * Return the name of the localisation function. Use in code that needs to
 942   * run both during installation and normal operation.
 943   */
 944  function get_t() {
 945    static $t;
 946    if (is_null($t)) {
 947      $t = function_exists('install_main') ? 'st' : 't';
 948    }
 949    return $t;
 950  }


Généré le : Fri Nov 30 16:20:15 2007 par Balluche grâce à PHPXref 0.7
  Clicky Web Analytics