MDL-12717 use apply_default_exception_settings before other admin defaults; merged...
[moodle.git] / lib / setup.php
CommitLineData
da8759cb 1<?php
2/**
3 * setup.php - Sets up sessions, connects to databases and so on
4 *
75249234 5 * Normally this is only called by the main config.php file
6 * Normally this file does not need to be edited.
da8759cb 7 * @author Martin Dougiamas
8 * @version $Id$
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/**
735b8567 15 * $USER is a global instance of a typical $user record.
da8759cb 16 *
735b8567 17 * Items found in the user record:
da8759cb 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 *
75249234 28 * @global object(user) $USER
da8759cb 29 */
674fb525 30global $USER;
da8759cb 31/**
735b8567 32 * This global variable is read in from the 'config' table.
da8759cb 33 *
735b8567 34 * Some typical settings in the $CFG global:
da8759cb 35 * - $CFG->wwwroot - Path to moodle index directory in url format.
36 * - $CFG->dataroot - Path to moodle index directory on server's filesystem.
e57d9d69 37 * - $CFG->libdir - Path to moodle's library folder on server's filesystem.
da8759cb 38 *
674fb525 39 * @global object(cfg) $CFG
da8759cb 40 */
674fb525 41global $CFG;
da8759cb 42/**
43 * Definition of session type
75249234 44 * @global object(session) $SESSION
da8759cb 45 */
46global $SESSION;
419e1d93 47/**
48 * Definition of shared memory cache
49 */
50global $MCACHE;
da8759cb 51/**
52 * Definition of course type
75249234 53 * @global object(course) $COURSE
da8759cb 54 */
55global $COURSE;
56/**
57 * Definition of db type
75249234 58 * @global object(db) $db
da8759cb 59 */
60global $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 *
75249234 68 * @global object(theme) $THEME
da8759cb 69 */
70global $THEME;
f9903ed0 71
9d0dd812 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*/
78global $HTTPSPAGEREQUIRED;
79
80
578dcc40 81/// First try to detect some attacks on older buggy PHP versions
735b8567 82 if (isset($_REQUEST['GLOBALS']) || isset($_COOKIE['GLOBALS']) || isset($_FILES['GLOBALS'])) {
578dcc40 83 die('Fatal: Illegal GLOBALS overwrite attempt detected!');
84 }
85
86
36ec6afe 87 if (!isset($CFG->wwwroot)) {
a670108e 88 trigger_error('Fatal: $CFG->wwwroot is not configured! Exiting.');
36ec6afe 89 die;
90 }
75249234 91
220a90c5 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
9d0dd812 95/// Set httpswwwroot default value (this variable will replace $CFG->wwwroot
96/// inside some URLs used in HTTPSPAGEREQUIRED pages.
d3f9f1f8 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
9d0dd812 102
c2fd9e95 103/// Time to start counting
66552670 104 init_performance_info();
105
b8cea9b2 106
74944b73 107/// If there are any errors in the standard libraries we want to know!
346b1a24 108 error_reporting(E_ALL);
f9903ed0 109
d7196099 110/// Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
0a194c4c 111/// http://www.google.com/webmasters/faq.html#prefetchblock
d7196099 112 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
0a194c4c 113 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
d7196099 114 trigger_error('Prefetch request forbidden.');
115 exit;
116 }
117
a8a71844 118/// Connect to the database using adodb
119
35c1c575 120/// Set $CFG->dbfamily global
121/// and configure some other specific variables for each db BEFORE attempting the connection
122 preconfigure_dbconnection();
1685298e 123
da8759cb 124 require_once($CFG->libdir .'/adodb/adodb.inc.php'); // Database access functions
fa3ba0f6 125
75249234 126 $db = &ADONewConnection($CFG->dbtype);
fa3ba0f6 127
ad6e0523 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
75249234 132 error_reporting(0); // Hide errors
9f71c9e7 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) {
b350cb9d 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>';
53f39b32 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>';
b350cb9d 156 echo '</body></html>';
880a6f6b 157
158 if (!empty($CFG->emailconnectionerrorsto)) {
159 mail($CFG->emailconnectionerrorsto,
160 'WARNING: Database connection error: '.$CFG->wwwroot,
161 'Connection error: '.$CFG->wwwroot);
162 }
9f71c9e7 163 die;
a8a71844 164 }
165
8e6a09bd 166/// Forcing ASSOC mode for ADOdb (some DBs default to FETCH_BOTH)
1b255021 167 $db->SetFetchMode(ADODB_FETCH_ASSOC);
73bb7f8d 168
7104d80d 169/// Starting here we have a correct DB conection but me must avoid
170/// to execute any DB transaction until "set names" has been executed
171/// some lines below!
6aaa17c7 172
0cb29cc4 173 error_reporting(E_ALL); // Show errors from now on.
174
b6bae251 175 if (!isset($CFG->prefix)) { // Just in case it isn't defined in config.php
da8759cb 176 $CFG->prefix = '';
b6bae251 177 }
178
179
dae73c05 180/// Define admin directory
181
182 if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
1040ea85 183 $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
dae73c05 184 }
185
76f3815b 186/// Increase memory limits if possible
4eefee97 187 raise_memory_limit('96M'); // We should never NEED this much but just in case...
a8a71844 188
75249234 189/// Load up standard libraries
76f3815b 190
6aaa17c7 191 require_once($CFG->libdir .'/textlib.class.php'); // Functions to handle multibyte strings
da8759cb 192 require_once($CFG->libdir .'/weblib.php'); // Functions for producing HTML
7e13be08 193 require_once($CFG->libdir .'/dmllib.php'); // Functions to handle DB data (DML)
194 require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
c4d0753b 195 require_once($CFG->libdir .'/accesslib.php'); // Access control functions
196 require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
da8759cb 197 require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
0856223c 198 require_once($CFG->libdir .'/eventslib.php'); // Events functions
13534ef7 199 require_once($CFG->libdir .'/grouplib.php'); // Groups functions
0856223c 200
aa893d6b 201/// Disable errors for now - needed for installation when debug enabled in config.php
202 if (isset($CFG->debug)) {
203 $originalconfigdebug = $CFG->debug;
204 unset($CFG->debug);
205 } else {
206 $originalconfigdebug = -1;
207 }
208
810944af 209/// Set the client/server and connection to utf8
73bb7f8d 210/// and configure some other specific variables for each db
211 configure_dbconnection();
212
74944b73 213/// Load up any configuration from the config table
326e563a 214 unset($CFG->rcache);
a4080313 215 $CFG = get_config();
f9903ed0 216
ceff9307 217/// Turn on SQL logging if required
218 if (!empty($CFG->logsql)) {
219 $db->LogSQL();
220 }
1e3e716f 221
aa893d6b 222/// Prevent warnings from roles when upgrading with debug on
223 if (isset($CFG->debug)) {
224 $originaldatabasedebug = $CFG->debug;
225 unset($CFG->debug);
226 } else {
227 $originaldatabasedebug = -1;
6fbf8d8f 228 }
4fd7ccc0 229
230
cf8133c4 231/// For now, only needed under apache (and probably unstable in other contexts)
cf1348ca 232 if (function_exists('register_shutdown_function')) {
cf8133c4 233 register_shutdown_function('moodle_request_shutdown');
234 }
235
bac6d28a 236/// Defining the site
475e9de8 237 if ($SITE = get_site()) {
238 /**
239 * If $SITE global from {@link get_site()} is set then SITEID to $SITE->id, otherwise set to 1.
240 */
241 define('SITEID', $SITE->id);
508b76d9 242 /// And the 'default' course
243 $COURSE = clone($SITE); // For now. This will usually get reset later in require_login() etc.
475e9de8 244 } else {
245 /**
246 * @ignore
247 */
248 define('SITEID', 1);
508b76d9 249 /// And the 'default' course
250 $COURSE = new object; // no site created yet
251 $COURSE->id = 1;
475e9de8 252 }
475e9de8 253
7d0c81b3 254 // define SYSCONTEXTID in config.php if you want to save some queries (after install or upgrade!)
255 if (!defined('SYSCONTEXTID')) {
256 get_system_context();
6dd34e93 257 }
475e9de8 258
aa893d6b 259/// Set error reporting back to normal
260 if ($originaldatabasedebug == -1) {
7eb0b60a 261 $CFG->debug = DEBUG_MINIMAL;
aa893d6b 262 } else {
263 $CFG->debug = $originaldatabasedebug;
264 }
265 if ($originalconfigdebug !== -1) {
266 $CFG->debug = $originalconfigdebug;
267 }
268 unset($originalconfigdebug);
269 unset($originaldatabasedebug);
270 error_reporting($CFG->debug);
271
25338300 272
273/// If we want to display Moodle errors, then try and set PHP errors to match
6349a3ba 274 if (!isset($CFG->debugdisplay)) {
275 //keep it as is during installation
276 } else if (empty($CFG->debugdisplay)) {
25338300 277 @ini_set('display_errors', '0');
278 @ini_set('log_errors', '1');
279 } else {
280 @ini_set('display_errors', '1');
281 }
282
419e1d93 283/// Shared-Memory cache init -- will set $MCACHE
284/// $MCACHE is a global object that offers at least add(), set() and delete()
285/// with similar semantics to the memcached PHP API http://php.net/memcache
bb931a61 286 if (!empty($CFG->cachetype)) {
287 if ($CFG->cachetype === 'memcached' && !empty($CFG->memcachedhosts)) {
288 if (!init_memcached()) {
289 debugging("Error initialising memcached");
290 }
291 } elseif ($CFG->cachetype === 'eaccelerator') {
292 if (!init_eaccelerator()) {
293 debugging("Error initialising eaccelerator cache");
294 }
295 }
296 } else { // just make sure it is defined
297 $CFG->cachetype = '';
419e1d93 298 }
bb931a61 299/// Ensure we define rcache - so we can later check for it
300/// with a really fast and unambiguous $CFG->rcache === false
301 if (empty($CFG->rcache)) {
302 $CFG->rcache = false;
303 } else {
304 $CFG->rcache = true;
2142d492 305 }
aa893d6b 306
0182c65c 307/// Set a default enrolment configuration (see bug 1598)
308 if (!isset($CFG->enrol)) {
a51e2a7f 309 $CFG->enrol = 'manual';
0182c65c 310 }
311
ed8365d9 312/// Set default enabled enrolment plugins
313 if (!isset($CFG->enrol_plugins_enabled)) {
314 $CFG->enrol_plugins_enabled = 'manual';
315 }
316
2e6d4273 317/// File permissions on created directories in the $CFG->dataroot
318
319 if (empty($CFG->directorypermissions)) {
320 $CFG->directorypermissions = 0777; // Must be octal (that's why it's here)
321 }
322
820743c5 323/// Calculate and set $CFG->ostype to be used everywhere. Possible values are:
324/// - WINDOWS: for any Windows flavour.
325/// - UNIX: for the rest
326/// Also, $CFG->os can continue being used if more specialization is required
323edd4b 327 if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
328 $CFG->ostype = 'WINDOWS';
329 } else {
330 $CFG->ostype = 'UNIX';
331 }
332 $CFG->os = PHP_OS;
820743c5 333
d21a5865 334/// Set up default frame target string, based on $CFG->framename
335 $CFG->frametarget = frametarget();
336
d6ead3a2 337/// Setup cache dir for Smarty and others
338 if (!file_exists($CFG->dataroot .'/cache')) {
339 make_upload_directory('cache');
340 }
341
afb18f5a 342/// Set up smarty template system
75249234 343 //require_once($CFG->libdir .'/smarty/Smarty.class.php');
0182c65c 344 //$smarty = new Smarty;
345 //$smarty->template_dir = $CFG->dirroot .'/templates/'. $CFG->template;
d6ead3a2 346 //if (!file_exists($CFG->dataroot .'/cache/smarty')) {
347 // make_upload_directory('cache/smarty');
0182c65c 348 //}
d6ead3a2 349 //$smarty->compile_dir = $CFG->dataroot .'/cache/smarty';
2e6d4273 350
75249234 351/// Set up session handling
f93426cf 352 if(empty($CFG->respectsessionsettings)) {
353 if (empty($CFG->dbsessions)) { /// File-based sessions
75249234 354
f93426cf 355 // Some distros disable GC by setting probability to 0
75249234 356 // overriding the PHP default of 1
f93426cf 357 // (gc_probability is divided by gc_divisor, which defaults to 1000)
358 if (ini_get('session.gc_probability') == 0) {
359 ini_set('session.gc_probability', 1);
360 }
75249234 361
f93426cf 362 if (!empty($CFG->sessiontimeout)) {
363 ini_set('session.gc_maxlifetime', $CFG->sessiontimeout);
364 }
75249234 365
f93426cf 366 if (!file_exists($CFG->dataroot .'/sessions')) {
367 make_upload_directory('sessions');
368 }
369 ini_set('session.save_path', $CFG->dataroot .'/sessions');
75249234 370
f93426cf 371 } else { /// Database sessions
75249234 372 ini_set('session.save_handler', 'user');
373
374 $ADODB_SESSION_DRIVER = $CFG->dbtype;
375 $ADODB_SESSION_CONNECT = $CFG->dbhost;
376 $ADODB_SESSION_USER = $CFG->dbuser;
377 $ADODB_SESSION_PWD = $CFG->dbpass;
378 $ADODB_SESSION_DB = $CFG->dbname;
647a2566 379 $ADODB_SESSION_TBL = $CFG->prefix.'sessions2';
380 if (!empty($CFG->sessiontimeout)) {
381 $ADODB_SESS_LIFE = $CFG->sessiontimeout;
382 }
75249234 383
647a2566 384 require_once($CFG->libdir. '/adodb/session/adodb-session2.php');
42b90599 385 }
39e1c415 386 }
1504e261 387/// Set sessioncookie and sessioncookiepath variable if it isn't already
482b6e6e 388 if (!isset($CFG->sessioncookie)) {
389 $CFG->sessioncookie = '';
390 }
1504e261 391 if (!isset($CFG->sessioncookiepath)) {
392 $CFG->sessioncookiepath = '/';
393 }
eb58acca 394
de7e4ac9 395/// Configure ampersands in URLs
396
397 @ini_set('arg_separator.output', '&amp;');
398
e7aa5a88 399/// Work around for a PHP bug see MDL-11237
400
401 @ini_set('pcre.backtrack_limit', 20971520); // 20 MB
402
74944b73 403/// Location of standard files
f9903ed0 404
da8759cb 405 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
406 $CFG->javascript = $CFG->libdir .'/javascript.php';
1040ea85 407 $CFG->moddata = 'moddata';
f9903ed0 408
ae7aafeb 409
aa6af0f8 410/// A hack to get around magic_quotes_gpc being turned off
578dcc40 411/// It is strongly recommended to enable "magic_quotes_gpc"!
aa6af0f8 412
1040ea85 413 if (!ini_get_bool('magic_quotes_gpc') ) {
1d86c8ea 414 function addslashes_deep($value) {
75249234 415 $value = is_array($value) ?
1d86c8ea 416 array_map('addslashes_deep', $value) :
417 addslashes($value);
75249234 418 return $value;
24cc8ec9 419 }
1d86c8ea 420 $_POST = array_map('addslashes_deep', $_POST);
421 $_GET = array_map('addslashes_deep', $_GET);
422 $_COOKIE = array_map('addslashes_deep', $_COOKIE);
578dcc40 423 $_REQUEST = array_map('addslashes_deep', $_REQUEST);
424 if (!empty($_SERVER['REQUEST_URI'])) {
425 $_SERVER['REQUEST_URI'] = addslashes($_SERVER['REQUEST_URI']);
426 }
427 if (!empty($_SERVER['QUERY_STRING'])) {
428 $_SERVER['QUERY_STRING'] = addslashes($_SERVER['QUERY_STRING']);
429 }
430 if (!empty($_SERVER['HTTP_REFERER'])) {
431 $_SERVER['HTTP_REFERER'] = addslashes($_SERVER['HTTP_REFERER']);
432 }
433 if (!empty($_SERVER['PATH_INFO'])) {
434 $_SERVER['PATH_INFO'] = addslashes($_SERVER['PATH_INFO']);
435 }
436 if (!empty($_SERVER['PHP_SELF'])) {
437 $_SERVER['PHP_SELF'] = addslashes($_SERVER['PHP_SELF']);
438 }
439 if (!empty($_SERVER['PATH_TRANSLATED'])) {
440 $_SERVER['PATH_TRANSLATED'] = addslashes($_SERVER['PATH_TRANSLATED']);
441 }
aa6af0f8 442 }
7a302afc 443
ae7aafeb 444
cb342045 445/// The following code can emulate "register globals" if required.
446/// This hack is no longer being applied as of Moodle 1.6 unless you really
447/// really want to use it (by defining $CFG->enableglobalshack = true)
373da1d4 448
cb342045 449 if (!empty($CFG->enableglobalshack)) {
735b8567 450 if (!empty($CFG->detect_unchecked_vars)) {
451 global $UNCHECKED_VARS;
452 $UNCHECKED_VARS->url = $_SERVER['PHP_SELF'];
453 $UNCHECKED_VARS->vars = array();
454 }
455
456 if (isset($_GET)) {
457 extract($_GET, EXTR_SKIP); // Skip existing variables, ie CFG
458 if (!empty($CFG->detect_unchecked_vars)) {
459 foreach ($_GET as $key => $val) {
460 $UNCHECKED_VARS->vars[$key]=$val;
461 }
462 }
463 }
464 if (isset($_POST)) {
465 extract($_POST, EXTR_SKIP); // Skip existing variables, ie CFG
466 if (!empty($CFG->detect_unchecked_vars)) {
467 foreach ($_POST as $key => $val) {
468 $UNCHECKED_VARS->vars[$key]=$val;
469 }
470 }
471 }
472 if (isset($_SERVER)) {
473 extract($_SERVER);
474 }
b0cb5e22 475 }
ae7aafeb 476
75249234 477
74944b73 478/// Load up global environment variables
f9903ed0 479
480 class object {};
24cc8ec9 481
16303ee9 482 //discard session ID from POST, GET and globals to tighten security,
483 //this session fixation prevention can not be used in cookieless mode
484 if (empty($CFG->usesid)) {
fd78420b 485 unset(${'MoodleSession'.$CFG->sessioncookie});
486 unset($_GET['MoodleSession'.$CFG->sessioncookie]);
487 unset($_POST['MoodleSession'.$CFG->sessioncookie]);
488 }
8d2b18a8 489 //compatibility hack for Moodle Cron, cookies not deleted, but set to "deleted" - should not be needed with $nomoodlecookie in cron.php now
53a6c4cf 490 if (!empty($_COOKIE['MoodleSession'.$CFG->sessioncookie]) && $_COOKIE['MoodleSession'.$CFG->sessioncookie] == "deleted") {
491 unset($_COOKIE['MoodleSession'.$CFG->sessioncookie]);
492 }
493 if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie]) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] == "deleted") {
494 unset($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie]);
495 }
16303ee9 496 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
fd78420b 497 require_once("$CFG->dirroot/lib/cookieless.php");
498 sid_start_ob();
499 }
53a6c4cf 500
8d2b18a8 501 if (empty($nomoodlecookie)) {
482b6e6e 502 session_name('MoodleSession'.$CFG->sessioncookie);
1504e261 503 session_set_cookie_params(0, $CFG->sessioncookiepath);
16e4918d 504 @session_start();
75249234 505 if (! isset($_SESSION['SESSION'])) {
506 $_SESSION['SESSION'] = new object;
00de82df 507 $_SESSION['SESSION']->session_test = random_string(10);
4dfa0925 508 if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
1c6932d8 509 $_SESSION['SESSION']->has_timed_out = true;
00de82df 510 }
1504e261 511 setcookie('MoodleSessionTest'.$CFG->sessioncookie, $_SESSION['SESSION']->session_test, 0, $CFG->sessioncookiepath);
4dfa0925 512 $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] = $_SESSION['SESSION']->session_test;
16e4918d 513 }
75249234 514 if (! isset($_SESSION['USER'])) {
515 $_SESSION['USER'] = new object;
16e4918d 516 }
75249234 517
16e4918d 518 $SESSION = &$_SESSION['SESSION']; // Makes them easier to reference
519 $USER = &$_SESSION['USER'];
35a518c5 520 if (!isset($USER->id)) {
521 $USER->id = 0; // to enable proper function of $CFG->notloggedinroleid hack
522 }
08c17336 523 }
24cc8ec9 524 else {
8d2b18a8 525 $SESSION = NULL;
526 $USER = new object();
527 $USER->id = 0; // user not logged in when session disabled
1d19804a 528 if (isset($CFG->mnet_localhost_id)) {
529 $USER->mnethostid = $CFG->mnet_localhost_id;
530 }
24cc8ec9 531 }
08c17336 532
f9f4d999 533 if (defined('FULLME')) { // Usually in command-line scripts like admin/cron.php
534 $FULLME = FULLME;
535 $ME = FULLME;
9d378732 536 } else {
9fa49e22 537 $FULLME = qualified_me();
9d378732 538 $ME = strip_querystring($FULLME);
9fa49e22 539 }
f9903ed0 540
75249234 541/// In VERY rare cases old PHP server bugs (it has been found on PHP 4.1.2 running
1063d088 542/// as a CGI under IIS on Windows) may require that you uncomment the following:
543// session_register("USER");
544// session_register("SESSION");
545
f9903ed0 546
18b9d664 547
548/// Load up theme variables (colours etc)
86cc3e75 549
550 if (!isset($CFG->themedir)) {
a44091bf 551 $CFG->themedir = $CFG->dirroot.'/theme';
552 $CFG->themewww = $CFG->wwwroot.'/theme';
86cc3e75 553 }
a44091bf 554 $CFG->httpsthemewww = $CFG->themewww;
86cc3e75 555
18b9d664 556 if (isset($_GET['theme'])) {
32e2b302 557 if ($CFG->allowthemechangeonurl || confirm_sesskey()) {
a44091bf 558 $themename = clean_param($_GET['theme'], PARAM_SAFEDIR);
559 if (($themename != '') and file_exists($CFG->themedir.'/'.$themename)) {
560 $SESSION->theme = $themename;
18b9d664 561 }
a44091bf 562 unset($themename);
18b9d664 563 }
564 }
565
566 if (!isset($CFG->theme)) {
34137668 567 $CFG->theme = 'standardwhite';
18b9d664 568 }
569
16303ee9 570/// now do a session test to prevent random user switching - observed on some PHP/Apache combinations,
571/// disable checks when working in cookieless mode
572 if (empty($CFG->usesid) || !empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
573 if ($SESSION != NULL) {
fd78420b 574 if (empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
575 report_session_error();
576 } else if (isset($SESSION->session_test) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] != $SESSION->session_test) {
577 report_session_error();
578 }
00de82df 579 }
580 }
581
18b9d664 582
75249234 583/// Set language/locale of printed times. If user has chosen a language that
584/// that is different from the site language, then use the locale specified
339bb559 585/// in the language file. Otherwise, if the admin hasn't specified a locale
75249234 586/// then use the one from the default language. Otherwise (and this is the
339bb559 587/// majority of cases), use the stored locale specified by admin.
df206ef8 588 if ($SESSION !== NULL && isset($_GET['lang']) && ($lang = clean_param($_GET['lang'], PARAM_SAFEDIR))) {
6ec7ca0f 589 if (file_exists($CFG->dataroot .'/lang/'. $lang) or file_exists($CFG->dirroot .'/lang/'. $lang)) {
32c60ce3 590 $SESSION->lang = $lang;
748390cd 591 } else if (file_exists($CFG->dataroot.'/lang/'.$lang.'_utf8') or
592 file_exists($CFG->dirroot .'/lang/'.$lang.'_utf8')) {
593 $SESSION->lang = $lang.'_utf8';
32c60ce3 594 }
3e9b5d5a 595 }
ab036ed9 596
597 setup_lang_from_browser();
598
6ec7ca0f 599 unset($lang);
ab036ed9 600
16ba7351 601 if (empty($CFG->lang)) {
6ec7ca0f 602 if (empty($SESSION->lang)) {
810944af 603 $CFG->lang = 'en_utf8';
6ec7ca0f 604 } else {
605 $CFG->lang = $SESSION->lang;
606 }
16ba7351 607 }
aa2ed803 608
dcf6d93c 609 // set default locale and themes - might be changed again later from require_login()
610 course_setup();
1040ea85 611
18845ac3 612 if (!empty($CFG->opentogoogle)) {
34bf3d43 613 if (empty($USER->id)) { // Ignore anyone logged in
18845ac3 614 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
615 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
616 $USER = guest_user();
43ee1454 617 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
a33c4e5a 618 $USER = guest_user();
43ee1454 619 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) { // Yahoo
a33c4e5a 620 $USER = guest_user();
43ee1454 621 } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) { // Zoomspider
622 $USER = guest_user();
623 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSNBOT') !== false ) { // MSN Search
2d33fc00 624 $USER = guest_user();
625 }
18845ac3 626 }
a33c4e5a 627 if (empty($USER) && !empty($_SERVER['HTTP_REFERER'])) {
18845ac3 628 if (strpos($_SERVER['HTTP_REFERER'], 'google') !== false ) {
629 $USER = guest_user();
33674080 630 } else if (strpos($_SERVER['HTTP_REFERER'], 'altavista') !== false ) {
631 $USER = guest_user();
18845ac3 632 }
633 }
2f32eed1 634 if (!empty($USER)) {
635 load_all_capabilities();
636 }
18845ac3 637 }
638 }
639
8d62ca68 640 if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') { // Temporary measure to help with XHTML validation
9bbb40d6 641 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($_SESSION['USER']->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
75249234 642 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
98de6431 643 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
7c12949d 644 if ($USER = get_complete_user_data("username", "w3cvalidator")) {
b60f0ee5 645 $USER->ignoresesskey = true;
003c49cb 646 } else {
9610a66e 647 $USER = guest_user();
648 }
649 }
650 }
651 }
652
a559eee6 653/// Apache log intergration. In apache conf file one can use ${MOODULEUSER}n in
654/// LogFormat to get the current logged in username in moodle.
ac0b19ff 655 if ($USER && function_exists('apache_note')
656 && !empty($CFG->apacheloguser) && isset($user->username)) {
2b287cac 657 $apachelog_userid = $USER->id;
ac0b19ff 658 $apachelog_username = clean_filename($USER->username);
659 $apachelog_name = '';
660 if (isset($USER->firstname)) {
661 // We can assume both will be set
662 // - even if to empty.
663 $apachelog_name = clean_filename($USER->firstname . " " .
664 $USER->lastname);
665 }
96e19e7b 666 if (isset($USER->realuser)) {
667 if ($realuser = get_record('user', 'id', $USER->realuser)) {
2b287cac 668 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
669 $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
670 $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
96e19e7b 671 }
672 }
5c5c16bb 673 switch ($CFG->apacheloguser) {
674 case 3:
2b287cac 675 $logname = $apachelog_username;
5c5c16bb 676 break;
677 case 2:
2b287cac 678 $logname = $apachelog_name;
5c5c16bb 679 break;
680 case 1:
681 default:
2b287cac 682 $logname = $apachelog_userid;
5c5c16bb 683 break;
684 }
685 apache_note('MOODLEUSER', $logname);
a559eee6 686 }
687
5982740d 688/// Adjust ALLOWED_TAGS
689 adjust_allowed_tags();
690
18259d4f 691
692/// Use a custom script replacement if one exists
693 if (!empty($CFG->customscripts)) {
694 if (($customscript = custom_script_path()) !== false) {
2b0b32d8 695 require ($customscript);
18259d4f 696 }
697 }
698
810944af 699/// note: we can not block non utf-8 installatrions here, because empty mysql database
700/// might be converted to utf-8 in admin/index.php during installation
d3f9f1f8 701?>