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