Updated the 19 build version to 20090123
[moodle.git] / lib / setup.php
blobff1e1aab269b3af975728b727cc6d0019f0a2c7b
1 <?php
2 /**
3 * setup.php - Sets up sessions, connects to databases and so on
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$
9 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
10 * @package moodlecore
13 ////// DOCUMENTATION IN PHPDOC FORMAT FOR MOODLE GLOBALS AND COMMON OBJECT TYPES /////////////
14 /**
15 * $USER is a global instance of a typical $user record.
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.
28 * @global object(user) $USER
30 global $USER;
31 /**
32 * This global variable is read in from the 'config' table.
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.
39 * @global object(cfg) $CFG
41 global $CFG;
42 /**
43 * Definition of session type
44 * @global object(session) $SESSION
46 global $SESSION;
47 /**
48 * Definition of shared memory cache
50 global $MCACHE;
51 /**
52 * Definition of course type
53 * @global object(course) $COURSE
55 global $COURSE;
56 /**
57 * Definition of db type
58 * @global object(db) $db
60 global $db;
61 /**
62 * $THEME is a global that defines the site theme.
64 * Items found in the theme record:
65 * - $THEME->cellheading - Cell colors.
66 * - $THEME->cellheading2 - Alternate cell colors.
68 * @global object(theme) $THEME
70 global $THEME;
72 /**
73 * HTTPSPAGEREQUIRED is a global to define if the page being displayed must run under HTTPS.
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
78 global $HTTPSPAGEREQUIRED;
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!');
87 if (!isset($CFG->wwwroot)) {
88 trigger_error('Fatal: $CFG->wwwroot is not configured! Exiting.');
89 die;
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;
95 /// Set httpswwwroot default value (this variable will replace $CFG->wwwroot
96 /// inside some URLs used in HTTPSPAGEREQUIRED pages.
97 $CFG->httpswwwroot = $CFG->wwwroot;
99 $CFG->libdir = $CFG->dirroot .'/lib';
101 require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
103 /// Time to start counting
104 init_performance_info();
107 /// If there are any errors in the standard libraries we want to know!
108 error_reporting(E_ALL);
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;
118 /// Connect to the database using adodb
120 /// Set $CFG->dbfamily global
121 /// and configure some other specific variables for each db BEFORE attempting the connection
122 preconfigure_dbconnection();
124 require_once($CFG->libdir .'/adodb/adodb.inc.php'); // Database access functions
126 $db = &ADONewConnection($CFG->dbtype);
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. \'';
132 error_reporting(0); // Hide errors
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);
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');
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>';
158 error_log('ADODB Error: '.$db->ErrorMsg()); // see MDL-14628
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());
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());
180 die;
183 /// Forcing ASSOC mode for ADOdb (some DBs default to FETCH_BOTH)
184 $db->SetFetchMode(ADODB_FETCH_ASSOC);
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!
190 error_reporting(E_ALL); // Show errors from now on.
192 if (!isset($CFG->prefix)) { // Just in case it isn't defined in config.php
193 $CFG->prefix = '';
197 /// Define admin directory
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
203 /// Increase memory limits if possible
204 raise_memory_limit('96M'); // We should never NEED this much but just in case...
206 /// Load up standard libraries
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
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'));
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;
230 /// Set the client/server and connection to utf8
231 /// and configure some other specific variables for each db
232 configure_dbconnection();
234 /// Load up any configuration from the config table
235 $CFG = get_config();
237 /// Turn on SQL logging if required
238 if (!empty($CFG->logsql)) {
239 $db->LogSQL();
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;
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');
256 /// Defining the site
257 if ($SITE = get_site()) {
259 * If $SITE global from {@link get_site()} is set then SITEID to $SITE->id, otherwise set to 1.
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 {
266 * @ignore
268 define('SITEID', 1);
269 /// And the 'default' course
270 $COURSE = new object; // no site created yet
271 $COURSE->id = 1;
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();
279 /// Set error reporting back to normal
280 if ($originaldatabasedebug == -1) {
281 $CFG->debug = DEBUG_MINIMAL;
282 } else {
283 $CFG->debug = $originaldatabasedebug;
285 if ($originalconfigdebug !== -1) {
286 $CFG->debug = $originalconfigdebug;
288 unset($originalconfigdebug);
289 unset($originaldatabasedebug);
290 error_reporting($CFG->debug);
293 /// find out if PHP cofigured to display warnings
294 if (ini_get_bool('display_errors')) {
295 define('WARN_DISPLAY_ERRORS_ENABLED', true);
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');
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');
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;
327 // do not try to initialize if cache disabled
328 if (!$CFG->rcache) {
329 $CFG->cachetype = '';
332 if ($CFG->cachetype === 'memcached' && !empty($CFG->memcachedhosts)) {
333 if (!init_memcached()) {
334 debugging("Error initialising memcached");
335 $CFG->cachetype = '';
336 $CFG->rcache = false;
338 } else if ($CFG->cachetype === 'eaccelerator') {
339 if (!init_eaccelerator()) {
340 debugging("Error initialising eaccelerator cache");
341 $CFG->cachetype = '';
342 $CFG->rcache = false;
346 } else { // just make sure it is defined
347 $CFG->cachetype = '';
348 $CFG->rcache = false;
351 /// Set a default enrolment configuration (see bug 1598)
352 if (!isset($CFG->enrol)) {
353 $CFG->enrol = 'manual';
356 /// Set default enabled enrolment plugins
357 if (!isset($CFG->enrol_plugins_enabled)) {
358 $CFG->enrol_plugins_enabled = 'manual';
361 /// File permissions on created directories in the $CFG->dataroot
363 if (empty($CFG->directorypermissions)) {
364 $CFG->directorypermissions = 0777; // Must be octal (that's why it's here)
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';
376 $CFG->os = PHP_OS;
378 /// Set up default frame target string, based on $CFG->framename
379 $CFG->frametarget = frametarget();
381 /// Setup cache dir for Smarty and others
382 if (!file_exists($CFG->dataroot .'/cache')) {
383 make_upload_directory('cache');
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');
393 //$smarty->compile_dir = $CFG->dataroot .'/cache/smarty';
395 /// Set up session handling
396 if(empty($CFG->respectsessionsettings)) {
397 if (empty($CFG->dbsessions)) { /// File-based sessions
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);
406 if (!empty($CFG->sessiontimeout)) {
407 ini_set('session.gc_maxlifetime', $CFG->sessiontimeout);
410 if (!file_exists($CFG->dataroot .'/sessions')) {
411 make_upload_directory('sessions');
413 ini_set('session.save_path', $CFG->dataroot .'/sessions');
415 } else { /// Database sessions
416 ini_set('session.save_handler', 'user');
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;
428 require_once($CFG->libdir. '/adodb/session/adodb-session2.php');
431 /// Set sessioncookie and sessioncookiepath variable if it isn't already
432 if (!isset($CFG->sessioncookie)) {
433 $CFG->sessioncookie = '';
435 if (!isset($CFG->sessioncookiedomain)) {
436 $CFG->sessioncookiedomain = '';
438 if (!isset($CFG->sessioncookiepath)) {
439 $CFG->sessioncookiepath = '/';
442 /// Configure ampersands in URLs
444 @ini_set('arg_separator.output', '&amp;');
446 /// Work around for a PHP bug see MDL-11237
448 @ini_set('pcre.backtrack_limit', 20971520); // 20 MB
450 /// Location of standard files
452 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
453 $CFG->javascript = $CFG->libdir .'/javascript.php';
454 $CFG->moddata = 'moddata';
456 // Alas, in some cases we cannot deal with magic_quotes.
457 if (defined('MOODLE_SANE_INPUT') && ini_get_bool('magic_quotes_gpc')) {
458 mdie("Facilities that require MOODLE_SANE_INPUT "
459 . "cannot work with magic_quotes_gpc. Please disable "
460 . "magic_quotes_gpc.");
462 /// A hack to get around magic_quotes_gpc being turned off
463 /// It is strongly recommended to enable "magic_quotes_gpc"!
464 if (!ini_get_bool('magic_quotes_gpc') && !defined('MOODLE_SANE_INPUT') ) {
465 function addslashes_deep($value) {
466 $value = is_array($value) ?
467 array_map('addslashes_deep', $value) :
468 addslashes($value);
469 return $value;
471 $_POST = array_map('addslashes_deep', $_POST);
472 $_GET = array_map('addslashes_deep', $_GET);
473 $_COOKIE = array_map('addslashes_deep', $_COOKIE);
474 $_REQUEST = array_map('addslashes_deep', $_REQUEST);
475 if (!empty($_SERVER['REQUEST_URI'])) {
476 $_SERVER['REQUEST_URI'] = addslashes($_SERVER['REQUEST_URI']);
478 if (!empty($_SERVER['QUERY_STRING'])) {
479 $_SERVER['QUERY_STRING'] = addslashes($_SERVER['QUERY_STRING']);
481 if (!empty($_SERVER['HTTP_REFERER'])) {
482 $_SERVER['HTTP_REFERER'] = addslashes($_SERVER['HTTP_REFERER']);
484 if (!empty($_SERVER['PATH_INFO'])) {
485 $_SERVER['PATH_INFO'] = addslashes($_SERVER['PATH_INFO']);
487 if (!empty($_SERVER['PHP_SELF'])) {
488 $_SERVER['PHP_SELF'] = addslashes($_SERVER['PHP_SELF']);
490 if (!empty($_SERVER['PATH_TRANSLATED'])) {
491 $_SERVER['PATH_TRANSLATED'] = addslashes($_SERVER['PATH_TRANSLATED']);
495 /// neutralise nasty chars in PHP_SELF
496 if (isset($_SERVER['PHP_SELF'])) {
497 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
498 if ($phppos !== false) {
499 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
501 unset($phppos);
504 /// The following code can emulate "register globals" if required.
505 /// This hack is no longer being applied as of Moodle 1.6 unless you really
506 /// really want to use it (by defining $CFG->enableglobalshack = true)
508 if (!empty($CFG->enableglobalshack) && !defined('MOODLE_SANE_INPUT')) {
509 if (!empty($CFG->detect_unchecked_vars)) {
510 global $UNCHECKED_VARS;
511 $UNCHECKED_VARS->url = $_SERVER['PHP_SELF'];
512 $UNCHECKED_VARS->vars = array();
514 if (isset($_GET)) {
515 extract($_GET, EXTR_SKIP); // Skip existing variables, ie CFG
516 if (!empty($CFG->detect_unchecked_vars)) {
517 foreach ($_GET as $key => $val) {
518 $UNCHECKED_VARS->vars[$key]=$val;
522 if (isset($_POST)) {
523 extract($_POST, EXTR_SKIP); // Skip existing variables, ie CFG
524 if (!empty($CFG->detect_unchecked_vars)) {
525 foreach ($_POST as $key => $val) {
526 $UNCHECKED_VARS->vars[$key]=$val;
530 if (isset($_SERVER)) {
531 extract($_SERVER);
536 /// Load up global environment variables
538 if (!isset($CFG->cookiesecure) or strpos($CFG->wwwroot, 'https://') !== 0) {
539 $CFG->cookiesecure = false;
542 if (!isset($CFG->cookiehttponly)) {
543 $CFG->cookiehttponly = false;
546 //discard session ID from POST, GET and globals to tighten security,
547 //this session fixation prevention can not be used in cookieless mode
548 if (empty($CFG->usesid) && !defined('MOODLE_SANE_INPUT')) {
549 unset(${'MoodleSession'.$CFG->sessioncookie});
550 unset($_GET['MoodleSession'.$CFG->sessioncookie]);
551 unset($_POST['MoodleSession'.$CFG->sessioncookie]);
553 //compatibility hack for Moodle Cron, cookies not deleted, but set to "deleted" - should not be needed with $nomoodlecookie in cron.php now
554 if (!empty($_COOKIE['MoodleSession'.$CFG->sessioncookie]) && $_COOKIE['MoodleSession'.$CFG->sessioncookie] == "deleted") {
555 unset($_COOKIE['MoodleSession'.$CFG->sessioncookie]);
557 if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie]) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] == "deleted") {
558 unset($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie]);
560 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
561 require_once("$CFG->dirroot/lib/cookieless.php");
562 sid_start_ob();
565 if (empty($nomoodlecookie)) {
566 session_name('MoodleSession'.$CFG->sessioncookie);
567 if (check_php_version('5.2.0')) {
568 session_set_cookie_params(0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
569 } else {
570 session_set_cookie_params(0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure);
572 @session_start();
573 if (! isset($_SESSION['SESSION'])) {
574 $_SESSION['SESSION'] = new object;
575 $_SESSION['SESSION']->session_test = random_string(10);
576 if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
577 $_SESSION['SESSION']->has_timed_out = true;
579 if (check_php_version('5.2.0')) {
580 setcookie('MoodleSessionTest'.$CFG->sessioncookie, $_SESSION['SESSION']->session_test, 0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
581 } else {
582 setcookie('MoodleSessionTest'.$CFG->sessioncookie, $_SESSION['SESSION']->session_test, 0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure);
584 $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] = $_SESSION['SESSION']->session_test;
586 if (! isset($_SESSION['USER'])) {
587 $_SESSION['USER'] = new object;
590 $SESSION = &$_SESSION['SESSION']; // Makes them easier to reference
591 $USER = &$_SESSION['USER'];
592 if (!isset($USER->id)) {
593 $USER->id = 0; // to enable proper function of $CFG->notloggedinroleid hack
596 else {
597 $SESSION = NULL;
598 $USER = new object();
599 $USER->id = 0; // user not logged in when session disabled
600 if (isset($CFG->mnet_localhost_id)) {
601 $USER->mnethostid = $CFG->mnet_localhost_id;
605 if (defined('FULLME')) { // Usually in command-line scripts like admin/cron.php
606 $FULLME = FULLME;
607 $ME = FULLME;
608 } else {
609 $FULLME = qualified_me();
610 $ME = strip_querystring($FULLME);
613 /// In VERY rare cases old PHP server bugs (it has been found on PHP 4.1.2 running
614 /// as a CGI under IIS on Windows) may require that you uncomment the following:
615 // session_register("USER");
616 // session_register("SESSION");
620 /// Load up theme variables (colours etc)
622 if (!isset($CFG->themedir)) {
623 $CFG->themedir = $CFG->dirroot.'/theme';
624 $CFG->themewww = $CFG->wwwroot.'/theme';
626 $CFG->httpsthemewww = $CFG->themewww;
628 if (isset($_GET['theme'])) {
629 if ($CFG->allowthemechangeonurl || confirm_sesskey()) {
630 $themename = clean_param($_GET['theme'], PARAM_SAFEDIR);
631 if (($themename != '') and file_exists($CFG->themedir.'/'.$themename)) {
632 $SESSION->theme = $themename;
634 unset($themename);
638 if (!isset($CFG->theme)) {
639 $CFG->theme = 'standardwhite';
642 /// now do a session test to prevent random user switching - observed on some PHP/Apache combinations,
643 /// disable checks when working in cookieless mode
644 if (empty($CFG->usesid) || !empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
645 if ($SESSION != NULL) {
646 if (empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
647 report_session_error();
648 } else if (isset($SESSION->session_test) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] != $SESSION->session_test) {
649 report_session_error();
655 /// Set language/locale of printed times. If user has chosen a language that
656 /// that is different from the site language, then use the locale specified
657 /// in the language file. Otherwise, if the admin hasn't specified a locale
658 /// then use the one from the default language. Otherwise (and this is the
659 /// majority of cases), use the stored locale specified by admin.
660 if ($SESSION !== NULL && isset($_GET['lang']) && ($lang = clean_param($_GET['lang'], PARAM_SAFEDIR))) {
661 if (file_exists($CFG->dataroot .'/lang/'. $lang) or file_exists($CFG->dirroot .'/lang/'. $lang)) {
662 $SESSION->lang = $lang;
663 } else if (file_exists($CFG->dataroot.'/lang/'.$lang.'_utf8') or
664 file_exists($CFG->dirroot .'/lang/'.$lang.'_utf8')) {
665 $SESSION->lang = $lang.'_utf8';
669 setup_lang_from_browser();
671 unset($lang);
673 if (empty($CFG->lang)) {
674 if (empty($SESSION->lang)) {
675 $CFG->lang = 'en_utf8';
676 } else {
677 $CFG->lang = $SESSION->lang;
681 // set default locale and themes - might be changed again later from require_login()
682 course_setup();
684 if (!empty($CFG->opentogoogle)) {
685 if (empty($USER->id)) { // Ignore anyone logged in
686 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
687 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
688 $USER = guest_user();
689 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
690 $USER = guest_user();
691 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) { // Yahoo
692 $USER = guest_user();
693 } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) { // Zoomspider
694 $USER = guest_user();
695 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSNBOT') !== false ) { // MSN Search
696 $USER = guest_user();
699 if (!empty($CFG->guestloginbutton) && empty($USER) && !empty($_SERVER['HTTP_REFERER'])) {
700 if (strpos($_SERVER['HTTP_REFERER'], 'google') !== false ) {
701 $USER = guest_user();
702 } else if (strpos($_SERVER['HTTP_REFERER'], 'altavista') !== false ) {
703 $USER = guest_user();
706 if (!empty($USER)) {
707 load_all_capabilities();
712 if (!empty($CFG->guestloginbutton)) {
713 if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') { // Temporary measure to help with XHTML validation
714 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($_SESSION['USER']->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
715 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
716 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
717 if ($USER = get_complete_user_data("username", "w3cvalidator")) {
718 $USER->ignoresesskey = true;
719 } else {
720 $USER = guest_user();
727 /// Apache log intergration. In apache conf file one can use ${MOODULEUSER}n in
728 /// LogFormat to get the current logged in username in moodle.
729 if ($USER && function_exists('apache_note')
730 && !empty($CFG->apacheloguser) && isset($USER->username)) {
731 $apachelog_userid = $USER->id;
732 $apachelog_username = clean_filename($USER->username);
733 $apachelog_name = '';
734 if (isset($USER->firstname)) {
735 // We can assume both will be set
736 // - even if to empty.
737 $apachelog_name = clean_filename($USER->firstname . " " .
738 $USER->lastname);
740 if (isset($USER->realuser)) {
741 if ($realuser = get_record('user', 'id', $USER->realuser)) {
742 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
743 $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
744 $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
747 switch ($CFG->apacheloguser) {
748 case 3:
749 $logname = $apachelog_username;
750 break;
751 case 2:
752 $logname = $apachelog_name;
753 break;
754 case 1:
755 default:
756 $logname = $apachelog_userid;
757 break;
759 apache_note('MOODLEUSER', $logname);
762 /// Adjust ALLOWED_TAGS
763 adjust_allowed_tags();
766 /// Use a custom script replacement if one exists
767 if (!empty($CFG->customscripts)) {
768 if (($customscript = custom_script_path()) !== false) {
769 require ($customscript);
773 /// note: we can not block non utf-8 installatrions here, because empty mysql database
774 /// might be converted to utf-8 in admin/index.php during installation