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