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