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
9 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
13 ////// DOCUMENTATION IN PHPDOC FORMAT FOR MOODLE GLOBALS AND COMMON OBJECT TYPES /////////////
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
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
43 * Definition of session type
44 * @global object(session) $SESSION
48 * Definition of shared memory cache
52 * Definition of course type
53 * @global object(course) $COURSE
57 * Definition of db type
58 * @global object(db) $db
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
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.');
92 /// sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
93 @ini_set
('precision', 14); // needed for upgrades and gradebook
96 /// store settings from config.php in array in $CFG - we can use it later to detect problems and overrides
97 $CFG->config_php_settings
= (array)$CFG;
99 /// Set httpswwwroot default value (this variable will replace $CFG->wwwroot
100 /// inside some URLs used in HTTPSPAGEREQUIRED pages.
101 $CFG->httpswwwroot
= $CFG->wwwroot
;
103 $CFG->libdir
= $CFG->dirroot
.'/lib';
105 require_once($CFG->libdir
.'/setuplib.php'); // Functions that MUST be loaded first
107 /// Time to start counting
108 init_performance_info();
111 /// If there are any errors in the standard libraries we want to know!
112 error_reporting(E_ALL
);
114 /// Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
115 /// http://www.google.com/webmasters/faq.html#prefetchblock
116 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
117 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
118 trigger_error('Prefetch request forbidden.');
122 /// Connect to the database using adodb
124 /// Set $CFG->dbfamily global
125 /// and configure some other specific variables for each db BEFORE attempting the connection
126 preconfigure_dbconnection();
128 require_once($CFG->libdir
.'/adodb/adodb.inc.php'); // Database access functions
130 $db = &ADONewConnection($CFG->dbtype
);
132 // See MDL-6760 for why this is necessary. In Moodle 1.8, once we start using NULLs properly,
133 // we probably want to change this value to ''.
134 $db->null2null
= 'A long random string that will never, ever match something we want to insert into the database, I hope. \'';
136 error_reporting(0); // Hide errors
138 if (!isset($CFG->dbpersist
) or !empty($CFG->dbpersist
)) { // Use persistent connection (default)
139 $dbconnected = $db->PConnect($CFG->dbhost
,$CFG->dbuser
,$CFG->dbpass
,$CFG->dbname
);
140 } else { // Use single connection
141 $dbconnected = $db->Connect($CFG->dbhost
,$CFG->dbuser
,$CFG->dbpass
,$CFG->dbname
);
143 if (! $dbconnected) {
144 // In the name of protocol correctness, monitoring and performance
145 // profiling, set the appropriate error headers for machine comsumption
146 if (isset($_SERVER['SERVER_PROTOCOL'])) {
147 // Avoid it with cron.php. Note that we assume it's HTTP/1.x
148 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
150 // and then for human consumption...
152 echo '<table align="center"><tr>';
153 echo '<td style="color:#990000; text-align:center; font-size:large; border-width:1px; '.
154 ' border-color:#000000; border-style:solid; border-radius: 20px; border-collapse: collapse; '.
155 ' -moz-border-radius: 20px; padding: 15px">';
156 echo '<p>Error: Database connection failed.</p>';
157 echo '<p>It is possible that the database is overloaded or otherwise not running properly.</p>';
158 echo '<p>The site administrator should also check that the database details have been correctly specified in config.php</p>';
159 echo '</td></tr></table>';
160 echo '</body></html>';
162 error_log('ADODB Error: '.$db->ErrorMsg()); // see MDL-14628
164 if (empty($CFG->noemailever
) and !empty($CFG->emailconnectionerrorsto
)) {
165 if (file_exists($CFG->dataroot
.'/emailcount')){
166 $fp = fopen($CFG->dataroot
.'/emailcount', 'r');
167 $content = fread($fp, 24);
169 if((time() - (int)$content) > 600){
170 mail($CFG->emailconnectionerrorsto
,
171 'WARNING: Database connection error: '.$CFG->wwwroot
,
172 'Connection error: '.$CFG->wwwroot
);
173 $fp = fopen($CFG->dataroot
.'/emailcount', 'w');
177 mail($CFG->emailconnectionerrorsto
,
178 'WARNING: Database connection error: '.$CFG->wwwroot
,
179 'Connection error: '.$CFG->wwwroot
);
180 $fp = fopen($CFG->dataroot
.'/emailcount', 'w');
187 /// Forcing ASSOC mode for ADOdb (some DBs default to FETCH_BOTH)
188 $db->SetFetchMode(ADODB_FETCH_ASSOC
);
190 /// Starting here we have a correct DB conection but me must avoid
191 /// to execute any DB transaction until "set names" has been executed
192 /// some lines below!
194 error_reporting(E_ALL
); // Show errors from now on.
196 if (!isset($CFG->prefix
)) { // Just in case it isn't defined in config.php
201 /// Define admin directory
203 if (!isset($CFG->admin
)) { // Just in case it isn't defined in config.php
204 $CFG->admin
= 'admin'; // This is relative to the wwwroot and dirroot
207 /// Increase memory limits if possible
208 raise_memory_limit('96M'); // We should never NEED this much but just in case...
210 /// Load up standard libraries
212 require_once($CFG->libdir
.'/textlib.class.php'); // Functions to handle multibyte strings
213 require_once($CFG->libdir
.'/weblib.php'); // Functions for producing HTML
214 require_once($CFG->libdir
.'/dmllib.php'); // Functions to handle DB data (DML)
215 require_once($CFG->libdir
.'/datalib.php'); // Legacy lib with a big-mix of functions.
216 require_once($CFG->libdir
.'/accesslib.php'); // Access control functions
217 require_once($CFG->libdir
.'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
218 require_once($CFG->libdir
.'/moodlelib.php'); // Other general-purpose functions
219 require_once($CFG->libdir
.'/eventslib.php'); // Events functions
220 require_once($CFG->libdir
.'/grouplib.php'); // Groups functions
222 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
223 //the problem is that we need specific version of quickforms and hacked excel files :-(
224 ini_set('include_path', $CFG->libdir
.'/pear' . PATH_SEPARATOR
. ini_get('include_path'));
226 /// Disable errors for now - needed for installation when debug enabled in config.php
227 if (isset($CFG->debug
)) {
228 $originalconfigdebug = $CFG->debug
;
231 $originalconfigdebug = -1;
234 /// Set the client/server and connection to utf8
235 /// and configure some other specific variables for each db
236 configure_dbconnection();
238 /// Load up any configuration from the config table
241 /// Turn on SQL logging if required
242 if (!empty($CFG->logsql
)) {
244 // And override ADODB's default logging time
245 if (isset($CFG->logsqlmintime
)) {
246 global $ADODB_PERF_MIN;
247 $ADODB_PERF_MIN = $CFG->logsqlmintime
;
251 /// Prevent warnings from roles when upgrading with debug on
252 if (isset($CFG->debug
)) {
253 $originaldatabasedebug = $CFG->debug
;
256 $originaldatabasedebug = -1;
260 /// For now, only needed under apache (and probably unstable in other contexts)
261 if (function_exists('register_shutdown_function')) {
262 register_shutdown_function('moodle_request_shutdown');
265 /// Defining the site
266 if ($SITE = get_site()) {
268 * If $SITE global from {@link get_site()} is set then SITEID to $SITE->id, otherwise set to 1.
270 define('SITEID', $SITE->id
);
271 /// And the 'default' course
272 $COURSE = clone($SITE); // For now. This will usually get reset later in require_login() etc.
278 /// And the 'default' course
279 $COURSE = new object; // no site created yet
283 // define SYSCONTEXTID in config.php if you want to save some queries (after install or upgrade!)
284 if (!defined('SYSCONTEXTID')) {
285 get_system_context();
288 /// Set error reporting back to normal
289 if ($originaldatabasedebug == -1) {
290 $CFG->debug
= DEBUG_MINIMAL
;
292 $CFG->debug
= $originaldatabasedebug;
294 if ($originalconfigdebug !== -1) {
295 $CFG->debug
= $originalconfigdebug;
297 unset($originalconfigdebug);
298 unset($originaldatabasedebug);
299 error_reporting($CFG->debug
);
302 /// find out if PHP cofigured to display warnings
303 if (ini_get_bool('display_errors')) {
304 define('WARN_DISPLAY_ERRORS_ENABLED', true);
306 /// If we want to display Moodle errors, then try and set PHP errors to match
307 if (!isset($CFG->debugdisplay
)) {
308 //keep it as is during installation
309 } else if (empty($CFG->debugdisplay
)) {
310 @ini_set
('display_errors', '0');
311 @ini_set
('log_errors', '1');
313 @ini_set
('display_errors', '1');
315 // Even when users want to see errors in the output,
316 // some parts of Moodle cannot display them at all.
317 // (Once we are XHTML strict compliant, debugdisplay
319 if (defined('MOODLE_SANE_OUTPUT')) {
320 @ini_set
('display_errors', '0');
321 @ini_set
('log_errors', '1');
324 /// Shared-Memory cache init -- will set $MCACHE
325 /// $MCACHE is a global object that offers at least add(), set() and delete()
326 /// with similar semantics to the memcached PHP API http://php.net/memcache
327 /// Ensure we define rcache - so we can later check for it
328 /// with a really fast and unambiguous $CFG->rcache === false
329 if (!empty($CFG->cachetype
)) {
330 if (empty($CFG->rcache
)) {
331 $CFG->rcache
= false;
336 // do not try to initialize if cache disabled
338 $CFG->cachetype
= '';
341 if ($CFG->cachetype
=== 'memcached' && !empty($CFG->memcachedhosts
)) {
342 if (!init_memcached()) {
343 debugging("Error initialising memcached");
344 $CFG->cachetype
= '';
345 $CFG->rcache
= false;
347 } else if ($CFG->cachetype
=== 'eaccelerator') {
348 if (!init_eaccelerator()) {
349 debugging("Error initialising eaccelerator cache");
350 $CFG->cachetype
= '';
351 $CFG->rcache
= false;
355 } else { // just make sure it is defined
356 $CFG->cachetype
= '';
357 $CFG->rcache
= false;
360 /// Set a default enrolment configuration (see bug 1598)
361 if (!isset($CFG->enrol
)) {
362 $CFG->enrol
= 'manual';
365 /// Set default enabled enrolment plugins
366 if (!isset($CFG->enrol_plugins_enabled
)) {
367 $CFG->enrol_plugins_enabled
= 'manual';
370 /// File permissions on created directories in the $CFG->dataroot
372 if (empty($CFG->directorypermissions
)) {
373 $CFG->directorypermissions
= 0777; // Must be octal (that's why it's here)
376 /// Calculate and set $CFG->ostype to be used everywhere. Possible values are:
377 /// - WINDOWS: for any Windows flavour.
378 /// - UNIX: for the rest
379 /// Also, $CFG->os can continue being used if more specialization is required
380 if (stristr(PHP_OS
, 'win') && !stristr(PHP_OS
, 'darwin')) {
381 $CFG->ostype
= 'WINDOWS';
383 $CFG->ostype
= 'UNIX';
387 /// Set up default frame target string, based on $CFG->framename
388 $CFG->frametarget
= frametarget();
390 /// Setup cache dir for Smarty and others
391 if (!file_exists($CFG->dataroot
.'/cache')) {
392 make_upload_directory('cache');
395 /// Set up smarty template system
396 //require_once($CFG->libdir .'/smarty/Smarty.class.php');
397 //$smarty = new Smarty;
398 //$smarty->template_dir = $CFG->dirroot .'/templates/'. $CFG->template;
399 //if (!file_exists($CFG->dataroot .'/cache/smarty')) {
400 // make_upload_directory('cache/smarty');
402 //$smarty->compile_dir = $CFG->dataroot .'/cache/smarty';
404 /// Set up session handling
405 if(empty($CFG->respectsessionsettings
)) {
406 if (empty($CFG->dbsessions
)) { /// File-based sessions
408 // Some distros disable GC by setting probability to 0
409 // overriding the PHP default of 1
410 // (gc_probability is divided by gc_divisor, which defaults to 1000)
411 if (ini_get('session.gc_probability') == 0) {
412 ini_set('session.gc_probability', 1);
415 if (!empty($CFG->sessiontimeout
)) {
416 ini_set('session.gc_maxlifetime', $CFG->sessiontimeout
);
419 if (!file_exists($CFG->dataroot
.'/sessions')) {
420 make_upload_directory('sessions');
422 ini_set('session.save_path', $CFG->dataroot
.'/sessions');
424 } else { /// Database sessions
425 ini_set('session.save_handler', 'user');
427 $ADODB_SESSION_DRIVER = $CFG->dbtype
;
428 $ADODB_SESSION_CONNECT = $CFG->dbhost
;
429 $ADODB_SESSION_USER = $CFG->dbuser
;
430 $ADODB_SESSION_PWD = $CFG->dbpass
;
431 $ADODB_SESSION_DB = $CFG->dbname
;
432 $ADODB_SESSION_TBL = $CFG->prefix
.'sessions2';
433 if (!empty($CFG->sessiontimeout
)) {
434 $ADODB_SESS_LIFE = $CFG->sessiontimeout
;
437 require_once($CFG->libdir
. '/adodb/session/adodb-session2.php');
440 /// Set sessioncookie and sessioncookiepath variable if it isn't already
441 if (!isset($CFG->sessioncookie
)) {
442 $CFG->sessioncookie
= '';
444 if (!isset($CFG->sessioncookiedomain
)) {
445 $CFG->sessioncookiedomain
= '';
447 if (!isset($CFG->sessioncookiepath
)) {
448 $CFG->sessioncookiepath
= '/';
451 /// Configure ampersands in URLs
453 @ini_set
('arg_separator.output', '&');
455 /// Work around for a PHP bug see MDL-11237
457 @ini_set
('pcre.backtrack_limit', 20971520); // 20 MB
459 /// Location of standard files
461 $CFG->wordlist
= $CFG->libdir
.'/wordlist.txt';
462 $CFG->javascript
= $CFG->libdir
.'/javascript.php';
463 $CFG->moddata
= 'moddata';
465 // Alas, in some cases we cannot deal with magic_quotes.
466 if (defined('MOODLE_SANE_INPUT') && ini_get_bool('magic_quotes_gpc')) {
467 mdie("Facilities that require MOODLE_SANE_INPUT "
468 . "cannot work with magic_quotes_gpc. Please disable "
469 . "magic_quotes_gpc.");
471 /// A hack to get around magic_quotes_gpc being turned off
472 /// It is strongly recommended to enable "magic_quotes_gpc"!
473 if (!ini_get_bool('magic_quotes_gpc') && !defined('MOODLE_SANE_INPUT') ) {
474 function addslashes_deep($value) {
475 $value = is_array($value) ?
476 array_map('addslashes_deep', $value) :
480 $_POST = array_map('addslashes_deep', $_POST);
481 $_GET = array_map('addslashes_deep', $_GET);
482 $_COOKIE = array_map('addslashes_deep', $_COOKIE);
483 $_REQUEST = array_map('addslashes_deep', $_REQUEST);
484 if (!empty($_SERVER['REQUEST_URI'])) {
485 $_SERVER['REQUEST_URI'] = addslashes($_SERVER['REQUEST_URI']);
487 if (!empty($_SERVER['QUERY_STRING'])) {
488 $_SERVER['QUERY_STRING'] = addslashes($_SERVER['QUERY_STRING']);
490 if (!empty($_SERVER['HTTP_REFERER'])) {
491 $_SERVER['HTTP_REFERER'] = addslashes($_SERVER['HTTP_REFERER']);
493 if (!empty($_SERVER['PATH_INFO'])) {
494 $_SERVER['PATH_INFO'] = addslashes($_SERVER['PATH_INFO']);
496 if (!empty($_SERVER['PHP_SELF'])) {
497 $_SERVER['PHP_SELF'] = addslashes($_SERVER['PHP_SELF']);
499 if (!empty($_SERVER['PATH_TRANSLATED'])) {
500 $_SERVER['PATH_TRANSLATED'] = addslashes($_SERVER['PATH_TRANSLATED']);
504 /// neutralise nasty chars in PHP_SELF
505 if (isset($_SERVER['PHP_SELF'])) {
506 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
507 if ($phppos !== false) {
508 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+
4);
513 /// The following code can emulate "register globals" if required.
514 /// This hack is no longer being applied as of Moodle 1.6 unless you really
515 /// really want to use it (by defining $CFG->enableglobalshack = true)
517 if (!empty($CFG->enableglobalshack
) && !defined('MOODLE_SANE_INPUT')) {
518 if (!empty($CFG->detect_unchecked_vars
)) {
519 global $UNCHECKED_VARS;
520 $UNCHECKED_VARS->url
= $_SERVER['PHP_SELF'];
521 $UNCHECKED_VARS->vars
= array();
524 extract($_GET, EXTR_SKIP
); // Skip existing variables, ie CFG
525 if (!empty($CFG->detect_unchecked_vars
)) {
526 foreach ($_GET as $key => $val) {
527 $UNCHECKED_VARS->vars
[$key]=$val;
532 extract($_POST, EXTR_SKIP
); // Skip existing variables, ie CFG
533 if (!empty($CFG->detect_unchecked_vars
)) {
534 foreach ($_POST as $key => $val) {
535 $UNCHECKED_VARS->vars
[$key]=$val;
539 if (isset($_SERVER)) {
545 /// Load up global environment variables
547 if (!isset($CFG->cookiesecure
) or strpos($CFG->wwwroot
, 'https://') !== 0) {
548 $CFG->cookiesecure
= false;
551 if (!isset($CFG->cookiehttponly
)) {
552 $CFG->cookiehttponly
= false;
555 //discard session ID from POST, GET and globals to tighten security,
556 //this session fixation prevention can not be used in cookieless mode
557 if (empty($CFG->usesid
) && !defined('MOODLE_SANE_INPUT')) {
558 unset($
{'MoodleSession'.$CFG->sessioncookie
});
559 unset($_GET['MoodleSession'.$CFG->sessioncookie
]);
560 unset($_POST['MoodleSession'.$CFG->sessioncookie
]);
562 //compatibility hack for Moodle Cron, cookies not deleted, but set to "deleted" - should not be needed with $nomoodlecookie in cron.php now
563 if (!empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
]) && $_COOKIE['MoodleSession'.$CFG->sessioncookie
] == "deleted") {
564 unset($_COOKIE['MoodleSession'.$CFG->sessioncookie
]);
566 if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie
]) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie
] == "deleted") {
567 unset($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie
]);
569 if (!empty($CFG->usesid
) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
])) {
570 require_once("$CFG->dirroot/lib/cookieless.php");
574 if (empty($nomoodlecookie)) {
575 session_name('MoodleSession'.$CFG->sessioncookie
);
576 if (check_php_version('5.2.0')) {
577 session_set_cookie_params(0, $CFG->sessioncookiepath
, $CFG->sessioncookiedomain
, $CFG->cookiesecure
, $CFG->cookiehttponly
);
579 session_set_cookie_params(0, $CFG->sessioncookiepath
, $CFG->sessioncookiedomain
, $CFG->cookiesecure
);
582 if (! isset($_SESSION['SESSION'])) {
583 $_SESSION['SESSION'] = new object;
584 $_SESSION['SESSION']->session_test
= random_string(10);
585 if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie
])) {
586 $_SESSION['SESSION']->has_timed_out
= true;
588 if (check_php_version('5.2.0')) {
589 setcookie('MoodleSessionTest'.$CFG->sessioncookie
, $_SESSION['SESSION']->session_test
, 0, $CFG->sessioncookiepath
, $CFG->sessioncookiedomain
, $CFG->cookiesecure
, $CFG->cookiehttponly
);
591 setcookie('MoodleSessionTest'.$CFG->sessioncookie
, $_SESSION['SESSION']->session_test
, 0, $CFG->sessioncookiepath
, $CFG->sessioncookiedomain
, $CFG->cookiesecure
);
593 $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie
] = $_SESSION['SESSION']->session_test
;
595 if (! isset($_SESSION['USER'])) {
596 $_SESSION['USER'] = new object;
599 $SESSION = &$_SESSION['SESSION']; // Makes them easier to reference
600 $USER = &$_SESSION['USER'];
601 if (!isset($USER->id
)) {
602 $USER->id
= 0; // to enable proper function of $CFG->notloggedinroleid hack
607 $USER = new object();
608 $USER->id
= 0; // user not logged in when session disabled
609 if (isset($CFG->mnet_localhost_id
)) {
610 $USER->mnethostid
= $CFG->mnet_localhost_id
;
614 if (defined('FULLME')) { // Usually in command-line scripts like admin/cron.php
618 $FULLME = qualified_me();
619 $ME = strip_querystring($FULLME);
622 /// In VERY rare cases old PHP server bugs (it has been found on PHP 4.1.2 running
623 /// as a CGI under IIS on Windows) may require that you uncomment the following:
624 // session_register("USER");
625 // session_register("SESSION");
629 /// Load up theme variables (colours etc)
631 if (!isset($CFG->themedir
)) {
632 $CFG->themedir
= $CFG->dirroot
.'/theme';
633 $CFG->themewww
= $CFG->wwwroot
.'/theme';
635 $CFG->httpsthemewww
= $CFG->themewww
;
637 if (isset($_GET['theme'])) {
638 if ($CFG->allowthemechangeonurl ||
confirm_sesskey()) {
639 $themename = clean_param($_GET['theme'], PARAM_SAFEDIR
);
640 if (($themename != '') and file_exists($CFG->themedir
.'/'.$themename)) {
641 $SESSION->theme
= $themename;
647 if (!isset($CFG->theme
)) {
648 $CFG->theme
= 'standardwhite';
651 /// now do a session test to prevent random user switching - observed on some PHP/Apache combinations,
652 /// disable checks when working in cookieless mode
653 if (empty($CFG->usesid
) ||
!empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
])) {
654 if ($SESSION != NULL) {
655 if (empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie
])) {
656 report_session_error();
657 } else if (isset($SESSION->session_test
) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie
] != $SESSION->session_test
) {
658 report_session_error();
664 /// Set language/locale of printed times. If user has chosen a language that
665 /// that is different from the site language, then use the locale specified
666 /// in the language file. Otherwise, if the admin hasn't specified a locale
667 /// then use the one from the default language. Otherwise (and this is the
668 /// majority of cases), use the stored locale specified by admin.
669 if ($SESSION !== NULL && isset($_GET['lang']) && ($lang = clean_param($_GET['lang'], PARAM_SAFEDIR
))) {
670 if (file_exists($CFG->dataroot
.'/lang/'. $lang) or file_exists($CFG->dirroot
.'/lang/'. $lang)) {
671 $SESSION->lang
= $lang;
672 } else if (file_exists($CFG->dataroot
.'/lang/'.$lang.'_utf8') or
673 file_exists($CFG->dirroot
.'/lang/'.$lang.'_utf8')) {
674 $SESSION->lang
= $lang.'_utf8';
678 setup_lang_from_browser();
682 if (empty($CFG->lang
)) {
683 if (empty($SESSION->lang
)) {
684 $CFG->lang
= 'en_utf8';
686 $CFG->lang
= $SESSION->lang
;
690 // set default locale and themes - might be changed again later from require_login()
693 if (!empty($CFG->opentogoogle
)) {
694 if (empty($USER->id
)) { // Ignore anyone logged in
695 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
696 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
697 $USER = guest_user();
698 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
699 $USER = guest_user();
700 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) { // Yahoo
701 $USER = guest_user();
702 } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) { // Zoomspider
703 $USER = guest_user();
704 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSNBOT') !== false ) { // MSN Search
705 $USER = guest_user();
708 if (!empty($CFG->guestloginbutton
) && empty($USER) && !empty($_SERVER['HTTP_REFERER'])) {
709 if (strpos($_SERVER['HTTP_REFERER'], 'google') !== false ) {
710 $USER = guest_user();
711 } else if (strpos($_SERVER['HTTP_REFERER'], 'altavista') !== false ) {
712 $USER = guest_user();
716 load_all_capabilities();
721 if (!empty($CFG->guestloginbutton
)) {
722 if ($CFG->theme
== 'standard' or $CFG->theme
== 'standardwhite') { // Temporary measure to help with XHTML validation
723 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($_SESSION['USER']->id
)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
724 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
725 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
726 if ($USER = get_complete_user_data("username", "w3cvalidator")) {
727 $USER->ignoresesskey
= true;
729 $USER = guest_user();
736 /// Apache log intergration. In apache conf file one can use ${MOODULEUSER}n in
737 /// LogFormat to get the current logged in username in moodle.
738 if ($USER && function_exists('apache_note')
739 && !empty($CFG->apacheloguser
) && isset($USER->username
)) {
740 $apachelog_userid = $USER->id
;
741 $apachelog_username = clean_filename($USER->username
);
742 $apachelog_name = '';
743 if (isset($USER->firstname
)) {
744 // We can assume both will be set
745 // - even if to empty.
746 $apachelog_name = clean_filename($USER->firstname
. " " .
749 if (isset($USER->realuser
)) {
750 if ($realuser = get_record('user', 'id', $USER->realuser
)) {
751 $apachelog_username = clean_filename($realuser->username
." as ".$apachelog_username);
752 $apachelog_name = clean_filename($realuser->firstname
." ".$realuser->lastname
." as ".$apachelog_name);
753 $apachelog_userid = clean_filename($realuser->id
." as ".$apachelog_userid);
756 switch ($CFG->apacheloguser
) {
758 $logname = $apachelog_username;
761 $logname = $apachelog_name;
765 $logname = $apachelog_userid;
768 apache_note('MOODLEUSER', $logname);
771 /// Adjust ALLOWED_TAGS
772 adjust_allowed_tags();
775 /// Use a custom script replacement if one exists
776 if (!empty($CFG->customscripts
)) {
777 if (($customscript = custom_script_path()) !== false) {
778 require ($customscript);
782 /// note: we can not block non utf-8 installatrions here, because empty mysql database
783 /// might be converted to utf-8 in admin/index.php during installation