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