MDL-14854
[moodle-linuxchix.git] / lib / setup.php
blob598ad10c51441853b17182b07cf2329921e96376
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 mail($CFG->emailconnectionerrorsto,
162 'WARNING: Database connection error: '.$CFG->wwwroot,
163 'Connection error: '.$CFG->wwwroot);
165 die;
168 /// Forcing ASSOC mode for ADOdb (some DBs default to FETCH_BOTH)
169 $db->SetFetchMode(ADODB_FETCH_ASSOC);
171 /// Starting here we have a correct DB conection but me must avoid
172 /// to execute any DB transaction until "set names" has been executed
173 /// some lines below!
175 error_reporting(E_ALL); // Show errors from now on.
177 if (!isset($CFG->prefix)) { // Just in case it isn't defined in config.php
178 $CFG->prefix = '';
182 /// Define admin directory
184 if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
185 $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
188 /// Increase memory limits if possible
189 raise_memory_limit('96M'); // We should never NEED this much but just in case...
191 /// Load up standard libraries
193 require_once($CFG->libdir .'/textlib.class.php'); // Functions to handle multibyte strings
194 require_once($CFG->libdir .'/weblib.php'); // Functions for producing HTML
195 require_once($CFG->libdir .'/dmllib.php'); // Functions to handle DB data (DML)
196 require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
197 require_once($CFG->libdir .'/accesslib.php'); // Access control functions
198 require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
199 require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
200 require_once($CFG->libdir .'/eventslib.php'); // Events functions
201 require_once($CFG->libdir .'/grouplib.php'); // Groups functions
203 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
204 //the problem is that we need specific version of quickforms and hacked excel files :-(
205 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
207 /// Disable errors for now - needed for installation when debug enabled in config.php
208 if (isset($CFG->debug)) {
209 $originalconfigdebug = $CFG->debug;
210 unset($CFG->debug);
211 } else {
212 $originalconfigdebug = -1;
215 /// Set the client/server and connection to utf8
216 /// and configure some other specific variables for each db
217 configure_dbconnection();
219 /// Load up any configuration from the config table
220 $CFG = get_config();
222 /// Turn on SQL logging if required
223 if (!empty($CFG->logsql)) {
224 $db->LogSQL();
227 /// Prevent warnings from roles when upgrading with debug on
228 if (isset($CFG->debug)) {
229 $originaldatabasedebug = $CFG->debug;
230 unset($CFG->debug);
231 } else {
232 $originaldatabasedebug = -1;
236 /// For now, only needed under apache (and probably unstable in other contexts)
237 if (function_exists('register_shutdown_function')) {
238 register_shutdown_function('moodle_request_shutdown');
241 /// Defining the site
242 if ($SITE = get_site()) {
244 * If $SITE global from {@link get_site()} is set then SITEID to $SITE->id, otherwise set to 1.
246 define('SITEID', $SITE->id);
247 /// And the 'default' course
248 $COURSE = clone($SITE); // For now. This will usually get reset later in require_login() etc.
249 } else {
251 * @ignore
253 define('SITEID', 1);
254 /// And the 'default' course
255 $COURSE = new object; // no site created yet
256 $COURSE->id = 1;
259 // define SYSCONTEXTID in config.php if you want to save some queries (after install or upgrade!)
260 if (!defined('SYSCONTEXTID')) {
261 get_system_context();
264 /// Set error reporting back to normal
265 if ($originaldatabasedebug == -1) {
266 $CFG->debug = DEBUG_MINIMAL;
267 } else {
268 $CFG->debug = $originaldatabasedebug;
270 if ($originalconfigdebug !== -1) {
271 $CFG->debug = $originalconfigdebug;
273 unset($originalconfigdebug);
274 unset($originaldatabasedebug);
275 error_reporting($CFG->debug);
278 /// If we want to display Moodle errors, then try and set PHP errors to match
279 if (!isset($CFG->debugdisplay)) {
280 //keep it as is during installation
281 } else if (empty($CFG->debugdisplay)) {
282 @ini_set('display_errors', '0');
283 @ini_set('log_errors', '1');
284 } else {
285 @ini_set('display_errors', '1');
287 // Even when users want to see errors in the output,
288 // some parts of Moodle cannot display them at all.
289 // (Once we are XHTML strict compliant, debugdisplay
290 // _must_ go away).
291 if (defined('MOODLE_SANE_OUTPUT')) {
292 @ini_set('display_errors', '0');
293 @ini_set('log_errors', '1');
296 /// Shared-Memory cache init -- will set $MCACHE
297 /// $MCACHE is a global object that offers at least add(), set() and delete()
298 /// with similar semantics to the memcached PHP API http://php.net/memcache
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->cachetype)) {
302 if (empty($CFG->rcache)) {
303 $CFG->rcache = false;
304 } else {
305 $CFG->rcache = true;
308 // do not try to initialize if cache disabled
309 if (!$CFG->rcache) {
310 $CFG->cachetype = '';
313 if ($CFG->cachetype === 'memcached' && !empty($CFG->memcachedhosts)) {
314 if (!init_memcached()) {
315 debugging("Error initialising memcached");
316 $CFG->cachetype = '';
317 $CFG->rcache = false;
319 } else if ($CFG->cachetype === 'eaccelerator') {
320 if (!init_eaccelerator()) {
321 debugging("Error initialising eaccelerator cache");
322 $CFG->cachetype = '';
323 $CFG->rcache = false;
327 } else { // just make sure it is defined
328 $CFG->cachetype = '';
329 $CFG->rcache = false;
332 /// Set a default enrolment configuration (see bug 1598)
333 if (!isset($CFG->enrol)) {
334 $CFG->enrol = 'manual';
337 /// Set default enabled enrolment plugins
338 if (!isset($CFG->enrol_plugins_enabled)) {
339 $CFG->enrol_plugins_enabled = 'manual';
342 /// File permissions on created directories in the $CFG->dataroot
344 if (empty($CFG->directorypermissions)) {
345 $CFG->directorypermissions = 0777; // Must be octal (that's why it's here)
348 /// Calculate and set $CFG->ostype to be used everywhere. Possible values are:
349 /// - WINDOWS: for any Windows flavour.
350 /// - UNIX: for the rest
351 /// Also, $CFG->os can continue being used if more specialization is required
352 if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
353 $CFG->ostype = 'WINDOWS';
354 } else {
355 $CFG->ostype = 'UNIX';
357 $CFG->os = PHP_OS;
359 /// Set up default frame target string, based on $CFG->framename
360 $CFG->frametarget = frametarget();
362 /// Setup cache dir for Smarty and others
363 if (!file_exists($CFG->dataroot .'/cache')) {
364 make_upload_directory('cache');
367 /// Set up smarty template system
368 //require_once($CFG->libdir .'/smarty/Smarty.class.php');
369 //$smarty = new Smarty;
370 //$smarty->template_dir = $CFG->dirroot .'/templates/'. $CFG->template;
371 //if (!file_exists($CFG->dataroot .'/cache/smarty')) {
372 // make_upload_directory('cache/smarty');
374 //$smarty->compile_dir = $CFG->dataroot .'/cache/smarty';
376 /// Set up session handling
377 if(empty($CFG->respectsessionsettings)) {
378 if (empty($CFG->dbsessions)) { /// File-based sessions
380 // Some distros disable GC by setting probability to 0
381 // overriding the PHP default of 1
382 // (gc_probability is divided by gc_divisor, which defaults to 1000)
383 if (ini_get('session.gc_probability') == 0) {
384 ini_set('session.gc_probability', 1);
387 if (!empty($CFG->sessiontimeout)) {
388 ini_set('session.gc_maxlifetime', $CFG->sessiontimeout);
391 if (!file_exists($CFG->dataroot .'/sessions')) {
392 make_upload_directory('sessions');
394 ini_set('session.save_path', $CFG->dataroot .'/sessions');
396 } else { /// Database sessions
397 ini_set('session.save_handler', 'user');
399 $ADODB_SESSION_DRIVER = $CFG->dbtype;
400 $ADODB_SESSION_CONNECT = $CFG->dbhost;
401 $ADODB_SESSION_USER = $CFG->dbuser;
402 $ADODB_SESSION_PWD = $CFG->dbpass;
403 $ADODB_SESSION_DB = $CFG->dbname;
404 $ADODB_SESSION_TBL = $CFG->prefix.'sessions2';
405 if (!empty($CFG->sessiontimeout)) {
406 $ADODB_SESS_LIFE = $CFG->sessiontimeout;
409 require_once($CFG->libdir. '/adodb/session/adodb-session2.php');
412 /// Set sessioncookie and sessioncookiepath variable if it isn't already
413 if (!isset($CFG->sessioncookie)) {
414 $CFG->sessioncookie = '';
416 if (!isset($CFG->sessioncookiepath)) {
417 $CFG->sessioncookiepath = '/';
420 /// Configure ampersands in URLs
422 @ini_set('arg_separator.output', '&amp;');
424 /// Work around for a PHP bug see MDL-11237
426 @ini_set('pcre.backtrack_limit', 20971520); // 20 MB
428 /// Location of standard files
430 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
431 $CFG->javascript = $CFG->libdir .'/javascript.php';
432 $CFG->moddata = 'moddata';
434 // Alas, in some cases we cannot deal with magic_quotes.
435 if (defined('MOODLE_SANE_INPUT') && ini_get_bool('magic_quotes_gpc')) {
436 mdie("Facilities that require MOODLE_SANE_INPUT "
437 . "cannot work with magic_quotes_gpc. Please disable "
438 . "magic_quotes_gpc.");
440 /// A hack to get around magic_quotes_gpc being turned off
441 /// It is strongly recommended to enable "magic_quotes_gpc"!
442 if (!ini_get_bool('magic_quotes_gpc') && !defined('MOODLE_SANE_INPUT') ) {
443 function addslashes_deep($value) {
444 $value = is_array($value) ?
445 array_map('addslashes_deep', $value) :
446 addslashes($value);
447 return $value;
449 $_POST = array_map('addslashes_deep', $_POST);
450 $_GET = array_map('addslashes_deep', $_GET);
451 $_COOKIE = array_map('addslashes_deep', $_COOKIE);
452 $_REQUEST = array_map('addslashes_deep', $_REQUEST);
453 if (!empty($_SERVER['REQUEST_URI'])) {
454 $_SERVER['REQUEST_URI'] = addslashes($_SERVER['REQUEST_URI']);
456 if (!empty($_SERVER['QUERY_STRING'])) {
457 $_SERVER['QUERY_STRING'] = addslashes($_SERVER['QUERY_STRING']);
459 if (!empty($_SERVER['HTTP_REFERER'])) {
460 $_SERVER['HTTP_REFERER'] = addslashes($_SERVER['HTTP_REFERER']);
462 if (!empty($_SERVER['PATH_INFO'])) {
463 $_SERVER['PATH_INFO'] = addslashes($_SERVER['PATH_INFO']);
465 if (!empty($_SERVER['PHP_SELF'])) {
466 $_SERVER['PHP_SELF'] = addslashes($_SERVER['PHP_SELF']);
468 if (!empty($_SERVER['PATH_TRANSLATED'])) {
469 $_SERVER['PATH_TRANSLATED'] = addslashes($_SERVER['PATH_TRANSLATED']);
474 /// The following code can emulate "register globals" if required.
475 /// This hack is no longer being applied as of Moodle 1.6 unless you really
476 /// really want to use it (by defining $CFG->enableglobalshack = true)
478 if (!empty($CFG->enableglobalshack) && !defined('MOODLE_SANE_INPUT')) {
479 if (!empty($CFG->detect_unchecked_vars)) {
480 global $UNCHECKED_VARS;
481 $UNCHECKED_VARS->url = $_SERVER['PHP_SELF'];
482 $UNCHECKED_VARS->vars = array();
484 if (isset($_GET)) {
485 extract($_GET, EXTR_SKIP); // Skip existing variables, ie CFG
486 if (!empty($CFG->detect_unchecked_vars)) {
487 foreach ($_GET as $key => $val) {
488 $UNCHECKED_VARS->vars[$key]=$val;
492 if (isset($_POST)) {
493 extract($_POST, EXTR_SKIP); // Skip existing variables, ie CFG
494 if (!empty($CFG->detect_unchecked_vars)) {
495 foreach ($_POST as $key => $val) {
496 $UNCHECKED_VARS->vars[$key]=$val;
500 if (isset($_SERVER)) {
501 extract($_SERVER);
506 /// Load up global environment variables
508 if (!isset($CFG->cookiesecure) or strpos($CFG->wwwroot, 'https://') !== 0) {
509 $CFG->cookiesecure = false;
512 if (!isset($CFG->cookiehttponly)) {
513 $CFG->cookiehttponly = false;
516 //discard session ID from POST, GET and globals to tighten security,
517 //this session fixation prevention can not be used in cookieless mode
518 if (empty($CFG->usesid) && !defined('MOODLE_SANE_INPUT')) {
519 unset(${'MoodleSession'.$CFG->sessioncookie});
520 unset($_GET['MoodleSession'.$CFG->sessioncookie]);
521 unset($_POST['MoodleSession'.$CFG->sessioncookie]);
523 //compatibility hack for Moodle Cron, cookies not deleted, but set to "deleted" - should not be needed with $nomoodlecookie in cron.php now
524 if (!empty($_COOKIE['MoodleSession'.$CFG->sessioncookie]) && $_COOKIE['MoodleSession'.$CFG->sessioncookie] == "deleted") {
525 unset($_COOKIE['MoodleSession'.$CFG->sessioncookie]);
527 if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie]) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] == "deleted") {
528 unset($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie]);
530 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
531 require_once("$CFG->dirroot/lib/cookieless.php");
532 sid_start_ob();
535 if (empty($nomoodlecookie)) {
536 session_name('MoodleSession'.$CFG->sessioncookie);
537 if (check_php_version('5.2.0')) {
538 session_set_cookie_params(0, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
539 } else {
540 session_set_cookie_params(0, $CFG->sessioncookiepath, '', $CFG->cookiesecure);
542 @session_start();
543 if (! isset($_SESSION['SESSION'])) {
544 $_SESSION['SESSION'] = new object;
545 $_SESSION['SESSION']->session_test = random_string(10);
546 if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
547 $_SESSION['SESSION']->has_timed_out = true;
549 if (check_php_version('5.2.0')) {
550 setcookie('MoodleSessionTest'.$CFG->sessioncookie, $_SESSION['SESSION']->session_test, 0, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
551 } else {
552 setcookie('MoodleSessionTest'.$CFG->sessioncookie, $_SESSION['SESSION']->session_test, 0, $CFG->sessioncookiepath, '', $CFG->cookiesecure);
554 $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] = $_SESSION['SESSION']->session_test;
556 if (! isset($_SESSION['USER'])) {
557 $_SESSION['USER'] = new object;
560 $SESSION = &$_SESSION['SESSION']; // Makes them easier to reference
561 $USER = &$_SESSION['USER'];
562 if (!isset($USER->id)) {
563 $USER->id = 0; // to enable proper function of $CFG->notloggedinroleid hack
566 else {
567 $SESSION = NULL;
568 $USER = new object();
569 $USER->id = 0; // user not logged in when session disabled
570 if (isset($CFG->mnet_localhost_id)) {
571 $USER->mnethostid = $CFG->mnet_localhost_id;
575 if (defined('FULLME')) { // Usually in command-line scripts like admin/cron.php
576 $FULLME = FULLME;
577 $ME = FULLME;
578 } else {
579 $FULLME = qualified_me();
580 $ME = strip_querystring($FULLME);
583 /// In VERY rare cases old PHP server bugs (it has been found on PHP 4.1.2 running
584 /// as a CGI under IIS on Windows) may require that you uncomment the following:
585 // session_register("USER");
586 // session_register("SESSION");
590 /// Load up theme variables (colours etc)
592 if (!isset($CFG->themedir)) {
593 $CFG->themedir = $CFG->dirroot.'/theme';
594 $CFG->themewww = $CFG->wwwroot.'/theme';
596 $CFG->httpsthemewww = $CFG->themewww;
598 if (isset($_GET['theme'])) {
599 if ($CFG->allowthemechangeonurl || confirm_sesskey()) {
600 $themename = clean_param($_GET['theme'], PARAM_SAFEDIR);
601 if (($themename != '') and file_exists($CFG->themedir.'/'.$themename)) {
602 $SESSION->theme = $themename;
604 unset($themename);
608 if (!isset($CFG->theme)) {
609 $CFG->theme = 'standardwhite';
612 /// now do a session test to prevent random user switching - observed on some PHP/Apache combinations,
613 /// disable checks when working in cookieless mode
614 if (empty($CFG->usesid) || !empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
615 if ($SESSION != NULL) {
616 if (empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
617 report_session_error();
618 } else if (isset($SESSION->session_test) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] != $SESSION->session_test) {
619 report_session_error();
625 /// Set language/locale of printed times. If user has chosen a language that
626 /// that is different from the site language, then use the locale specified
627 /// in the language file. Otherwise, if the admin hasn't specified a locale
628 /// then use the one from the default language. Otherwise (and this is the
629 /// majority of cases), use the stored locale specified by admin.
630 if ($SESSION !== NULL && isset($_GET['lang']) && ($lang = clean_param($_GET['lang'], PARAM_SAFEDIR))) {
631 if (file_exists($CFG->dataroot .'/lang/'. $lang) or file_exists($CFG->dirroot .'/lang/'. $lang)) {
632 $SESSION->lang = $lang;
633 } else if (file_exists($CFG->dataroot.'/lang/'.$lang.'_utf8') or
634 file_exists($CFG->dirroot .'/lang/'.$lang.'_utf8')) {
635 $SESSION->lang = $lang.'_utf8';
639 setup_lang_from_browser();
641 unset($lang);
643 if (empty($CFG->lang)) {
644 if (empty($SESSION->lang)) {
645 $CFG->lang = 'en_utf8';
646 } else {
647 $CFG->lang = $SESSION->lang;
651 // set default locale and themes - might be changed again later from require_login()
652 course_setup();
654 if (!empty($CFG->opentogoogle)) {
655 if (empty($USER->id)) { // Ignore anyone logged in
656 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
657 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
658 $USER = guest_user();
659 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
660 $USER = guest_user();
661 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) { // Yahoo
662 $USER = guest_user();
663 } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) { // Zoomspider
664 $USER = guest_user();
665 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSNBOT') !== false ) { // MSN Search
666 $USER = guest_user();
669 if (empty($USER) && !empty($_SERVER['HTTP_REFERER'])) {
670 if (strpos($_SERVER['HTTP_REFERER'], 'google') !== false ) {
671 $USER = guest_user();
672 } else if (strpos($_SERVER['HTTP_REFERER'], 'altavista') !== false ) {
673 $USER = guest_user();
676 if (!empty($USER)) {
677 load_all_capabilities();
682 if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') { // Temporary measure to help with XHTML validation
683 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($_SESSION['USER']->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
684 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
685 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
686 if ($USER = get_complete_user_data("username", "w3cvalidator")) {
687 $USER->ignoresesskey = true;
688 } else {
689 $USER = guest_user();
695 /// Apache log intergration. In apache conf file one can use ${MOODULEUSER}n in
696 /// LogFormat to get the current logged in username in moodle.
697 if ($USER && function_exists('apache_note')
698 && !empty($CFG->apacheloguser) && isset($user->username)) {
699 $apachelog_userid = $USER->id;
700 $apachelog_username = clean_filename($USER->username);
701 $apachelog_name = '';
702 if (isset($USER->firstname)) {
703 // We can assume both will be set
704 // - even if to empty.
705 $apachelog_name = clean_filename($USER->firstname . " " .
706 $USER->lastname);
708 if (isset($USER->realuser)) {
709 if ($realuser = get_record('user', 'id', $USER->realuser)) {
710 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
711 $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
712 $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
715 switch ($CFG->apacheloguser) {
716 case 3:
717 $logname = $apachelog_username;
718 break;
719 case 2:
720 $logname = $apachelog_name;
721 break;
722 case 1:
723 default:
724 $logname = $apachelog_userid;
725 break;
727 apache_note('MOODLEUSER', $logname);
730 /// Adjust ALLOWED_TAGS
731 adjust_allowed_tags();
734 /// Use a custom script replacement if one exists
735 if (!empty($CFG->customscripts)) {
736 if (($customscript = custom_script_path()) !== false) {
737 require ($customscript);
741 /// note: we can not block non utf-8 installatrions here, because empty mysql database
742 /// might be converted to utf-8 in admin/index.php during installation