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