[ Index ]

PHP Cross Reference of Moodle 1.9.3 [Build 15-Oct-2008]

title

Body

[close]

/lib/ -> setup.php (source)

   1  <?php
   2  /**
   3   * setup.php - Sets up sessions, connects to databases and so on
   4   *
   5   * Normally this is only called by the main config.php file
   6   * Normally this file does not need to be edited.
   7   * @author Martin Dougiamas
   8   * @version $Id: setup.php,v 1.212.2.19 2008/08/17 22:22:51 skodak Exp $
   9   * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  10   * @package moodlecore
  11   */
  12  
  13  ////// DOCUMENTATION IN PHPDOC FORMAT FOR MOODLE GLOBALS AND COMMON OBJECT TYPES /////////////
  14  /**
  15   * $USER is a global instance of a typical $user record.
  16   *
  17   * Items found in the user record:
  18   *  - $USER->emailstop - Does the user want email sent to them?
  19   *  - $USER->email - The user's email address.
  20   *  - $USER->id - The unique integer identified of this user in the 'user' table.
  21   *  - $USER->email - The user's email address.
  22   *  - $USER->firstname - The user's first name.
  23   *  - $USER->lastname - The user's last name.
  24   *  - $USER->username - The user's login username.
  25   *  - $USER->secret - The user's ?.
  26   *  - $USER->lang - The user's language choice.
  27   *
  28   * @global object(user) $USER
  29   */
  30  global $USER;
  31  /**
  32   * This global variable is read in from the 'config' table.
  33   *
  34   * Some typical settings in the $CFG global:
  35   *  - $CFG->wwwroot - Path to moodle index directory in url format.
  36   *  - $CFG->dataroot - Path to moodle index directory on server's filesystem.
  37   *  - $CFG->libdir  - Path to moodle's library folder on server's filesystem.
  38   *
  39   * @global object(cfg) $CFG
  40   */
  41  global $CFG;
  42  /**
  43   * Definition of session type
  44   * @global object(session) $SESSION
  45   */
  46  global $SESSION;
  47  /** 
  48   * Definition of shared memory cache
  49   */
  50  global $MCACHE;
  51  /**
  52   * Definition of course type
  53   * @global object(course) $COURSE
  54   */
  55  global $COURSE;
  56  /**
  57   * Definition of db type
  58   * @global object(db) $db
  59   */
  60  global $db;
  61  /**
  62   * $THEME is a global that defines the site theme.
  63   *
  64   * Items found in the theme record:
  65   *  - $THEME->cellheading - Cell colors.
  66   *  - $THEME->cellheading2 - Alternate cell colors.
  67   *
  68   * @global object(theme) $THEME
  69   */
  70  global $THEME;
  71  
  72  /**
  73   * HTTPSPAGEREQUIRED is a global to define if the page being displayed must run under HTTPS. 
  74   * 
  75   * It's primary goal is to allow 100% HTTPS pages when $CFG->loginhttps is enabled. Default to false.
  76   * It's enabled only by the httpsrequired() function and used in some pages to update some URLs
  77  */
  78  global $HTTPSPAGEREQUIRED;
  79  
  80  
  81  /// First try to detect some attacks on older buggy PHP versions
  82      if (isset($_REQUEST['GLOBALS']) || isset($_COOKIE['GLOBALS']) || isset($_FILES['GLOBALS'])) {
  83          die('Fatal: Illegal GLOBALS overwrite attempt detected!');
  84      }
  85  
  86  
  87      if (!isset($CFG->wwwroot)) {
  88          trigger_error('Fatal: $CFG->wwwroot is not configured! Exiting.');
  89          die;
  90      }
  91  
  92  /// store settings from config.php in array in $CFG - we can use it later to detect problems and overrides
  93      $CFG->config_php_settings = (array)$CFG;
  94  
  95  /// Set httpswwwroot default value (this variable will replace $CFG->wwwroot
  96  /// inside some URLs used in HTTPSPAGEREQUIRED pages.
  97      $CFG->httpswwwroot = $CFG->wwwroot;
  98  
  99      $CFG->libdir   = $CFG->dirroot .'/lib';
 100  
 101      require_once($CFG->libdir .'/setuplib.php');        // Functions that MUST be loaded first
 102  
 103  /// Time to start counting    
 104      init_performance_info();        
 105      
 106  
 107  /// If there are any errors in the standard libraries we want to know!
 108      error_reporting(E_ALL);
 109  
 110  /// Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
 111  /// http://www.google.com/webmasters/faq.html#prefetchblock
 112      if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
 113          header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');        
 114          trigger_error('Prefetch request forbidden.');
 115          exit;
 116      }
 117  
 118  /// Connect to the database using adodb
 119  
 120  /// Set $CFG->dbfamily global
 121  /// and configure some other specific variables for each db BEFORE attempting the connection
 122      preconfigure_dbconnection();
 123  
 124      require_once($CFG->libdir .'/adodb/adodb.inc.php'); // Database access functions
 125  
 126      $db = &ADONewConnection($CFG->dbtype);
 127  
 128      // See MDL-6760 for why this is necessary. In Moodle 1.8, once we start using NULLs properly,
 129      // we probably want to change this value to ''.
 130      $db->null2null = 'A long random string that will never, ever match something we want to insert into the database, I hope. \'';
 131  
 132      error_reporting(0);  // Hide errors
 133  
 134      if (!isset($CFG->dbpersist) or !empty($CFG->dbpersist)) {    // Use persistent connection (default)
 135          $dbconnected = $db->PConnect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);
 136      } else {                                                     // Use single connection
 137          $dbconnected = $db->Connect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);
 138      }
 139      if (! $dbconnected) {
 140          // In the name of protocol correctness, monitoring and performance
 141          // profiling, set the appropriate error headers for machine comsumption
 142          if (isset($_SERVER['SERVER_PROTOCOL'])) { 
 143              // Avoid it with cron.php. Note that we assume it's HTTP/1.x
 144              header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');        
 145          }
 146          // and then for human consumption...
 147          echo '<html><body>';
 148          echo '<table align="center"><tr>';
 149          echo '<td style="color:#990000; text-align:center; font-size:large; border-width:1px; '.
 150               '    border-color:#000000; border-style:solid; border-radius: 20px; border-collapse: collapse; '.
 151               '    -moz-border-radius: 20px; padding: 15px">';
 152          echo '<p>Error: Database connection failed.</p>';
 153          echo '<p>It is possible that the database is overloaded or otherwise not running properly.</p>';
 154          echo '<p>The site administrator should also check that the database details have been correctly specified in config.php</p>';
 155          echo '</td></tr></table>';
 156          echo '</body></html>';
 157  
 158          error_log('ADODB Error: '.$db->ErrorMsg()); // see MDL-14628
 159  
 160          if (empty($CFG->noemailever) and !empty($CFG->emailconnectionerrorsto)) {
 161              if (file_exists($CFG->dataroot.'/emailcount')){
 162                  $fp = fopen($CFG->dataroot.'/emailcount', 'r');
 163                  $content = fread($fp, 24);
 164                  fclose($fp);
 165                  if((time() - (int)$content) > 600){
 166                      mail($CFG->emailconnectionerrorsto, 
 167                          'WARNING: Database connection error: '.$CFG->wwwroot, 
 168                          'Connection error: '.$CFG->wwwroot);
 169                      $fp = fopen($CFG->dataroot.'/emailcount', 'w');
 170                      fwrite($fp, time());
 171                  }
 172              } else {
 173                 mail($CFG->emailconnectionerrorsto, 
 174                      'WARNING: Database connection error: '.$CFG->wwwroot, 
 175                      'Connection error: '.$CFG->wwwroot);
 176                 $fp = fopen($CFG->dataroot.'/emailcount', 'w');
 177                 fwrite($fp, time());
 178              }
 179          }
 180          die;
 181      }
 182  
 183  /// Forcing ASSOC mode for ADOdb (some DBs default to FETCH_BOTH)
 184      $db->SetFetchMode(ADODB_FETCH_ASSOC);
 185  
 186  /// Starting here we have a correct DB conection but me must avoid
 187  /// to execute any DB transaction until "set names" has been executed
 188  /// some lines below!
 189  
 190      error_reporting(E_ALL);       // Show errors from now on.
 191  
 192      if (!isset($CFG->prefix)) {   // Just in case it isn't defined in config.php
 193          $CFG->prefix = '';
 194      }
 195  
 196  
 197  /// Define admin directory
 198  
 199      if (!isset($CFG->admin)) {   // Just in case it isn't defined in config.php
 200          $CFG->admin = 'admin';   // This is relative to the wwwroot and dirroot
 201      }
 202  
 203  /// Increase memory limits if possible
 204      raise_memory_limit('96M');    // We should never NEED this much but just in case...
 205  
 206  /// Load up standard libraries
 207  
 208      require_once($CFG->libdir .'/textlib.class.php');   // Functions to handle multibyte strings
 209      require_once($CFG->libdir .'/weblib.php');          // Functions for producing HTML
 210      require_once($CFG->libdir .'/dmllib.php');          // Functions to handle DB data (DML)
 211      require_once($CFG->libdir .'/datalib.php');         // Legacy lib with a big-mix of functions.
 212      require_once($CFG->libdir .'/accesslib.php');       // Access control functions
 213      require_once($CFG->libdir .'/deprecatedlib.php');   // Deprecated functions included for backward compatibility
 214      require_once($CFG->libdir .'/moodlelib.php');       // Other general-purpose functions
 215      require_once($CFG->libdir .'/eventslib.php');       // Events functions
 216      require_once($CFG->libdir .'/grouplib.php');        // Groups functions
 217  
 218      //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
 219      //the problem is that we need specific version of quickforms and hacked excel files :-(
 220      ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
 221  
 222  /// Disable errors for now - needed for installation when debug enabled in config.php
 223      if (isset($CFG->debug)) {
 224          $originalconfigdebug = $CFG->debug;
 225          unset($CFG->debug);
 226      } else {
 227          $originalconfigdebug = -1;
 228      }
 229  
 230  /// Set the client/server and connection to utf8
 231  /// and configure some other specific variables for each db
 232      configure_dbconnection();
 233  
 234  /// Load up any configuration from the config table
 235      $CFG = get_config();
 236  
 237  /// Turn on SQL logging if required
 238      if (!empty($CFG->logsql)) {
 239          $db->LogSQL();
 240      }
 241  
 242  /// Prevent warnings from roles when upgrading with debug on
 243      if (isset($CFG->debug)) {
 244          $originaldatabasedebug = $CFG->debug;
 245          unset($CFG->debug);
 246      } else {
 247          $originaldatabasedebug = -1;
 248      }
 249  
 250  
 251  /// For now, only needed under apache (and probably unstable in other contexts)
 252      if (function_exists('register_shutdown_function')) {
 253          register_shutdown_function('moodle_request_shutdown');
 254      }
 255  
 256  /// Defining the site
 257      if ($SITE = get_site()) {
 258          /**
 259           * If $SITE global from {@link get_site()} is set then SITEID to $SITE->id, otherwise set to 1.
 260           */
 261          define('SITEID', $SITE->id);
 262          /// And the 'default' course
 263          $COURSE = clone($SITE);   // For now.  This will usually get reset later in require_login() etc.
 264      } else {
 265          /**
 266           * @ignore
 267           */
 268          define('SITEID', 1);
 269          /// And the 'default' course
 270          $COURSE = new object;  // no site created yet
 271          $COURSE->id = 1;
 272      }
 273  
 274      // define SYSCONTEXTID in config.php if you want to save some queries (after install or upgrade!)
 275      if (!defined('SYSCONTEXTID')) {
 276          get_system_context();
 277      }
 278  
 279  /// Set error reporting back to normal
 280      if ($originaldatabasedebug == -1) {
 281          $CFG->debug = DEBUG_MINIMAL;
 282      } else {
 283          $CFG->debug = $originaldatabasedebug;
 284      }
 285      if ($originalconfigdebug !== -1) {
 286          $CFG->debug = $originalconfigdebug; 
 287      }
 288      unset($originalconfigdebug);
 289      unset($originaldatabasedebug);
 290      error_reporting($CFG->debug);
 291  
 292  
 293  /// find out if PHP cofigured to display warnings
 294      if (ini_get_bool('display_errors')) {
 295          define('WARN_DISPLAY_ERRORS_ENABLED', true);
 296      }
 297  /// If we want to display Moodle errors, then try and set PHP errors to match
 298      if (!isset($CFG->debugdisplay)) {
 299          //keep it as is during installation
 300      } else if (empty($CFG->debugdisplay)) {
 301          @ini_set('display_errors', '0');
 302          @ini_set('log_errors', '1');
 303      } else {
 304          @ini_set('display_errors', '1');
 305      }
 306  // Even when users want to see errors in the output,
 307  // some parts of Moodle cannot display them at all.
 308  // (Once we are XHTML strict compliant, debugdisplay
 309  //  _must_ go away).
 310      if (defined('MOODLE_SANE_OUTPUT')) {
 311          @ini_set('display_errors', '0');
 312          @ini_set('log_errors', '1');
 313      }
 314  
 315  /// Shared-Memory cache init -- will set $MCACHE
 316  /// $MCACHE is a global object that offers at least add(), set() and delete()
 317  /// with similar semantics to the memcached PHP API http://php.net/memcache
 318  /// Ensure we define rcache - so we can later check for it
 319  /// with a really fast and unambiguous $CFG->rcache === false
 320      if (!empty($CFG->cachetype)) {
 321          if (empty($CFG->rcache)) {
 322              $CFG->rcache = false;
 323          } else {
 324              $CFG->rcache = true;
 325          }
 326  
 327          // do not try to initialize if cache disabled
 328          if (!$CFG->rcache) {
 329              $CFG->cachetype = '';
 330          }
 331  
 332          if ($CFG->cachetype === 'memcached' && !empty($CFG->memcachedhosts)) {
 333              if (!init_memcached()) {
 334                  debugging("Error initialising memcached");
 335                  $CFG->cachetype = '';
 336                  $CFG->rcache = false;
 337              }
 338          } else if ($CFG->cachetype === 'eaccelerator') {
 339              if (!init_eaccelerator()) {
 340                  debugging("Error initialising eaccelerator cache");
 341                  $CFG->cachetype = '';
 342                  $CFG->rcache = false;                
 343              }
 344          }
 345  
 346      } else { // just make sure it is defined
 347          $CFG->cachetype = '';
 348          $CFG->rcache    = false;
 349      }
 350  
 351  /// Set a default enrolment configuration (see bug 1598)
 352      if (!isset($CFG->enrol)) {
 353          $CFG->enrol = 'manual';
 354      }
 355  
 356  /// Set default enabled enrolment plugins
 357      if (!isset($CFG->enrol_plugins_enabled)) {
 358          $CFG->enrol_plugins_enabled = 'manual';
 359      }
 360  
 361  /// File permissions on created directories in the $CFG->dataroot
 362  
 363      if (empty($CFG->directorypermissions)) {
 364          $CFG->directorypermissions = 0777;      // Must be octal (that's why it's here)
 365      }
 366  
 367  /// Calculate and set $CFG->ostype to be used everywhere. Possible values are:
 368  /// - WINDOWS: for any Windows flavour.
 369  /// - UNIX: for the rest
 370  /// Also, $CFG->os can continue being used if more specialization is required
 371      if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
 372          $CFG->ostype = 'WINDOWS';
 373      } else {
 374          $CFG->ostype = 'UNIX';
 375      }
 376      $CFG->os = PHP_OS;
 377  
 378  /// Set up default frame target string, based on $CFG->framename
 379      $CFG->frametarget = frametarget();
 380  
 381  /// Setup cache dir for Smarty and others
 382      if (!file_exists($CFG->dataroot .'/cache')) {
 383          make_upload_directory('cache');
 384      }
 385  
 386  /// Set up smarty template system
 387      //require_once($CFG->libdir .'/smarty/Smarty.class.php');
 388      //$smarty = new Smarty;
 389      //$smarty->template_dir = $CFG->dirroot .'/templates/'. $CFG->template;
 390      //if (!file_exists($CFG->dataroot .'/cache/smarty')) {
 391      //    make_upload_directory('cache/smarty');
 392      //}
 393      //$smarty->compile_dir = $CFG->dataroot .'/cache/smarty';
 394  
 395  /// Set up session handling
 396      if(empty($CFG->respectsessionsettings)) {
 397          if (empty($CFG->dbsessions)) {   /// File-based sessions
 398  
 399              // Some distros disable GC by setting probability to 0
 400              // overriding the PHP default of 1
 401              // (gc_probability is divided by gc_divisor, which defaults to 1000)
 402              if (ini_get('session.gc_probability') == 0) {
 403                  ini_set('session.gc_probability', 1);
 404              }
 405  
 406              if (!empty($CFG->sessiontimeout)) {
 407                  ini_set('session.gc_maxlifetime', $CFG->sessiontimeout);
 408              }
 409  
 410              if (!file_exists($CFG->dataroot .'/sessions')) {
 411                  make_upload_directory('sessions');
 412              }
 413              ini_set('session.save_path', $CFG->dataroot .'/sessions');
 414  
 415          } else {                         /// Database sessions
 416              ini_set('session.save_handler', 'user');
 417  
 418              $ADODB_SESSION_DRIVER  = $CFG->dbtype;
 419              $ADODB_SESSION_CONNECT = $CFG->dbhost;
 420              $ADODB_SESSION_USER    = $CFG->dbuser;
 421              $ADODB_SESSION_PWD     = $CFG->dbpass;
 422              $ADODB_SESSION_DB      = $CFG->dbname;
 423              $ADODB_SESSION_TBL     = $CFG->prefix.'sessions2';
 424              if (!empty($CFG->sessiontimeout)) {
 425                  $ADODB_SESS_LIFE   = $CFG->sessiontimeout;
 426              }
 427  
 428              require_once($CFG->libdir. '/adodb/session/adodb-session2.php');
 429          }
 430      }
 431  /// Set sessioncookie and sessioncookiepath variable if it isn't already
 432      if (!isset($CFG->sessioncookie)) {
 433          $CFG->sessioncookie = '';
 434      }
 435      if (!isset($CFG->sessioncookiepath)) {
 436          $CFG->sessioncookiepath = '/';
 437      }
 438  
 439  /// Configure ampersands in URLs
 440  
 441      @ini_set('arg_separator.output', '&amp;');
 442  
 443  /// Work around for a PHP bug   see MDL-11237
 444    
 445      @ini_set('pcre.backtrack_limit', 20971520);  // 20 MB 
 446  
 447  /// Location of standard files
 448  
 449      $CFG->wordlist    = $CFG->libdir .'/wordlist.txt';
 450      $CFG->javascript  = $CFG->libdir .'/javascript.php';
 451      $CFG->moddata     = 'moddata';
 452  
 453  // Alas, in some cases we cannot deal with magic_quotes.
 454      if (defined('MOODLE_SANE_INPUT') && ini_get_bool('magic_quotes_gpc')) {
 455          mdie("Facilities that require MOODLE_SANE_INPUT "
 456               . "cannot work with magic_quotes_gpc. Please disable "
 457               . "magic_quotes_gpc.");
 458      }
 459  /// A hack to get around magic_quotes_gpc being turned off
 460  /// It is strongly recommended to enable "magic_quotes_gpc"!
 461      if (!ini_get_bool('magic_quotes_gpc') && !defined('MOODLE_SANE_INPUT') ) {
 462          function addslashes_deep($value) {
 463              $value = is_array($value) ?
 464                      array_map('addslashes_deep', $value) :
 465                      addslashes($value);
 466              return $value;
 467          }
 468          $_POST = array_map('addslashes_deep', $_POST);
 469          $_GET = array_map('addslashes_deep', $_GET);
 470          $_COOKIE = array_map('addslashes_deep', $_COOKIE);
 471          $_REQUEST = array_map('addslashes_deep', $_REQUEST);
 472          if (!empty($_SERVER['REQUEST_URI'])) {
 473              $_SERVER['REQUEST_URI'] = addslashes($_SERVER['REQUEST_URI']);
 474          }
 475          if (!empty($_SERVER['QUERY_STRING'])) {
 476              $_SERVER['QUERY_STRING'] = addslashes($_SERVER['QUERY_STRING']);
 477          }
 478          if (!empty($_SERVER['HTTP_REFERER'])) {
 479              $_SERVER['HTTP_REFERER'] = addslashes($_SERVER['HTTP_REFERER']);
 480          }
 481         if (!empty($_SERVER['PATH_INFO'])) {
 482              $_SERVER['PATH_INFO'] = addslashes($_SERVER['PATH_INFO']);
 483          }
 484          if (!empty($_SERVER['PHP_SELF'])) {
 485              $_SERVER['PHP_SELF'] = addslashes($_SERVER['PHP_SELF']);
 486          }
 487          if (!empty($_SERVER['PATH_TRANSLATED'])) {
 488              $_SERVER['PATH_TRANSLATED'] = addslashes($_SERVER['PATH_TRANSLATED']);
 489          }
 490      }
 491  
 492  
 493  /// The following code can emulate "register globals" if required.
 494  /// This hack is no longer being applied as of Moodle 1.6 unless you really 
 495  /// really want to use it (by defining  $CFG->enableglobalshack = true)
 496  
 497      if (!empty($CFG->enableglobalshack) && !defined('MOODLE_SANE_INPUT')) {
 498          if (!empty($CFG->detect_unchecked_vars)) {
 499              global $UNCHECKED_VARS;
 500              $UNCHECKED_VARS->url = $_SERVER['PHP_SELF'];
 501              $UNCHECKED_VARS->vars = array();
 502          }
 503          if (isset($_GET)) {
 504              extract($_GET, EXTR_SKIP);    // Skip existing variables, ie CFG
 505              if (!empty($CFG->detect_unchecked_vars)) {
 506                  foreach ($_GET as $key => $val) {
 507                      $UNCHECKED_VARS->vars[$key]=$val;
 508                  }
 509              }
 510          }
 511          if (isset($_POST)) {
 512              extract($_POST, EXTR_SKIP);   // Skip existing variables, ie CFG
 513              if (!empty($CFG->detect_unchecked_vars)) {
 514                  foreach ($_POST as $key => $val) {
 515                      $UNCHECKED_VARS->vars[$key]=$val;
 516                  }
 517              }
 518          }
 519          if (isset($_SERVER)) {
 520              extract($_SERVER);
 521          }
 522      }
 523  
 524  
 525  /// Load up global environment variables
 526  
 527      if (!isset($CFG->cookiesecure) or strpos($CFG->wwwroot, 'https://') !== 0) {
 528          $CFG->cookiesecure = false;
 529      }
 530  
 531      if (!isset($CFG->cookiehttponly)) {
 532          $CFG->cookiehttponly = false;
 533      }
 534  
 535      //discard session ID from POST, GET and globals to tighten security,
 536      //this session fixation prevention can not be used in cookieless mode
 537      if (empty($CFG->usesid) && !defined('MOODLE_SANE_INPUT')) {
 538          unset(${'MoodleSession'.$CFG->sessioncookie});
 539          unset($_GET['MoodleSession'.$CFG->sessioncookie]);
 540          unset($_POST['MoodleSession'.$CFG->sessioncookie]);
 541      }
 542      //compatibility hack for Moodle Cron, cookies not deleted, but set to "deleted" - should not be needed with $nomoodlecookie in cron.php now 
 543      if (!empty($_COOKIE['MoodleSession'.$CFG->sessioncookie]) && $_COOKIE['MoodleSession'.$CFG->sessioncookie] == "deleted") {
 544          unset($_COOKIE['MoodleSession'.$CFG->sessioncookie]);
 545      }
 546      if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie]) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] == "deleted") {
 547          unset($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie]);
 548      }
 549      if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
 550          require_once("$CFG->dirroot/lib/cookieless.php");
 551          sid_start_ob();
 552      }
 553  
 554      if (empty($nomoodlecookie)) {
 555          session_name('MoodleSession'.$CFG->sessioncookie);
 556          if (check_php_version('5.2.0')) {
 557              session_set_cookie_params(0, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
 558          } else {
 559              session_set_cookie_params(0, $CFG->sessioncookiepath, '', $CFG->cookiesecure);
 560          }
 561          @session_start();
 562          if (! isset($_SESSION['SESSION'])) {
 563              $_SESSION['SESSION'] = new object;
 564              $_SESSION['SESSION']->session_test = random_string(10);
 565              if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
 566                  $_SESSION['SESSION']->has_timed_out = true;
 567              }
 568              if (check_php_version('5.2.0')) {
 569                  setcookie('MoodleSessionTest'.$CFG->sessioncookie, $_SESSION['SESSION']->session_test, 0, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
 570              } else {
 571                  setcookie('MoodleSessionTest'.$CFG->sessioncookie, $_SESSION['SESSION']->session_test, 0, $CFG->sessioncookiepath, '', $CFG->cookiesecure);
 572              }
 573              $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] = $_SESSION['SESSION']->session_test;
 574          }
 575          if (! isset($_SESSION['USER']))    {
 576              $_SESSION['USER']    = new object;
 577          }
 578  
 579          $SESSION = &$_SESSION['SESSION'];   // Makes them easier to reference
 580          $USER    = &$_SESSION['USER'];
 581          if (!isset($USER->id)) {
 582              $USER->id = 0; // to enable proper function of $CFG->notloggedinroleid hack
 583          }
 584      }
 585      else {
 586          $SESSION  = NULL;
 587          $USER     = new object();
 588          $USER->id = 0; // user not logged in when session disabled
 589          if (isset($CFG->mnet_localhost_id)) {
 590              $USER->mnethostid = $CFG->mnet_localhost_id;
 591          }
 592      }
 593  
 594      if (defined('FULLME')) {     // Usually in command-line scripts like admin/cron.php
 595          $FULLME = FULLME;
 596          $ME = FULLME;
 597      } else {
 598          $FULLME = qualified_me();
 599          $ME = strip_querystring($FULLME);
 600      }
 601  
 602  /// In VERY rare cases old PHP server bugs (it has been found on PHP 4.1.2 running
 603  /// as a CGI under IIS on Windows) may require that you uncomment the following:
 604  //  session_register("USER");
 605  //  session_register("SESSION");
 606  
 607  
 608  
 609  /// Load up theme variables (colours etc)
 610  
 611      if (!isset($CFG->themedir)) {
 612          $CFG->themedir = $CFG->dirroot.'/theme';
 613          $CFG->themewww = $CFG->wwwroot.'/theme';
 614      }
 615      $CFG->httpsthemewww = $CFG->themewww; 
 616  
 617      if (isset($_GET['theme'])) {
 618          if ($CFG->allowthemechangeonurl || confirm_sesskey()) {
 619              $themename = clean_param($_GET['theme'], PARAM_SAFEDIR);
 620              if (($themename != '') and file_exists($CFG->themedir.'/'.$themename)) {
 621                  $SESSION->theme = $themename;
 622              }
 623              unset($themename);
 624          }
 625      }
 626  
 627      if (!isset($CFG->theme)) {
 628          $CFG->theme = 'standardwhite';
 629      }
 630  
 631  /// now do a session test to prevent random user switching - observed on some PHP/Apache combinations,
 632  /// disable checks when working in cookieless mode
 633      if (empty($CFG->usesid) || !empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
 634          if ($SESSION != NULL) {
 635              if (empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
 636                  report_session_error();
 637              } else if (isset($SESSION->session_test) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] != $SESSION->session_test) {
 638                  report_session_error();
 639              }
 640          }
 641      }
 642  
 643  
 644  /// Set language/locale of printed times.  If user has chosen a language that
 645  /// that is different from the site language, then use the locale specified
 646  /// in the language file.  Otherwise, if the admin hasn't specified a locale
 647  /// then use the one from the default language.  Otherwise (and this is the
 648  /// majority of cases), use the stored locale specified by admin.
 649      if ($SESSION !== NULL && isset($_GET['lang']) && ($lang = clean_param($_GET['lang'], PARAM_SAFEDIR))) {
 650          if (file_exists($CFG->dataroot .'/lang/'. $lang) or file_exists($CFG->dirroot .'/lang/'. $lang)) {
 651              $SESSION->lang = $lang;
 652          } else if (file_exists($CFG->dataroot.'/lang/'.$lang.'_utf8') or 
 653                     file_exists($CFG->dirroot .'/lang/'.$lang.'_utf8')) {
 654              $SESSION->lang = $lang.'_utf8';
 655          }
 656      }
 657  
 658      setup_lang_from_browser();
 659  
 660      unset($lang);
 661  
 662      if (empty($CFG->lang)) {
 663          if (empty($SESSION->lang)) {
 664              $CFG->lang = 'en_utf8';
 665          } else {
 666              $CFG->lang = $SESSION->lang;
 667          }
 668      }
 669      
 670      // set default locale and themes - might be changed again later from require_login()
 671      course_setup();
 672  
 673      if (!empty($CFG->opentogoogle)) {
 674          if (empty($USER->id)) {  // Ignore anyone logged in
 675              if (!empty($_SERVER['HTTP_USER_AGENT'])) {
 676                  if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
 677                      $USER = guest_user();
 678                  } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
 679                      $USER = guest_user();
 680                  } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) {  // Yahoo
 681                      $USER = guest_user();
 682                  } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) {  // Zoomspider
 683                      $USER = guest_user();
 684                  } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSNBOT') !== false ) {  // MSN Search
 685                      $USER = guest_user();
 686                  }
 687              }
 688              if (empty($USER) && !empty($_SERVER['HTTP_REFERER'])) {
 689                  if (strpos($_SERVER['HTTP_REFERER'], 'google') !== false ) {
 690                      $USER = guest_user();
 691                  } else if (strpos($_SERVER['HTTP_REFERER'], 'altavista') !== false ) {
 692                      $USER = guest_user();
 693                  }
 694              }
 695              if (!empty($USER)) {
 696                  load_all_capabilities();
 697              }
 698          }
 699      }
 700  
 701      if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') {    // Temporary measure to help with XHTML validation
 702          if (isset($_SERVER['HTTP_USER_AGENT']) and empty($_SESSION['USER']->id)) {      // Allow W3CValidator in as user called w3cvalidator (or guest)
 703              if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
 704                  (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
 705                  if ($USER = get_complete_user_data("username", "w3cvalidator")) {
 706                      $USER->ignoresesskey = true;
 707                  } else {
 708                      $USER = guest_user();
 709                  }
 710              }
 711          }
 712      }
 713  
 714  /// Apache log intergration. In apache conf file one can use ${MOODULEUSER}n in
 715  /// LogFormat to get the current logged in username in moodle.
 716      if ($USER && function_exists('apache_note')
 717          && !empty($CFG->apacheloguser) && isset($USER->username)) {
 718          $apachelog_userid = $USER->id;
 719          $apachelog_username = clean_filename($USER->username);
 720          $apachelog_name = '';
 721          if (isset($USER->firstname)) {
 722              // We can assume both will be set
 723              // - even if to empty.
 724              $apachelog_name = clean_filename($USER->firstname . " " .
 725                                               $USER->lastname);
 726          }
 727          if (isset($USER->realuser)) {
 728              if ($realuser = get_record('user', 'id', $USER->realuser)) {
 729                  $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
 730                  $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
 731                  $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
 732              }
 733          }
 734          switch ($CFG->apacheloguser) {
 735              case 3:
 736                  $logname = $apachelog_username;
 737                  break;
 738              case 2:
 739                  $logname = $apachelog_name;
 740                  break;
 741              case 1:
 742              default:
 743                  $logname = $apachelog_userid;
 744                  break;
 745          }
 746          apache_note('MOODLEUSER', $logname);
 747      }
 748  
 749  /// Adjust ALLOWED_TAGS
 750      adjust_allowed_tags();
 751  
 752  
 753  /// Use a custom script replacement if one exists
 754      if (!empty($CFG->customscripts)) {
 755          if (($customscript = custom_script_path()) !== false) {
 756              require ($customscript);
 757          }
 758      }
 759  
 760  /// note: we can not block non utf-8 installatrions here, because empty mysql database
 761  /// might be converted to utf-8 in admin/index.php during installation
 762  ?>


Generated: Wed Jan 14 11:33:29 2009 Cross-referenced by PHPXref 0.7