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
95 /// New versions of HTML Purifier are not compatible with PHP 4
96 if (version_compare(phpversion(), "5.0.5") < 0) {
97 $CFG->enablehtmlpurifier
= 0;
100 /// store settings from config.php in array in $CFG - we can use it later to detect problems and overrides
101 $CFG->config_php_settings
= (array)$CFG;
103 /// Set httpswwwroot default value (this variable will replace $CFG->wwwroot
104 /// inside some URLs used in HTTPSPAGEREQUIRED pages.
105 $CFG->httpswwwroot
= $CFG->wwwroot
;
107 $CFG->libdir
= $CFG->dirroot
.'/lib';
109 require_once($CFG->libdir
.'/setuplib.php'); // Functions that MUST be loaded first
111 /// Time to start counting
112 init_performance_info();
115 /// If there are any errors in the standard libraries we want to know!
116 error_reporting(E_ALL
);
118 /// Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
119 /// http://www.google.com/webmasters/faq.html#prefetchblock
120 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
121 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
122 trigger_error('Prefetch request forbidden.');
126 /// Connect to the database using adodb
128 /// Set $CFG->dbfamily global
129 /// and configure some other specific variables for each db BEFORE attempting the connection
130 preconfigure_dbconnection();
132 require_once($CFG->libdir
.'/adodb/adodb.inc.php'); // Database access functions
134 $db = &ADONewConnection($CFG->dbtype
);
136 // See MDL-6760 for why this is necessary. In Moodle 1.8, once we start using NULLs properly,
137 // we probably want to change this value to ''.
138 $db->null2null
= 'A long random string that will never, ever match something we want to insert into the database, I hope. \'';
140 error_reporting(0); // Hide errors
142 if (!isset($CFG->dbpersist
) or !empty($CFG->dbpersist
)) { // Use persistent connection (default)
143 $dbconnected = $db->PConnect($CFG->dbhost
,$CFG->dbuser
,$CFG->dbpass
,$CFG->dbname
);
144 } else { // Use single connection
145 $dbconnected = $db->Connect($CFG->dbhost
,$CFG->dbuser
,$CFG->dbpass
,$CFG->dbname
);
147 if (! $dbconnected) {
148 // In the name of protocol correctness, monitoring and performance
149 // profiling, set the appropriate error headers for machine comsumption
150 if (isset($_SERVER['SERVER_PROTOCOL'])) {
151 // Avoid it with cron.php. Note that we assume it's HTTP/1.x
152 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
154 // and then for human consumption...
156 echo '<table align="center"><tr>';
157 echo '<td style="color:#990000; text-align:center; font-size:large; border-width:1px; '.
158 ' border-color:#000000; border-style:solid; border-radius: 20px; border-collapse: collapse; '.
159 ' -moz-border-radius: 20px; padding: 15px">';
160 echo '<p>Error: Database connection failed.</p>';
161 echo '<p>It is possible that the database is overloaded or otherwise not running properly.</p>';
162 echo '<p>The site administrator should also check that the database details have been correctly specified in config.php</p>';
163 echo '</td></tr></table>';
164 echo '</body></html>';
166 error_log('ADODB Error: '.$db->ErrorMsg()); // see MDL-14628
168 if (empty($CFG->noemailever
) and !empty($CFG->emailconnectionerrorsto
)) {
169 if (file_exists($CFG->dataroot
.'/emailcount')){
170 $fp = fopen($CFG->dataroot
.'/emailcount', 'r');
171 $content = fread($fp, 24);
173 if((time() - (int)$content) > 600){
174 mail($CFG->emailconnectionerrorsto
,
175 'WARNING: Database connection error: '.$CFG->wwwroot
,
176 'Connection error: '.$CFG->wwwroot
);
177 $fp = fopen($CFG->dataroot
.'/emailcount', 'w');
181 mail($CFG->emailconnectionerrorsto
,
182 'WARNING: Database connection error: '.$CFG->wwwroot
,
183 'Connection error: '.$CFG->wwwroot
);
184 $fp = fopen($CFG->dataroot
.'/emailcount', 'w');
191 /// Forcing ASSOC mode for ADOdb (some DBs default to FETCH_BOTH)
192 $db->SetFetchMode(ADODB_FETCH_ASSOC
);
194 /// Starting here we have a correct DB conection but me must avoid
195 /// to execute any DB transaction until "set names" has been executed
196 /// some lines below!
198 error_reporting(E_ALL
); // Show errors from now on.
200 if (!isset($CFG->prefix
)) { // Just in case it isn't defined in config.php
205 /// Define admin directory
207 if (!isset($CFG->admin
)) { // Just in case it isn't defined in config.php
208 $CFG->admin
= 'admin'; // This is relative to the wwwroot and dirroot
211 /// Increase memory limits if possible
212 raise_memory_limit('96M'); // We should never NEED this much but just in case...
214 /// Load up standard libraries
216 require_once($CFG->libdir
.'/textlib.class.php'); // Functions to handle multibyte strings
217 require_once($CFG->libdir
.'/weblib.php'); // Functions for producing HTML
218 require_once($CFG->libdir
.'/dmllib.php'); // Functions to handle DB data (DML)
219 require_once($CFG->libdir
.'/datalib.php'); // Legacy lib with a big-mix of functions.
220 require_once($CFG->libdir
.'/accesslib.php'); // Access control functions
221 require_once($CFG->libdir
.'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
222 require_once($CFG->libdir
.'/moodlelib.php'); // Other general-purpose functions
223 require_once($CFG->libdir
.'/eventslib.php'); // Events functions
224 require_once($CFG->libdir
.'/grouplib.php'); // Groups functions
226 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
227 //the problem is that we need specific version of quickforms and hacked excel files :-(
228 ini_set('include_path', $CFG->libdir
.'/pear' . PATH_SEPARATOR
. ini_get('include_path'));
230 /// Disable errors for now - needed for installation when debug enabled in config.php
231 if (isset($CFG->debug
)) {
232 $originalconfigdebug = $CFG->debug
;
235 $originalconfigdebug = -1;
238 /// Set the client/server and connection to utf8
239 /// and configure some other specific variables for each db
240 configure_dbconnection();
242 /// Load up any configuration from the config table
245 /// Turn on SQL logging if required
246 if (!empty($CFG->logsql
)) {
248 // And override ADODB's default logging time
249 if (isset($CFG->logsqlmintime
)) {
250 global $ADODB_PERF_MIN;
251 $ADODB_PERF_MIN = $CFG->logsqlmintime
;
255 /// Prevent warnings from roles when upgrading with debug on
256 if (isset($CFG->debug
)) {
257 $originaldatabasedebug = $CFG->debug
;
260 $originaldatabasedebug = -1;
263 /// For now, only needed under apache (and probably unstable in other contexts)
264 if (function_exists('register_shutdown_function')) {
265 register_shutdown_function('moodle_request_shutdown');
268 /// Defining the site
269 if ($SITE = get_site()) {
271 * If $SITE global from {@link get_site()} is set then SITEID to $SITE->id, otherwise set to 1.
273 define('SITEID', $SITE->id
);
274 /// And the 'default' course
275 $COURSE = clone($SITE); // For now. This will usually get reset later in require_login() etc.
281 /// And the 'default' course
282 $COURSE = new object; // no site created yet
286 // define SYSCONTEXTID in config.php if you want to save some queries (after install or upgrade!)
287 if (!defined('SYSCONTEXTID')) {
288 get_system_context();
291 /// Set error reporting back to normal
292 if ($originaldatabasedebug == -1) {
293 $CFG->debug
= DEBUG_MINIMAL
;
295 $CFG->debug
= $originaldatabasedebug;
297 if ($originalconfigdebug !== -1) {
298 $CFG->debug
= $originalconfigdebug;
300 unset($originalconfigdebug);
301 unset($originaldatabasedebug);
302 error_reporting($CFG->debug
);
305 /// find out if PHP cofigured to display warnings
306 if (ini_get_bool('display_errors')) {
307 define('WARN_DISPLAY_ERRORS_ENABLED', true);
309 /// If we want to display Moodle errors, then try and set PHP errors to match
310 if (!isset($CFG->debugdisplay
)) {
311 //keep it as is during installation
312 } else if (empty($CFG->debugdisplay
)) {
313 @ini_set
('display_errors', '0');
314 @ini_set
('log_errors', '1');
316 @ini_set
('display_errors', '1');
318 // Even when users want to see errors in the output,
319 // some parts of Moodle cannot display them at all.
320 // (Once we are XHTML strict compliant, debugdisplay
322 if (defined('MOODLE_SANE_OUTPUT')) {
323 @ini_set
('display_errors', '0');
324 @ini_set
('log_errors', '1');
327 /// Shared-Memory cache init -- will set $MCACHE
328 /// $MCACHE is a global object that offers at least add(), set() and delete()
329 /// with similar semantics to the memcached PHP API http://php.net/memcache
330 /// Ensure we define rcache - so we can later check for it
331 /// with a really fast and unambiguous $CFG->rcache === false
332 if (!empty($CFG->cachetype
)) {
333 if (empty($CFG->rcache
)) {
334 $CFG->rcache
= false;
339 // do not try to initialize if cache disabled
341 $CFG->cachetype
= '';
344 if ($CFG->cachetype
=== 'memcached' && !empty($CFG->memcachedhosts
)) {
345 if (!init_memcached()) {
346 debugging("Error initialising memcached");
347 $CFG->cachetype
= '';
348 $CFG->rcache
= false;
350 } else if ($CFG->cachetype
=== 'eaccelerator') {
351 if (!init_eaccelerator()) {
352 debugging("Error initialising eaccelerator cache");
353 $CFG->cachetype
= '';
354 $CFG->rcache
= false;
358 } else { // just make sure it is defined
359 $CFG->cachetype
= '';
360 $CFG->rcache
= false;
363 /// Set a default enrolment configuration (see bug 1598)
364 if (!isset($CFG->enrol
)) {
365 $CFG->enrol
= 'manual';
368 /// Set default enabled enrolment plugins
369 if (!isset($CFG->enrol_plugins_enabled
)) {
370 $CFG->enrol_plugins_enabled
= 'manual';
373 /// File permissions on created directories in the $CFG->dataroot
375 if (empty($CFG->directorypermissions
)) {
376 $CFG->directorypermissions
= 0777; // Must be octal (that's why it's here)
379 /// Calculate and set $CFG->ostype to be used everywhere. Possible values are:
380 /// - WINDOWS: for any Windows flavour.
381 /// - UNIX: for the rest
382 /// Also, $CFG->os can continue being used if more specialization is required
383 if (stristr(PHP_OS
, 'win') && !stristr(PHP_OS
, 'darwin')) {
384 $CFG->ostype
= 'WINDOWS';
386 $CFG->ostype
= 'UNIX';
390 /// Set up default frame target string, based on $CFG->framename
391 $CFG->frametarget
= frametarget();
393 /// Setup cache dir for Smarty and others
394 if (!file_exists($CFG->dataroot
.'/cache')) {
395 make_upload_directory('cache');
398 /// Set up smarty template system
399 //require_once($CFG->libdir .'/smarty/Smarty.class.php');
400 //$smarty = new Smarty;
401 //$smarty->template_dir = $CFG->dirroot .'/templates/'. $CFG->template;
402 //if (!file_exists($CFG->dataroot .'/cache/smarty')) {
403 // make_upload_directory('cache/smarty');
405 //$smarty->compile_dir = $CFG->dataroot .'/cache/smarty';
407 /// Set up session handling
408 if(empty($CFG->respectsessionsettings
)) {
409 if (empty($CFG->dbsessions
)) { /// File-based sessions
411 // Some distros disable GC by setting probability to 0
412 // overriding the PHP default of 1
413 // (gc_probability is divided by gc_divisor, which defaults to 1000)
414 if (ini_get('session.gc_probability') == 0) {
415 ini_set('session.gc_probability', 1);
418 if (!empty($CFG->sessiontimeout
)) {
419 ini_set('session.gc_maxlifetime', $CFG->sessiontimeout
);
422 if (!file_exists($CFG->dataroot
.'/sessions')) {
423 make_upload_directory('sessions');
425 ini_set('session.save_path', $CFG->dataroot
.'/sessions');
427 } else { /// Database sessions
428 ini_set('session.save_handler', 'user');
430 $ADODB_SESSION_DRIVER = $CFG->dbtype
;
431 $ADODB_SESSION_CONNECT = $CFG->dbhost
;
432 $ADODB_SESSION_USER = $CFG->dbuser
;
433 $ADODB_SESSION_PWD = $CFG->dbpass
;
434 $ADODB_SESSION_DB = $CFG->dbname
;
435 $ADODB_SESSION_TBL = $CFG->prefix
.'sessions2';
436 if (!empty($CFG->sessiontimeout
)) {
437 $ADODB_SESS_LIFE = $CFG->sessiontimeout
;
440 require_once($CFG->libdir
. '/adodb/session/adodb-session2.php');
443 /// Set sessioncookie and sessioncookiepath variable if it isn't already
444 if (!isset($CFG->sessioncookie
)) {
445 $CFG->sessioncookie
= '';
447 if (!isset($CFG->sessioncookiedomain
)) {
448 $CFG->sessioncookiedomain
= '';
450 if (!isset($CFG->sessioncookiepath
)) {
451 $CFG->sessioncookiepath
= '/';
454 /// Configure ampersands in URLs
456 @ini_set
('arg_separator.output', '&');
458 /// Work around for a PHP bug see MDL-11237
460 @ini_set
('pcre.backtrack_limit', 20971520); // 20 MB
462 /// Location of standard files
464 $CFG->wordlist
= $CFG->libdir
.'/wordlist.txt';
465 $CFG->javascript
= $CFG->libdir
.'/javascript.php';
466 $CFG->moddata
= 'moddata';
468 // Alas, in some cases we cannot deal with magic_quotes.
469 if (defined('MOODLE_SANE_INPUT') && ini_get_bool('magic_quotes_gpc')) {
470 mdie("Facilities that require MOODLE_SANE_INPUT "
471 . "cannot work with magic_quotes_gpc. Please disable "
472 . "magic_quotes_gpc.");
474 /// A hack to get around magic_quotes_gpc being turned off
475 /// It is strongly recommended to enable "magic_quotes_gpc"!
476 if (!ini_get_bool('magic_quotes_gpc') && !defined('MOODLE_SANE_INPUT') ) {
477 function addslashes_deep($value) {
478 $value = is_array($value) ?
479 array_map('addslashes_deep', $value) :
483 $_POST = array_map('addslashes_deep', $_POST);
484 $_GET = array_map('addslashes_deep', $_GET);
485 $_COOKIE = array_map('addslashes_deep', $_COOKIE);
486 $_REQUEST = array_map('addslashes_deep', $_REQUEST);
487 if (!empty($_SERVER['REQUEST_URI'])) {
488 $_SERVER['REQUEST_URI'] = addslashes($_SERVER['REQUEST_URI']);
490 if (!empty($_SERVER['QUERY_STRING'])) {
491 $_SERVER['QUERY_STRING'] = addslashes($_SERVER['QUERY_STRING']);
493 if (!empty($_SERVER['HTTP_REFERER'])) {
494 $_SERVER['HTTP_REFERER'] = addslashes($_SERVER['HTTP_REFERER']);
496 if (!empty($_SERVER['PATH_INFO'])) {
497 $_SERVER['PATH_INFO'] = addslashes($_SERVER['PATH_INFO']);
499 if (!empty($_SERVER['PHP_SELF'])) {
500 $_SERVER['PHP_SELF'] = addslashes($_SERVER['PHP_SELF']);
502 if (!empty($_SERVER['PATH_TRANSLATED'])) {
503 $_SERVER['PATH_TRANSLATED'] = addslashes($_SERVER['PATH_TRANSLATED']);
507 /// neutralise nasty chars in PHP_SELF
508 if (isset($_SERVER['PHP_SELF'])) {
509 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
510 if ($phppos !== false) {
511 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+
4);
516 /// The following code can emulate "register globals" if required.
517 /// This hack is no longer being applied as of Moodle 1.6 unless you really
518 /// really want to use it (by defining $CFG->enableglobalshack = true)
520 if (!empty($CFG->enableglobalshack
) && !defined('MOODLE_SANE_INPUT')) {
521 if (!empty($CFG->detect_unchecked_vars
)) {
522 global $UNCHECKED_VARS;
523 $UNCHECKED_VARS->url
= $_SERVER['PHP_SELF'];
524 $UNCHECKED_VARS->vars
= array();
527 extract($_GET, EXTR_SKIP
); // Skip existing variables, ie CFG
528 if (!empty($CFG->detect_unchecked_vars
)) {
529 foreach ($_GET as $key => $val) {
530 $UNCHECKED_VARS->vars
[$key]=$val;
535 extract($_POST, EXTR_SKIP
); // Skip existing variables, ie CFG
536 if (!empty($CFG->detect_unchecked_vars
)) {
537 foreach ($_POST as $key => $val) {
538 $UNCHECKED_VARS->vars
[$key]=$val;
542 if (isset($_SERVER)) {
548 /// Load up global environment variables
550 if (!isset($CFG->cookiesecure
) or strpos($CFG->wwwroot
, 'https://') !== 0) {
551 $CFG->cookiesecure
= false;
554 if (!isset($CFG->cookiehttponly
)) {
555 $CFG->cookiehttponly
= false;
558 //discard session ID from POST, GET and globals to tighten security,
559 //this session fixation prevention can not be used in cookieless mode
560 if (empty($CFG->usesid
) && !defined('MOODLE_SANE_INPUT')) {
561 unset($
{'MoodleSession'.$CFG->sessioncookie
});
562 unset($_GET['MoodleSession'.$CFG->sessioncookie
]);
563 unset($_POST['MoodleSession'.$CFG->sessioncookie
]);
565 //compatibility hack for Moodle Cron, cookies not deleted, but set to "deleted" - should not be needed with $nomoodlecookie in cron.php now
566 if (!empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
]) && $_COOKIE['MoodleSession'.$CFG->sessioncookie
] == "deleted") {
567 unset($_COOKIE['MoodleSession'.$CFG->sessioncookie
]);
569 if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie
]) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie
] == "deleted") {
570 unset($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie
]);
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);
621 if (!empty($CFG->usesid
) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
])) {
622 require_once("$CFG->dirroot/lib/cookieless.php");
624 /// In VERY rare cases old PHP server bugs (it has been found on PHP 4.1.2 running
625 /// as a CGI under IIS on Windows) may require that you uncomment the following:
626 // session_register("USER");
627 // session_register("SESSION");
631 /// Load up theme variables (colours etc)
633 if (!isset($CFG->themedir
)) {
634 $CFG->themedir
= $CFG->dirroot
.'/theme';
635 $CFG->themewww
= $CFG->wwwroot
.'/theme';
637 $CFG->httpsthemewww
= $CFG->themewww
;
639 if (isset($_GET['theme'])) {
640 if ($CFG->allowthemechangeonurl ||
confirm_sesskey()) {
641 $themename = clean_param($_GET['theme'], PARAM_SAFEDIR
);
642 if (($themename != '') and file_exists($CFG->themedir
.'/'.$themename)) {
643 $SESSION->theme
= $themename;
649 if (!isset($CFG->theme
)) {
650 $CFG->theme
= 'standardwhite';
653 /// now do a session test to prevent random user switching - observed on some PHP/Apache combinations,
654 /// disable checks when working in cookieless mode
655 if (empty($CFG->usesid
) ||
!empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
])) {
656 if ($SESSION != NULL) {
657 if (empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie
])) {
658 report_session_error();
659 } else if (isset($SESSION->session_test
) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie
] != $SESSION->session_test
) {
660 report_session_error();
666 /// Set language/locale of printed times. If user has chosen a language that
667 /// that is different from the site language, then use the locale specified
668 /// in the language file. Otherwise, if the admin hasn't specified a locale
669 /// then use the one from the default language. Otherwise (and this is the
670 /// majority of cases), use the stored locale specified by admin.
671 if ($SESSION !== NULL && isset($_GET['lang']) && ($lang = clean_param($_GET['lang'], PARAM_SAFEDIR
))) {
672 if (file_exists($CFG->dataroot
.'/lang/'. $lang) or file_exists($CFG->dirroot
.'/lang/'. $lang)) {
673 $SESSION->lang
= $lang;
674 } else if (file_exists($CFG->dataroot
.'/lang/'.$lang.'_utf8') or
675 file_exists($CFG->dirroot
.'/lang/'.$lang.'_utf8')) {
676 $SESSION->lang
= $lang.'_utf8';
680 setup_lang_from_browser();
684 if (empty($CFG->lang
)) {
685 if (empty($SESSION->lang
)) {
686 $CFG->lang
= 'en_utf8';
688 $CFG->lang
= $SESSION->lang
;
692 // set default locale and themes - might be changed again later from require_login()
695 if (!empty($CFG->opentogoogle
)) {
696 if (empty($USER->id
)) { // Ignore anyone logged in
697 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
698 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
699 $USER = guest_user();
700 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
701 $USER = guest_user();
702 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) { // Yahoo
703 $USER = guest_user();
704 } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) { // Zoomspider
705 $USER = guest_user();
706 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSNBOT') !== false ) { // MSN Search
707 $USER = guest_user();
710 if (!empty($CFG->guestloginbutton
) && empty($USER) && !empty($_SERVER['HTTP_REFERER'])) {
711 if (strpos($_SERVER['HTTP_REFERER'], 'google') !== false ) {
712 $USER = guest_user();
713 } else if (strpos($_SERVER['HTTP_REFERER'], 'altavista') !== false ) {
714 $USER = guest_user();
718 load_all_capabilities();
723 if (!empty($CFG->guestloginbutton
)) {
724 if ($CFG->theme
== 'standard' or $CFG->theme
== 'standardwhite') { // Temporary measure to help with XHTML validation
725 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($_SESSION['USER']->id
)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
726 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
727 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
728 if ($USER = get_complete_user_data("username", "w3cvalidator")) {
729 $USER->ignoresesskey
= true;
731 $USER = guest_user();
738 /// Apache log intergration. In apache conf file one can use ${MOODULEUSER}n in
739 /// LogFormat to get the current logged in username in moodle.
740 if ($USER && function_exists('apache_note')
741 && !empty($CFG->apacheloguser
) && isset($USER->username
)) {
742 $apachelog_userid = $USER->id
;
743 $apachelog_username = clean_filename($USER->username
);
744 $apachelog_name = '';
745 if (isset($USER->firstname
)) {
746 // We can assume both will be set
747 // - even if to empty.
748 $apachelog_name = clean_filename($USER->firstname
. " " .
751 if (isset($USER->realuser
)) {
752 if ($realuser = get_record('user', 'id', $USER->realuser
)) {
753 $apachelog_username = clean_filename($realuser->username
." as ".$apachelog_username);
754 $apachelog_name = clean_filename($realuser->firstname
." ".$realuser->lastname
." as ".$apachelog_name);
755 $apachelog_userid = clean_filename($realuser->id
." as ".$apachelog_userid);
758 switch ($CFG->apacheloguser
) {
760 $logname = $apachelog_username;
763 $logname = $apachelog_name;
767 $logname = $apachelog_userid;
770 apache_note('MOODLEUSER', $logname);
773 /// Adjust ALLOWED_TAGS
774 adjust_allowed_tags();
777 /// Use a custom script replacement if one exists
778 if (!empty($CFG->customscripts
)) {
779 if (($customscript = custom_script_path()) !== false) {
780 require ($customscript);
784 /// note: we can not block non utf-8 installatrions here, because empty mysql database
785 /// might be converted to utf-8 in admin/index.php during installation