Updated the HEAD build version to 20091220
[moodle.git] / lib / setup.php
CommitLineData
da8759cb 1<?php
b37eac91 2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
da8759cb 18/**
19 * setup.php - Sets up sessions, connects to databases and so on
20 *
75249234 21 * Normally this is only called by the main config.php file
22 * Normally this file does not need to be edited.
b37eac91 23 *
24 * @package moodlecore
25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
da8759cb 27 */
28
78946b9b
PS
29// special support for highly optimised scripts that do not need libraries and DB connection
30if (defined('ABORT_AFTER_CONFIG')) {
31 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
32 require_once("$CFG->dirroot/lib/configonlylib.php");
33 return;
34 }
35}
36
da8759cb 37/**
e1d1b796 38 * Holds the core settings that affect how Moodle works. Some of its fields
39 * are set in config.php, and the rest are loaded from the config table.
40 *
41 * Some typical settings in the $CFG global:
42 * - $CFG->wwwroot - Path to moodle index directory in url format.
43 * - $CFG->dataroot - Path to moodle index directory on server's filesystem.
44 * - $CFG->libdir - Path to moodle's library folder on server's filesystem.
45 *
46 * @global object $CFG
b37eac91 47 * @name $CFG
e1d1b796 48 */
49global $CFG;
50
51/**
52 * Database connection. Used for all access to the database.
53 * @global moodle_database $DB
b37eac91 54 * @name $DB
e1d1b796 55 */
56global $DB;
57
58/**
59 * Moodle's wrapper round PHP's $_SESSION.
60 *
61 * @global object $SESSION
b37eac91 62 * @name $SESSION
e1d1b796 63 */
64global $SESSION;
65
66/**
67 * Holds the user table record for the current user. Will be the 'guest'
68 * user record for people who are not logged in.
69 *
70 * $USER is stored in the session.
da8759cb 71 *
735b8567 72 * Items found in the user record:
da8759cb 73 * - $USER->emailstop - Does the user want email sent to them?
74 * - $USER->email - The user's email address.
75 * - $USER->id - The unique integer identified of this user in the 'user' table.
76 * - $USER->email - The user's email address.
77 * - $USER->firstname - The user's first name.
78 * - $USER->lastname - The user's last name.
79 * - $USER->username - The user's login username.
80 * - $USER->secret - The user's ?.
81 * - $USER->lang - The user's language choice.
82 *
e1d1b796 83 * @global object $USER
b37eac91 84 * @name $USER
da8759cb 85 */
674fb525 86global $USER;
e1d1b796 87
c13a5e71 88/**
89 * A central store of information about the current page we are
90 * generating in response to the user's request.
91 *
92 * @global moodle_page $PAGE
b37eac91 93 * @name $PAGE
c13a5e71 94 */
95global $PAGE;
96
da8759cb 97/**
e1d1b796 98 * The current course. An alias for $PAGE->course.
99 * @global object $COURSE
b37eac91 100 * @name $COURSE
da8759cb 101 */
102global $COURSE;
e1d1b796 103
da8759cb 104/**
78946b9b 105 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
34a2777c 106 * it to generate HTML for output.
da8759cb 107 *
c84a2dbe 108 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
109 * for the magic that does that. After $OUTPUT has been initialised, any attempt
110 * to change something that affects the current theme ($PAGE->course, logged in use,
111 * httpsrequried ... will result in an exception.)
34a2777c 112 *
113 * @global object $OUTPUT
114 * @name $OUTPUT
115 */
116global $OUTPUT;
117
118/**
119 * $THEME is a global that defines the current theme.
da8759cb 120 *
ebebf55c 121 * @global theme_config $THEME
b37eac91 122 * @name THEME
da8759cb 123 */
124global $THEME;
f9903ed0 125
9d0dd812 126/**
e1d1b796 127 * Shared memory cache.
128 * @global object $MCACHE
b37eac91 129 * @name $MCACHE
e1d1b796 130 */
131global $MCACHE;
132
133/**
134 * A global to define if the page being displayed must run under HTTPS.
6800d78e 135 *
e1d1b796 136 * Its primary goal is to allow 100% HTTPS pages when $CFG->loginhttps is enabled. Default to false.
b7009474 137 * Its enabled only by the $PAGE->https_required() function and used in some pages to update some URLs
b37eac91 138 *
139 * @global bool $HTTPSPAGEREQUIRED
140 * @name $HTTPSPAGEREQUIRED
141 */
9d0dd812 142global $HTTPSPAGEREQUIRED;
143
b37eac91 144/**
145 * Full script path including all params, slash arguments, scheme and host.
146 * @global string $FULLME
147 * @name $FULLME
148 */
11e7b506 149global $FULLME;
e1d1b796 150
b37eac91 151/**
152 * Script path including query string and slash arguments without host.
153 * @global string $ME
154 * @name $ME
155 */
11e7b506 156global $ME;
e1d1b796 157
b37eac91 158/**
159 * $FULLME without slasharguments and query string.
160 * @global string $FULLSCRIPT
161 * @name $FULLSCRIPT
162 */
11e7b506 163global $FULLSCRIPT;
e1d1b796 164
b37eac91 165/**
166 * Relative moodle script path '/course/view.php'
167 * @global string $SCRIPT
168 * @name $SCRIPT
169 */
11e7b506 170global $SCRIPT;
9d0dd812 171
2e9b772f
PS
172// Scripts may request no debug and error messages in output
173// please note it must be defined before including the config.php script
174// and in some cases you also need to set custom default exception handler
175if (!defined('NO_DEBUG_DISPLAY')) {
176 define('NO_DEBUG_DISPLAY', false);
177}
178
ccda6d68
PS
179// wwwroot is mandatory
180if (!isset($CFG->wwwroot)) {
181 // trigger_error() is not correct here, no need to log this
47c2811b
PS
182 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
183 echo('Fatal: $CFG->wwwroot is not configured! Exiting.');
184 exit(1);
ccda6d68 185}
75249234 186
4dffc775
PS
187// Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
188if (!defined('CLI_SCRIPT')) { // CLI_SCRIPT might be defined in 'fake' CLI scripts like admin/cron.php
189 if (isset($_SERVER['REMOTE_ADDR'])) {
190 define('CLI_SCRIPT', false);
191 } else {
192 /** @ignore */
193 define('CLI_SCRIPT', true);
a91b910e 194 }
4dffc775 195}
a91b910e 196
4dffc775
PS
197// sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
198@ini_set('precision', 14); // needed for upgrades and gradebook
133b5929 199
4dffc775
PS
200// The current directory in PHP version 4.3.0 and above isn't necessarily the
201// directory of the script when run from the command line. The require_once()
202// would fail, so we'll have to chdir()
203if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
204 chdir(dirname($_SERVER['argv'][0]));
205}
133b5929 206
4dffc775
PS
207// Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides
208$CFG->config_php_settings = (array)$CFG;
a91b910e 209
4dffc775
PS
210// Set up some paths.
211$CFG->libdir = $CFG->dirroot .'/lib';
a91b910e 212
4dffc775
PS
213// Set httpswwwroot default value (this variable will replace $CFG->wwwroot
214// inside some URLs used in HTTPSPAGEREQUIRED pages.
215$CFG->httpswwwroot = $CFG->wwwroot;
d3f9f1f8 216
4dffc775 217require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
17da2e6f 218
4dffc775
PS
219// Time to start counting
220init_performance_info();
b7009474 221
4dffc775
PS
222// Put $OUTPUT in place, so errors can be displayed.
223$OUTPUT = new bootstrap_renderer();
9d0dd812 224
4c1c9175 225// set handler for uncaught exceptions - equivalent to print_error() call
4dffc775 226set_exception_handler('default_exception_handler');
6800d78e 227
4dffc775
PS
228// If there are any errors in the standard libraries we want to know!
229error_reporting(E_ALL);
c84a2dbe 230
4dffc775
PS
231// Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
232// http://www.google.com/webmasters/faq.html#prefetchblock
233if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
234 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
235 echo('Prefetch request forbidden.');
236 exit(1);
237}
b8cea9b2 238
4dffc775
PS
239// Define admin directory
240if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
241 $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
242}
f9903ed0 243
4dffc775
PS
244if (!isset($CFG->prefix)) { // Just in case it isn't defined in config.php
245 $CFG->prefix = '';
246}
d7196099 247
bf62f187
PS
248// exact version of currently used yui2 and 3 library
249$CFG->yui2version = '2.8.0r4';
bee934af 250$CFG->yui3version = '3.0.0';
bf62f187 251
4dffc775
PS
252// Load up standard libraries
253require_once($CFG->libdir .'/textlib.class.php'); // Functions to handle multibyte strings
254require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output
255require_once($CFG->libdir .'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
256require_once($CFG->libdir .'/weblib.php'); // Functions relating to HTTP and content
257require_once($CFG->libdir .'/outputlib.php'); // Functions for generating output
258require_once($CFG->libdir .'/navigationlib.php'); // Class for generating Navigation structure
259require_once($CFG->libdir .'/dmllib.php'); // Database access
260require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
261require_once($CFG->libdir .'/accesslib.php'); // Access control functions
262require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
263require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
264require_once($CFG->libdir .'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
265require_once($CFG->libdir .'/blocklib.php'); // Library for controlling blocks
266require_once($CFG->libdir .'/eventslib.php'); // Events functions
267require_once($CFG->libdir .'/grouplib.php'); // Groups functions
268require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie related stuff
269require_once($CFG->libdir .'/editorlib.php'); // All text editor related functions and classes
7c7d3afa 270require_once($CFG->libdir .'/messagelib.php'); // Messagelib functions
4dffc775
PS
271
272//point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
273//the problem is that we need specific version of quickforms and hacked excel files :-(
274ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
275//point zend include path to moodles lib/zend so that includes and requires will search there for files before anywhere else
6e03bed7 276//please note zend library is supposed to be used only from web service protocol classes, it may be removed in future
4dffc775
PS
277ini_set('include_path', $CFG->libdir.'/zend' . PATH_SEPARATOR . ini_get('include_path'));
278
279// make sure PHP is not severly misconfigured
280setup_validate_php_configuration();
281
282// Increase memory limits if possible
283raise_memory_limit('96M'); // We should never NEED this much but just in case...
284
285// Connect to the database
286setup_DB();
287
288// Disable errors for now - needed for installation when debug enabled in config.php
289if (isset($CFG->debug)) {
290 $originalconfigdebug = $CFG->debug;
291 unset($CFG->debug);
292} else {
293 $originalconfigdebug = -1;
294}
dae73c05 295
4dffc775
PS
296// Load up any configuration from the config table
297try {
298 $CFG = get_config();
299} catch (dml_read_exception $e) {
300 // most probably empty db, going to install soon
301}
a8a71844 302
4dffc775
PS
303// Verify upgrade is not running unless we are in a script that needs to execute in any case
304if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
305 if ($CFG->upgraderunning < time()) {
306 unset_config('upgraderunning');
aa893d6b 307 } else {
4dffc775 308 print_error('upgraderunning');
aa893d6b 309 }
4dffc775 310}
aa893d6b 311
4dffc775
PS
312// Turn on SQL logging if required
313if (!empty($CFG->logsql)) {
314 $DB->set_logging(true);
315}
f9903ed0 316
4dffc775
PS
317// Prevent warnings from roles when upgrading with debug on
318if (isset($CFG->debug)) {
319 $originaldatabasedebug = $CFG->debug;
320 unset($CFG->debug);
321} else {
322 $originaldatabasedebug = -1;
323}
775f811a 324
1e3e716f 325
4dffc775
PS
326// For now, only needed under apache (and probably unstable in other contexts)
327if (function_exists('register_shutdown_function')) {
328 register_shutdown_function('moodle_request_shutdown');
329}
4fd7ccc0 330
4dffc775
PS
331// Defining the site
332try {
333 $SITE = get_site();
4dffc775
PS
334 /**
335 * If $SITE global from {@link get_site()} is set then SITEID to $SITE->id, otherwise set to 1.
336 */
337 define('SITEID', $SITE->id);
7b51fb61
PS
338 // And the 'default' course - this will usually get reset later in require_login() etc.
339 $COURSE = clone($SITE);
340} catch (dml_read_exception $e) {
341 $SITE = null;
342 if (empty($CFG->version)) {
343 // we are just installing
344 /**
345 * @ignore
346 */
347 define('SITEID', 1);
348 // And the 'default' course
349 $COURSE = new object(); // no site created yet
350 $COURSE->id = 1;
351 } else {
352 throw $e;
353 }
4dffc775 354}
cf8133c4 355
4dffc775
PS
356// define SYSCONTEXTID in config.php if you want to save some queries (after install or upgrade!)
357if (!defined('SYSCONTEXTID')) {
358 get_system_context();
359}
c23b0ea1 360
4dffc775
PS
361// Set error reporting back to normal
362if ($originaldatabasedebug == -1) {
363 $CFG->debug = DEBUG_MINIMAL;
364} else {
365 $CFG->debug = $originaldatabasedebug;
366}
367if ($originalconfigdebug !== -1) {
368 $CFG->debug = $originalconfigdebug;
369}
370unset($originalconfigdebug);
371unset($originaldatabasedebug);
372error_reporting($CFG->debug);
373
374// find out if PHP cofigured to display warnings,
375// this is a security problem because some moodle scripts may
376// disclose sensitive information
377if (ini_get_bool('display_errors')) {
378 define('WARN_DISPLAY_ERRORS_ENABLED', true);
379}
380// If we want to display Moodle errors, then try and set PHP errors to match
381if (!isset($CFG->debugdisplay)) {
382 // keep it "as is" during installation
383} else if (NO_DEBUG_DISPLAY) {
384 // some parts of Moodle cannot display errors and debug at all.
385 @ini_set('display_errors', '0');
386 @ini_set('log_errors', '1');
387} else if (empty($CFG->debugdisplay)) {
388 @ini_set('display_errors', '0');
389 @ini_set('log_errors', '1');
390} else {
391 // This is very problematic in XHTML strict mode!
392 @ini_set('display_errors', '1');
393}
475e9de8 394
4dffc775
PS
395// detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
396if (!empty($CFG->version) and $CFG->version < 2007101509) {
397 print_error('upgraderequires19', 'error');
398 die;
399}
475e9de8 400
4dffc775
PS
401// Shared-Memory cache init -- will set $MCACHE
402// $MCACHE is a global object that offers at least add(), set() and delete()
403// with similar semantics to the memcached PHP API http://php.net/memcache
404// Ensure we define rcache - so we can later check for it
405// with a really fast and unambiguous $CFG->rcache === false
406if (!empty($CFG->cachetype)) {
407 if (empty($CFG->rcache)) {
408 $CFG->rcache = false;
25338300 409 } else {
4dffc775 410 $CFG->rcache = true;
25338300 411 }
412
4dffc775
PS
413 // do not try to initialize if cache disabled
414 if (!$CFG->rcache) {
415 $CFG->cachetype = '';
f9955801 416 }
417
4dffc775
PS
418 if ($CFG->cachetype === 'memcached' && !empty($CFG->memcachedhosts)) {
419 if (!init_memcached()) {
420 debugging("Error initialising memcached");
421 $CFG->cachetype = '';
392e7363 422 $CFG->rcache = false;
392e7363 423 }
4dffc775
PS
424 } else if ($CFG->cachetype === 'eaccelerator') {
425 if (!init_eaccelerator()) {
426 debugging("Error initialising eaccelerator cache");
392e7363 427 $CFG->cachetype = '';
4dffc775 428 $CFG->rcache = false;
392e7363 429 }
2142d492 430 }
aa893d6b 431
4dffc775
PS
432} else { // just make sure it is defined
433 $CFG->cachetype = '';
434 $CFG->rcache = false;
435}
0182c65c 436
4dffc775
PS
437// File permissions on created directories in the $CFG->dataroot
438if (empty($CFG->directorypermissions)) {
439 $CFG->directorypermissions = 0777; // Must be octal (that's why it's here)
440}
441if (empty($CFG->filepermissions)) {
442 $CFG->filepermissions = ($CFG->directorypermissions & 0666); // strip execute flags
443}
444// better also set default umask because recursive mkdir() does not apply permissions recursively otherwise
445umask(0000);
446
447// Calculate and set $CFG->ostype to be used everywhere. Possible values are:
448// - WINDOWS: for any Windows flavour.
449// - UNIX: for the rest
450// Also, $CFG->os can continue being used if more specialization is required
451if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
452 $CFG->ostype = 'WINDOWS';
453} else {
454 $CFG->ostype = 'UNIX';
455}
456$CFG->os = PHP_OS;
820743c5 457
4dffc775
PS
458// Set up default frame target string, based on $CFG->framename
459$CFG->frametarget = frametarget();
d21a5865 460
4dffc775
PS
461// Setup cache dir for Smarty and others
462if (!file_exists($CFG->dataroot .'/cache')) {
463 make_upload_directory('cache');
464}
d6ead3a2 465
4dffc775
PS
466// Configure ampersands in URLs
467@ini_set('arg_separator.output', '&amp;');
de7e4ac9 468
4dffc775
PS
469// Work around for a PHP bug see MDL-11237
470@ini_set('pcre.backtrack_limit', 20971520); // 20 MB
e7aa5a88 471
4dffc775 472// Location of standard files
4c1c9175
PS
473$CFG->wordlist = $CFG->libdir .'/wordlist.txt';
474$CFG->moddata = 'moddata';
f9903ed0 475
4dffc775
PS
476// Create the $PAGE global.
477if (!empty($CFG->moodlepageclass)) {
478 $classname = $CFG->moodlepageclass;
479} else {
480 $classname = 'moodle_page';
481}
482$PAGE = new $classname();
483unset($classname);
484
485// A hack to get around magic_quotes_gpc being turned on
486// It is strongly recommended to disable "magic_quotes_gpc"!
487if (ini_get_bool('magic_quotes_gpc')) {
488 function stripslashes_deep($value) {
489 $value = is_array($value) ?
490 array_map('stripslashes_deep', $value) :
491 stripslashes($value);
492 return $value;
c84a2dbe 493 }
4dffc775
PS
494 $_POST = array_map('stripslashes_deep', $_POST);
495 $_GET = array_map('stripslashes_deep', $_GET);
496 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
497 $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
498 if (!empty($_SERVER['REQUEST_URI'])) {
499 $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']);
f98cfb53 500 }
4dffc775
PS
501 if (!empty($_SERVER['QUERY_STRING'])) {
502 $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']);
503 }
504 if (!empty($_SERVER['HTTP_REFERER'])) {
505 $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']);
aa6af0f8 506 }
4dffc775
PS
507 if (!empty($_SERVER['PATH_INFO'])) {
508 $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']);
509 }
510 if (!empty($_SERVER['PHP_SELF'])) {
511 $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']);
512 }
513 if (!empty($_SERVER['PATH_TRANSLATED'])) {
514 $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']);
515 }
516}
7a302afc 517
4dffc775
PS
518// neutralise nasty chars in PHP_SELF
519if (isset($_SERVER['PHP_SELF'])) {
520 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
521 if ($phppos !== false) {
522 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
18b9d664 523 }
4dffc775
PS
524 unset($phppos);
525}
526
527// initialise ME's
528initialise_fullme();
529
530// start session and prepare global $SESSION, $USER
531session_get_instance();
532$SESSION = &$_SESSION['SESSION'];
533$USER = &$_SESSION['USER'];
18b9d664 534
4dffc775
PS
535// Process theme change in the URL.
536if (!empty($CFG->allowthemechangeonurl) && ($urlthemename = optional_param('theme', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
537 try {
538 theme_config::load($urlthemename); // Makes sure the theme can be loaded without errors.
539 $SESSION->theme = $urlthemename;
540 } catch (Exception $e) {
541 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
18b9d664 542 }
4dffc775
PS
543}
544unset($urlthemename);
18b9d664 545
4dffc775
PS
546// Ensure a valid theme is set.
547if (!isset($CFG->theme)) {
548 $CFG->theme = 'standardwhite';
549}
550
551// Set language/locale of printed times. If user has chosen a language that
552// that is different from the site language, then use the locale specified
553// in the language file. Otherwise, if the admin hasn't specified a locale
554// then use the one from the default language. Otherwise (and this is the
555// majority of cases), use the stored locale specified by admin.
556if (($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
557 if (file_exists($CFG->dataroot .'/lang/'. $lang) or
558 file_exists($CFG->dirroot .'/lang/'. $lang)) {
559 $SESSION->lang = $lang;
560 } else if (file_exists($CFG->dataroot.'/lang/'.$lang.'_utf8') or
561 file_exists($CFG->dirroot .'/lang/'.$lang.'_utf8')) {
562 $SESSION->lang = $lang.'_utf8';
3e9b5d5a 563 }
4dffc775
PS
564}
565unset($lang);
ab036ed9 566
4dffc775 567setup_lang_from_browser();
ab036ed9 568
4dffc775
PS
569if (empty($CFG->lang)) {
570 if (empty($SESSION->lang)) {
571 $CFG->lang = 'en_utf8';
572 } else {
573 $CFG->lang = $SESSION->lang;
16ba7351 574 }
4dffc775 575}
6800d78e 576
4dffc775
PS
577// We used to call moodle_setlocale() and theme_setup() here, even though they
578// would be called again from require_login or $PAGE->set_course. As an experiment
579// I am going to try removing those calls. With luck it will help us find and
4c1c9175 580// fix a few bugs where scripts do not initialise things properly, without causing
4dffc775
PS
581// too much grief.
582
583if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
584 if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') { // Temporary measure to help with XHTML validation
585 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
586 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
587 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
588 if ($user = get_complete_user_data("username", "w3cvalidator")) {
589 $user->ignoresesskey = true;
590 } else {
591 $user = guest_user();
9610a66e 592 }
4dffc775 593 session_set_user($user);
9610a66e 594 }
595 }
596 }
4dffc775 597}
9610a66e 598
4c1c9175 599// Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
4dffc775
PS
600// LogFormat to get the current logged in username in moodle.
601if ($USER && function_exists('apache_note')
602 && !empty($CFG->apacheloguser) && isset($USER->username)) {
603 $apachelog_userid = $USER->id;
604 $apachelog_username = clean_filename($USER->username);
605 $apachelog_name = '';
606 if (isset($USER->firstname)) {
607 // We can assume both will be set
608 // - even if to empty.
609 $apachelog_name = clean_filename($USER->firstname . " " .
610 $USER->lastname);
611 }
612 if (session_is_loggedinas()) {
613 $realuser = session_get_realuser();
614 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
615 $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
616 $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
617 }
618 switch ($CFG->apacheloguser) {
619 case 3:
620 $logname = $apachelog_username;
621 break;
622 case 2:
623 $logname = $apachelog_name;
624 break;
625 case 1:
626 default:
627 $logname = $apachelog_userid;
628 break;
629 }
630 apache_note('MOODLEUSER', $logname);
631}
a559eee6 632
4dffc775
PS
633// Adjust ALLOWED_TAGS
634adjust_allowed_tags();
5982740d 635
4dffc775
PS
636// Use a custom script replacement if one exists
637if (!empty($CFG->customscripts)) {
638 if (($customscript = custom_script_path()) !== false) {
639 require ($customscript);
18259d4f 640 }
4dffc775 641}
18259d4f 642
4dffc775
PS
643// in the first case, ip in allowed list will be performed first
644// for example, client IP is 192.168.1.1
645// 192.168 subnet is an entry in allowed list
646// 192.168.1.1 is banned in blocked list
647// This ip will be banned finally
648if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
649 if (!empty($CFG->allowedip)) {
650 if (!remoteip_in_list($CFG->allowedip)) {
651 die(get_string('ipblocked', 'admin'));
ab99c8f0 652 }
4dffc775
PS
653 }
654 // need further check, client ip may a part of
655 // allowed subnet, but a IP address are listed
656 // in blocked list.
657 if (!empty($CFG->blockedip)) {
658 if (remoteip_in_list($CFG->blockedip)) {
659 die(get_string('ipblocked', 'admin'));
5035228f 660 }
4dffc775 661 }
d255c6e9 662
4dffc775
PS
663} else {
664 // in this case, IPs in blocked list will be performed first
665 // for example, client IP is 192.168.1.1
666 // 192.168 subnet is an entry in blocked list
667 // 192.168.1.1 is allowed in allowed list
668 // This ip will be allowed finally
669 if (!empty($CFG->blockedip)) {
670 if (remoteip_in_list($CFG->blockedip)) {
671 // if the allowed ip list is not empty
672 // IPs are not included in the allowed list will be
673 // blocked too
674 if (!empty($CFG->allowedip)) {
675 if (!remoteip_in_list($CFG->allowedip)) {
d255c6e9 676 die(get_string('ipblocked', 'admin'));
677 }
4dffc775 678 } else {
d255c6e9 679 die(get_string('ipblocked', 'admin'));
680 }
5035228f 681 }
4dffc775
PS
682 }
683 // if blocked list is null
684 // allowed list should be tested
685 if(!empty($CFG->allowedip)) {
686 if (!remoteip_in_list($CFG->allowedip)) {
687 die(get_string('ipblocked', 'admin'));
688 }
ab99c8f0 689 }
690
4dffc775 691}
092bfaf1 692
4dffc775
PS
693// note: we can not block non utf-8 installations here, because empty mysql database
694// might be converted to utf-8 in admin/index.php during installation