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