MDL-20695 no need to log prefetch attempts, we can not prevent them
[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
a91b910e 179/// Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
180 if (!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 {
b37eac91 184 /** @ignore */
a91b910e 185 define('CLI_SCRIPT', true);
186 }
187 }
188
133b5929 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
191
192
a91b910e 193/// The current directory in PHP version 4.3.0 and above isn't necessarily the
194/// directory of the script when run from the command line. The require_once()
195/// would fail, so we'll have to chdir()
196 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
197 chdir(dirname($_SERVER['argv'][0]));
198 }
199
200
b7009474 201/// Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides
220a90c5 202 $CFG->config_php_settings = (array)$CFG;
203
b7009474 204/// Set up some paths.
d3f9f1f8 205 $CFG->libdir = $CFG->dirroot .'/lib';
206
17da2e6f 207 if (!isset($CFG->themedir)) {
208 $CFG->themedir = $CFG->dirroot.'/theme';
209 $CFG->themewww = $CFG->wwwroot.'/theme';
210 }
211
b7009474 212/// Set httpswwwroot default value (this variable will replace $CFG->wwwroot
213/// inside some URLs used in HTTPSPAGEREQUIRED pages.
214 $CFG->httpswwwroot = $CFG->wwwroot;
215 $CFG->httpsthemewww = $CFG->themewww;
216
d3f9f1f8 217 require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
9d0dd812 218
6800d78e
FM
219/// Time to start counting
220 init_performance_info();
221
c84a2dbe 222/// Put $OUTPUT in place, so errors can be displayed.
223 $OUTPUT = new bootstrap_renderer();
224
225/// set handler for uncought exceptions - equivalent to print_error() call
226 set_exception_handler('default_exception_handler');
b8cea9b2 227
74944b73 228/// If there are any errors in the standard libraries we want to know!
346b1a24 229 error_reporting(E_ALL);
f9903ed0 230
d7196099 231/// Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
0a194c4c 232/// http://www.google.com/webmasters/faq.html#prefetchblock
d7196099 233 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
6800d78e 234 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
47c2811b
PS
235 echo('Prefetch request forbidden.');
236 exit(1);
d7196099 237 }
238
dae73c05 239/// Define admin directory
dae73c05 240 if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
1040ea85 241 $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
dae73c05 242 }
243
f33e1ed4 244 if (!isset($CFG->prefix)) { // Just in case it isn't defined in config.php
245 $CFG->prefix = '';
246 }
a8a71844 247
75249234 248/// Load up standard libraries
6aaa17c7 249 require_once($CFG->libdir .'/textlib.class.php'); // Functions to handle multibyte strings
93d4a373 250 require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output
251 require_once($CFG->libdir .'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
34a2777c 252 require_once($CFG->libdir .'/weblib.php'); // Functions relating to HTTP and content
253 require_once($CFG->libdir .'/outputlib.php'); // Functions for generating output
7d2a0492 254 require_once($CFG->libdir .'/navigationlib.php'); // Class for generating Navigation structure
8aff8482 255 require_once($CFG->libdir .'/dmllib.php'); // Database access
7e13be08 256 require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
c4d0753b 257 require_once($CFG->libdir .'/accesslib.php'); // Access control functions
258 require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
da8759cb 259 require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
d4a03c00 260 require_once($CFG->libdir .'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
93d4a373 261 require_once($CFG->libdir .'/blocklib.php'); // Library for controlling blocks
0856223c 262 require_once($CFG->libdir .'/eventslib.php'); // Events functions
13534ef7 263 require_once($CFG->libdir .'/grouplib.php'); // Groups functions
6800d78e 264 require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie related stuff
5ca3c838 265 require_once($CFG->libdir .'/editorlib.php'); // All text editor related functions and classes
a4c371ec 266
7fc1a27d 267 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
268 //the problem is that we need specific version of quickforms and hacked excel files :-(
269 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
647a1a82 270 //point zend include path to moodles lib/zend so that includes and requires will search there for files before anywhere else
271 ini_set('include_path', $CFG->libdir.'/zend' . PATH_SEPARATOR . ini_get('include_path'));
a4c371ec 272
fbf2c91e 273/// make sure PHP is not severly misconfigured
274 setup_validate_php_configuration();
275
f33e1ed4 276/// Increase memory limits if possible
f6b2709f 277 raise_memory_limit('96M'); // We should never NEED this much but just in case...
6c771454 278
279 /// Connect to the database
280 setup_DB();
f33e1ed4 281
aa893d6b 282/// Disable errors for now - needed for installation when debug enabled in config.php
283 if (isset($CFG->debug)) {
284 $originalconfigdebug = $CFG->debug;
285 unset($CFG->debug);
286 } else {
287 $originalconfigdebug = -1;
288 }
289
74944b73 290/// Load up any configuration from the config table
c23b0ea1 291 try {
292 $CFG = get_config();
293 } catch (dml_read_exception $e) {
294 // most probably empty db, going to install soon
295 }
f9903ed0 296
a78bee28 297/// Verify upgrade is not running unless we are in a script that needs to execute in any case
298 if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
775f811a 299 if ($CFG->upgraderunning < time()) {
300 unset_config('upgraderunning');
301 } else {
302 print_error('upgraderunning');
303 }
304 }
305
ceff9307 306/// Turn on SQL logging if required
307 if (!empty($CFG->logsql)) {
f33e1ed4 308 $DB->set_logging(true);
ceff9307 309 }
1e3e716f 310
aa893d6b 311/// Prevent warnings from roles when upgrading with debug on
312 if (isset($CFG->debug)) {
313 $originaldatabasedebug = $CFG->debug;
314 unset($CFG->debug);
315 } else {
316 $originaldatabasedebug = -1;
6fbf8d8f 317 }
4fd7ccc0 318
319
cf8133c4 320/// For now, only needed under apache (and probably unstable in other contexts)
cf1348ca 321 if (function_exists('register_shutdown_function')) {
cf8133c4 322 register_shutdown_function('moodle_request_shutdown');
323 }
324
bac6d28a 325/// Defining the site
c23b0ea1 326 try {
327 $SITE = get_site();
328 } catch (dml_read_exception $e) {
329 $SITE = null;
330 }
331
332 if ($SITE) {
475e9de8 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);
508b76d9 337 /// And the 'default' course
338 $COURSE = clone($SITE); // For now. This will usually get reset later in require_login() etc.
475e9de8 339 } else {
340 /**
341 * @ignore
342 */
343 define('SITEID', 1);
508b76d9 344 /// And the 'default' course
345 $COURSE = new object; // no site created yet
346 $COURSE->id = 1;
475e9de8 347 }
475e9de8 348
7d0c81b3 349 // define SYSCONTEXTID in config.php if you want to save some queries (after install or upgrade!)
350 if (!defined('SYSCONTEXTID')) {
0ecff22d 351 get_system_context();
6dd34e93 352 }
475e9de8 353
aa893d6b 354/// Set error reporting back to normal
355 if ($originaldatabasedebug == -1) {
7eb0b60a 356 $CFG->debug = DEBUG_MINIMAL;
aa893d6b 357 } else {
358 $CFG->debug = $originaldatabasedebug;
359 }
360 if ($originalconfigdebug !== -1) {
6800d78e 361 $CFG->debug = $originalconfigdebug;
aa893d6b 362 }
363 unset($originalconfigdebug);
364 unset($originaldatabasedebug);
365 error_reporting($CFG->debug);
366
2e9b772f
PS
367 // find out if PHP cofigured to display warnings,
368 // this is a security problem because some moodle scripts may
369 // disclose sensitive information
b3732604 370 if (ini_get_bool('display_errors')) {
371 define('WARN_DISPLAY_ERRORS_ENABLED', true);
372 }
2e9b772f 373 // If we want to display Moodle errors, then try and set PHP errors to match
6349a3ba 374 if (!isset($CFG->debugdisplay)) {
2e9b772f
PS
375 // keep it "as is" during installation
376 } else if (NO_DEBUG_DISPLAY) {
377 // some parts of Moodle cannot display errors and debug at all.
378 @ini_set('display_errors', '0');
379 @ini_set('log_errors', '1');
6349a3ba 380 } else if (empty($CFG->debugdisplay)) {
25338300 381 @ini_set('display_errors', '0');
382 @ini_set('log_errors', '1');
383 } else {
2e9b772f 384 // This is very problematic in XHTML strict mode!
25338300 385 @ini_set('display_errors', '1');
386 }
387
f9955801 388/// detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
2728a623 389 if (!empty($CFG->version) and $CFG->version < 2007101509) {
6d5a22b2 390 print_error('upgraderequires19', 'error');
f9955801 391 die;
392 }
393
419e1d93 394/// Shared-Memory cache init -- will set $MCACHE
395/// $MCACHE is a global object that offers at least add(), set() and delete()
396/// with similar semantics to the memcached PHP API http://php.net/memcache
392e7363 397/// Ensure we define rcache - so we can later check for it
398/// with a really fast and unambiguous $CFG->rcache === false
bb931a61 399 if (!empty($CFG->cachetype)) {
b1df0eb2 400 if (empty($CFG->rcache)) {
392e7363 401 $CFG->rcache = false;
402 } else {
403 $CFG->rcache = true;
404 }
405
406 // do not try to initialize if cache disabled
407 if (!$CFG->rcache) {
408 $CFG->cachetype = '';
409 }
410
bb931a61 411 if ($CFG->cachetype === 'memcached' && !empty($CFG->memcachedhosts)) {
412 if (!init_memcached()) {
413 debugging("Error initialising memcached");
0a2925be 414 $CFG->cachetype = '';
415 $CFG->rcache = false;
bb931a61 416 }
392e7363 417 } else if ($CFG->cachetype === 'eaccelerator') {
bb931a61 418 if (!init_eaccelerator()) {
419 debugging("Error initialising eaccelerator cache");
0a2925be 420 $CFG->cachetype = '';
6800d78e 421 $CFG->rcache = false;
bb931a61 422 }
423 }
392e7363 424
bb931a61 425 } else { // just make sure it is defined
426 $CFG->cachetype = '';
392e7363 427 $CFG->rcache = false;
2142d492 428 }
aa893d6b 429
0182c65c 430/// Set a default enrolment configuration (see bug 1598)
431 if (!isset($CFG->enrol)) {
a51e2a7f 432 $CFG->enrol = 'manual';
0182c65c 433 }
434
ed8365d9 435/// Set default enabled enrolment plugins
436 if (!isset($CFG->enrol_plugins_enabled)) {
437 $CFG->enrol_plugins_enabled = 'manual';
438 }
439
2e6d4273 440/// File permissions on created directories in the $CFG->dataroot
441
442 if (empty($CFG->directorypermissions)) {
443 $CFG->directorypermissions = 0777; // Must be octal (that's why it's here)
444 }
1aa01caf 445 if (empty($CFG->filepermissions)) {
446 $CFG->filepermissions = ($CFG->directorypermissions & 0666); // strip execute flags
447 }
448/// better also set default umask because recursive mkdir() does not apply permissions recursively otherwise
449 umask(0000);
2e6d4273 450
820743c5 451/// Calculate and set $CFG->ostype to be used everywhere. Possible values are:
452/// - WINDOWS: for any Windows flavour.
453/// - UNIX: for the rest
454/// Also, $CFG->os can continue being used if more specialization is required
323edd4b 455 if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
456 $CFG->ostype = 'WINDOWS';
457 } else {
458 $CFG->ostype = 'UNIX';
459 }
460 $CFG->os = PHP_OS;
820743c5 461
d21a5865 462/// Set up default frame target string, based on $CFG->framename
463 $CFG->frametarget = frametarget();
464
d6ead3a2 465/// Setup cache dir for Smarty and others
466 if (!file_exists($CFG->dataroot .'/cache')) {
467 make_upload_directory('cache');
468 }
469
de7e4ac9 470/// Configure ampersands in URLs
de7e4ac9 471 @ini_set('arg_separator.output', '&amp;');
472
e7aa5a88 473/// Work around for a PHP bug see MDL-11237
6800d78e 474 @ini_set('pcre.backtrack_limit', 20971520); // 20 MB
e7aa5a88 475
74944b73 476/// Location of standard files
da8759cb 477 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
1040ea85 478 $CFG->moddata = 'moddata';
f9903ed0 479
c84a2dbe 480/// Create the $PAGE global.
481 if (!empty($CFG->moodlepageclass)) {
482 $classname = $CFG->moodlepageclass;
483 } else {
484 $classname = 'moodle_page';
485 }
486 $PAGE = new $classname();
487 unset($classname);
488
294ce987 489/// A hack to get around magic_quotes_gpc being turned on
490/// It is strongly recommended to disable "magic_quotes_gpc"!
491 if (ini_get_bool('magic_quotes_gpc')) {
492 function stripslashes_deep($value) {
75249234 493 $value = is_array($value) ?
294ce987 494 array_map('stripslashes_deep', $value) :
495 stripslashes($value);
75249234 496 return $value;
24cc8ec9 497 }
294ce987 498 $_POST = array_map('stripslashes_deep', $_POST);
499 $_GET = array_map('stripslashes_deep', $_GET);
500 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
501 $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
578dcc40 502 if (!empty($_SERVER['REQUEST_URI'])) {
294ce987 503 $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']);
578dcc40 504 }
505 if (!empty($_SERVER['QUERY_STRING'])) {
294ce987 506 $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']);
578dcc40 507 }
508 if (!empty($_SERVER['HTTP_REFERER'])) {
294ce987 509 $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']);
578dcc40 510 }
511 if (!empty($_SERVER['PATH_INFO'])) {
294ce987 512 $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']);
578dcc40 513 }
514 if (!empty($_SERVER['PHP_SELF'])) {
294ce987 515 $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']);
578dcc40 516 }
517 if (!empty($_SERVER['PATH_TRANSLATED'])) {
294ce987 518 $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']);
b62dff99 519 }
f98cfb53 520 }
521
522/// neutralise nasty chars in PHP_SELF
523 if (isset($_SERVER['PHP_SELF'])) {
524 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
525 if ($phppos !== false) {
526 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
578dcc40 527 }
f98cfb53 528 unset($phppos);
aa6af0f8 529 }
7a302afc 530
9bda43e6 531/// initialise ME's
11e7b506 532 initialise_fullme();
f9903ed0 533
9bda43e6 534/// start session and prepare global $SESSION, $USER
535 session_get_instance();
536 $SESSION = &$_SESSION['SESSION'];
537 $USER = &$_SESSION['USER'];
538
b7009474 539/// Process theme change in the URL.
540 if (!empty($CFG->allowthemechangeonurl) && ($urlthemename = optional_param('theme', '', PARAM_SAFEDIR)) && confirm_sesskey()) {
541 try {
542 theme_config::load($urlthemename); // Makes sure the theme can be loaded without errors.
543 $SESSION->theme = $urlthemename;
544 } catch (Exception $e) {
545 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
18b9d664 546 }
547 }
b7009474 548 unset($urlthemename);
18b9d664 549
b7009474 550/// Ensure a valid theme is set.
18b9d664 551 if (!isset($CFG->theme)) {
34137668 552 $CFG->theme = 'standardwhite';
18b9d664 553 }
554
75249234 555/// Set language/locale of printed times. If user has chosen a language that
556/// that is different from the site language, then use the locale specified
339bb559 557/// in the language file. Otherwise, if the admin hasn't specified a locale
75249234 558/// then use the one from the default language. Otherwise (and this is the
339bb559 559/// majority of cases), use the stored locale specified by admin.
b7009474 560 if (($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
561 if (file_exists($CFG->dataroot .'/lang/'. $lang) or
562 file_exists($CFG->dirroot .'/lang/'. $lang)) {
32c60ce3 563 $SESSION->lang = $lang;
6800d78e 564 } else if (file_exists($CFG->dataroot.'/lang/'.$lang.'_utf8') or
b7009474 565 file_exists($CFG->dirroot .'/lang/'.$lang.'_utf8')) {
748390cd 566 $SESSION->lang = $lang.'_utf8';
32c60ce3 567 }
3e9b5d5a 568 }
b7009474 569 unset($lang);
ab036ed9 570
571 setup_lang_from_browser();
572
16ba7351 573 if (empty($CFG->lang)) {
6ec7ca0f 574 if (empty($SESSION->lang)) {
810944af 575 $CFG->lang = 'en_utf8';
6ec7ca0f 576 } else {
577 $CFG->lang = $SESSION->lang;
578 }
16ba7351 579 }
6800d78e 580
c13a5e71 581 // We used to call moodle_setlocale() and theme_setup() here, even though they
582 // would be called again from require_login or $PAGE->set_course. As an experiment
583 // I am going to try removing those calls. With luck it will help us find and
584 // fix a few bugs where scripts do not initialise thigns properly, wihtout causing
585 // too much grief.
1040ea85 586
360dde50 587 if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
1b813f5c 588 if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') { // Temporary measure to help with XHTML validation
589 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
590 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
591 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
592 if ($user = get_complete_user_data("username", "w3cvalidator")) {
593 $user->ignoresesskey = true;
594 } else {
595 $user = guest_user();
596 }
597 session_set_user($user);
9610a66e 598 }
599 }
600 }
601 }
602
a559eee6 603/// Apache log intergration. In apache conf file one can use ${MOODULEUSER}n in
604/// LogFormat to get the current logged in username in moodle.
ac0b19ff 605 if ($USER && function_exists('apache_note')
20e9d26f 606 && !empty($CFG->apacheloguser) && isset($USER->username)) {
2b287cac 607 $apachelog_userid = $USER->id;
ac0b19ff 608 $apachelog_username = clean_filename($USER->username);
609 $apachelog_name = '';
610 if (isset($USER->firstname)) {
611 // We can assume both will be set
612 // - even if to empty.
613 $apachelog_name = clean_filename($USER->firstname . " " .
614 $USER->lastname);
615 }
b7b64ff2 616 if (session_is_loggedinas()) {
617 $realuser = session_get_realuser();
6132768e 618 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
619 $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
620 $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
96e19e7b 621 }
5c5c16bb 622 switch ($CFG->apacheloguser) {
623 case 3:
2b287cac 624 $logname = $apachelog_username;
5c5c16bb 625 break;
626 case 2:
2b287cac 627 $logname = $apachelog_name;
5c5c16bb 628 break;
629 case 1:
630 default:
2b287cac 631 $logname = $apachelog_userid;
5c5c16bb 632 break;
633 }
634 apache_note('MOODLEUSER', $logname);
a559eee6 635 }
636
5982740d 637/// Adjust ALLOWED_TAGS
638 adjust_allowed_tags();
639
18259d4f 640/// Use a custom script replacement if one exists
641 if (!empty($CFG->customscripts)) {
642 if (($customscript = custom_script_path()) !== false) {
2b0b32d8 643 require ($customscript);
18259d4f 644 }
645 }
646
5035228f 647 // in the first case, ip in allowed list will be performed first
648 // for example, client IP is 192.168.1.1
649 // 192.168 subnet is an entry in allowed list
d255c6e9 650 // 192.168.1.1 is banned in blocked list
5035228f 651 // This ip will be banned finally
d255c6e9 652 if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
653 if (!empty($CFG->allowedip)) {
654 if (!remoteip_in_list($CFG->allowedip)) {
655 die(get_string('ipblocked', 'admin'));
656 }
ab99c8f0 657 }
d255c6e9 658 // need further check, client ip may a part of
659 // allowed subnet, but a IP address are listed
5035228f 660 // in blocked list.
d255c6e9 661 if (!empty($CFG->blockedip)) {
662 if (remoteip_in_list($CFG->blockedip)) {
663 die(get_string('ipblocked', 'admin'));
664 }
5035228f 665 }
d255c6e9 666
5035228f 667 } else {
668 // in this case, IPs in blocked list will be performed first
669 // for example, client IP is 192.168.1.1
670 // 192.168 subnet is an entry in blocked list
d255c6e9 671 // 192.168.1.1 is allowed in allowed list
5035228f 672 // This ip will be allowed finally
d255c6e9 673 if (!empty($CFG->blockedip)) {
674 if (remoteip_in_list($CFG->blockedip)) {
675 // if the allowed ip list is not empty
676 // IPs are not included in the allowed list will be
677 // blocked too
678 if (!empty($CFG->allowedip)) {
679 if (!remoteip_in_list($CFG->allowedip)) {
680 die(get_string('ipblocked', 'admin'));
681 }
682 } else {
683 die(get_string('ipblocked', 'admin'));
684 }
685 }
5035228f 686 }
d255c6e9 687 // if blocked list is null
688 // allowed list should be tested
689 if(!empty($CFG->allowedip)) {
690 if (!remoteip_in_list($CFG->allowedip)) {
691 die(get_string('ipblocked', 'admin'));
692 }
5035228f 693 }
d255c6e9 694
ab99c8f0 695 }
696
2e9b772f 697/// note: we can not block non utf-8 installations here, because empty mysql database
810944af 698/// might be converted to utf-8 in admin/index.php during installation
092bfaf1 699