Merge branch 'MDL-38112-24' of git://github.com/danpoltawski/moodle into MOODLE_24_STABLE
[moodle.git] / lib / setup.php
blob3037136f282149b1898d560ff9aae992b8d9cccf
1 <?php
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.
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/>.
18 /**
19 * setup.php - Sets up sessions, connects to databases and so on
21 * Normally this is only called by the main config.php file
22 * Normally this file does not need to be edited.
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
30 /**
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.
34 * Some typical settings in the $CFG global:
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.
39 * - $CFG->tempdir - Path to moodle's temp file directory on server's filesystem.
40 * - $CFG->cachedir - Path to moodle's cache directory on server's filesystem.
42 * @global object $CFG
43 * @name $CFG
45 global $CFG; // this should be done much earlier in config.php before creating new $CFG instance
47 if (!isset($CFG)) {
48 if (defined('PHPUNIT_TEST') and PHPUNIT_TEST) {
49 echo('There is a missing "global $CFG;" at the beginning of the config.php file.'."\n");
50 exit(1);
51 } else {
52 // this should never happen, maybe somebody is accessing this file directly...
53 exit(1);
57 // We can detect real dirroot path reliably since PHP 4.0.2,
58 // it can not be anything else, there is no point in having this in config.php
59 $CFG->dirroot = dirname(dirname(__FILE__));
61 // Normalise dataroot - we do not want any symbolic links, trailing / or any other weirdness there
62 if (!isset($CFG->dataroot)) {
63 if (isset($_SERVER['REMOTE_ADDR'])) {
64 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
66 echo('Fatal error: $CFG->dataroot is not specified in config.php! Exiting.'."\n");
67 exit(1);
69 $CFG->dataroot = realpath($CFG->dataroot);
70 if ($CFG->dataroot === false) {
71 if (isset($_SERVER['REMOTE_ADDR'])) {
72 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
74 echo('Fatal error: $CFG->dataroot is not configured properly, directory does not exist or is not accessible! Exiting.'."\n");
75 exit(1);
76 } else if (!is_writable($CFG->dataroot)) {
77 if (isset($_SERVER['REMOTE_ADDR'])) {
78 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
80 echo('Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.'."\n");
81 exit(1);
84 // wwwroot is mandatory
85 if (!isset($CFG->wwwroot) or $CFG->wwwroot === 'http://example.com/moodle') {
86 if (isset($_SERVER['REMOTE_ADDR'])) {
87 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
89 echo('Fatal error: $CFG->wwwroot is not configured! Exiting.'."\n");
90 exit(1);
93 // Define admin directory
94 if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
95 $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
98 // Set up some paths.
99 $CFG->libdir = $CFG->dirroot .'/lib';
101 // Allow overriding of tempdir but be backwards compatible
102 if (!isset($CFG->tempdir)) {
103 $CFG->tempdir = "$CFG->dataroot/temp";
106 // Allow overriding of cachedir but be backwards compatible
107 if (!isset($CFG->cachedir)) {
108 $CFG->cachedir = "$CFG->dataroot/cache";
111 // The current directory in PHP version 4.3.0 and above isn't necessarily the
112 // directory of the script when run from the command line. The require_once()
113 // would fail, so we'll have to chdir()
114 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
115 // do it only once - skip the second time when continuing after prevous abort
116 if (!defined('ABORT_AFTER_CONFIG') and !defined('ABORT_AFTER_CONFIG_CANCEL')) {
117 chdir(dirname($_SERVER['argv'][0]));
121 // sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
122 ini_set('precision', 14); // needed for upgrades and gradebook
124 // Scripts may request no debug and error messages in output
125 // please note it must be defined before including the config.php script
126 // and in some cases you also need to set custom default exception handler
127 if (!defined('NO_DEBUG_DISPLAY')) {
128 define('NO_DEBUG_DISPLAY', false);
131 // Some scripts such as upgrade may want to prevent output buffering
132 if (!defined('NO_OUTPUT_BUFFERING')) {
133 define('NO_OUTPUT_BUFFERING', false);
136 // PHPUnit tests need custom init
137 if (!defined('PHPUNIT_TEST')) {
138 define('PHPUNIT_TEST', false);
141 // When set to true MUC (Moodle caching) will be disabled as much as possible.
142 // A special cache factory will be used to handle this situation and will use special "disabled" equivalents objects.
143 // This ensure we don't attempt to read or create the config file, don't use stores, don't provide persistence or
144 // storage of any kind.
145 if (!defined('CACHE_DISABLE_ALL')) {
146 define('CACHE_DISABLE_ALL', false);
149 // When set to true MUC (Moodle caching) will not use any of the defined or default stores.
150 // The Cache API will continue to function however this will force the use of the cachestore_dummy so all requests
151 // will be interacting with a static property and will never go to the proper cache stores.
152 // Useful if you need to avoid the stores for one reason or another.
153 if (!defined('CACHE_DISABLE_STORES')) {
154 define('CACHE_DISABLE_STORES', false);
157 // Servers should define a default timezone in php.ini, but if they don't then make sure something is defined.
158 // This is a quick hack. Ideally we should ask the admin for a value. See MDL-22625 for more on this.
159 if (function_exists('date_default_timezone_set') and function_exists('date_default_timezone_get')) {
160 $olddebug = error_reporting(0);
161 date_default_timezone_set(date_default_timezone_get());
162 error_reporting($olddebug);
163 unset($olddebug);
166 // Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
167 // In your new CLI scripts just add "define('CLI_SCRIPT', true);" before requiring config.php.
168 // Please note that one script can not be accessed from both CLI and web interface.
169 if (!defined('CLI_SCRIPT')) {
170 define('CLI_SCRIPT', false);
172 if (defined('WEB_CRON_EMULATED_CLI')) {
173 if (!isset($_SERVER['REMOTE_ADDR'])) {
174 echo('Web cron can not be executed as CLI script any more, please use admin/cli/cron.php instead'."\n");
175 exit(1);
177 } else if (isset($_SERVER['REMOTE_ADDR'])) {
178 if (CLI_SCRIPT) {
179 echo('Command line scripts can not be executed from the web interface');
180 exit(1);
182 } else {
183 if (!CLI_SCRIPT) {
184 echo('Command line scripts must define CLI_SCRIPT before requiring config.php'."\n");
185 exit(1);
189 // Detect CLI maintenance mode - this is useful when you need to mess with database, such as during upgrades
190 if (file_exists("$CFG->dataroot/climaintenance.html")) {
191 if (!CLI_SCRIPT) {
192 header('Content-type: text/html; charset=utf-8');
193 header('X-UA-Compatible: IE=edge');
194 /// Headers to make it not cacheable and json
195 header('Cache-Control: no-store, no-cache, must-revalidate');
196 header('Cache-Control: post-check=0, pre-check=0', false);
197 header('Pragma: no-cache');
198 header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
199 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
200 header('Accept-Ranges: none');
201 readfile("$CFG->dataroot/climaintenance.html");
202 die;
203 } else {
204 if (!defined('CLI_MAINTENANCE')) {
205 define('CLI_MAINTENANCE', true);
208 } else {
209 if (!defined('CLI_MAINTENANCE')) {
210 define('CLI_MAINTENANCE', false);
214 if (CLI_SCRIPT) {
215 // sometimes people use different PHP binary for web and CLI, make 100% sure they have the supported PHP version
216 if (version_compare(phpversion(), '5.3.2') < 0) {
217 $phpversion = phpversion();
218 // do NOT localise - lang strings would not work here and we CAN NOT move it to later place
219 echo "Moodle 2.1 or later requires at least PHP 5.3.2 (currently using version $phpversion).\n";
220 echo "Some servers may have multiple PHP versions installed, are you using the correct executable?\n";
221 exit(1);
225 // Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
226 if (!defined('AJAX_SCRIPT')) {
227 define('AJAX_SCRIPT', false);
230 // File permissions on created directories in the $CFG->dataroot
231 if (empty($CFG->directorypermissions)) {
232 $CFG->directorypermissions = 02777; // Must be octal (that's why it's here)
234 if (empty($CFG->filepermissions)) {
235 $CFG->filepermissions = ($CFG->directorypermissions & 0666); // strip execute flags
237 // better also set default umask because recursive mkdir() does not apply permissions recursively otherwise
238 umask(0000);
240 // exact version of currently used yui2 and 3 library
241 $CFG->yui2version = '2.9.0';
242 $CFG->yui3version = '3.7.3';
245 // special support for highly optimised scripts that do not need libraries and DB connection
246 if (defined('ABORT_AFTER_CONFIG')) {
247 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
248 // hide debugging if not enabled in config.php - we do not want to disclose sensitive info
249 if (isset($CFG->debug)) {
250 error_reporting($CFG->debug);
251 } else {
252 error_reporting(0);
254 if (NO_DEBUG_DISPLAY) {
255 // Some parts of Moodle cannot display errors and debug at all.
256 ini_set('display_errors', '0');
257 ini_set('log_errors', '1');
258 } else if (empty($CFG->debugdisplay)) {
259 ini_set('display_errors', '0');
260 ini_set('log_errors', '1');
261 } else {
262 ini_set('display_errors', '1');
264 require_once("$CFG->dirroot/lib/configonlylib.php");
265 return;
269 /** Used by library scripts to check they are being called by Moodle */
270 if (!defined('MOODLE_INTERNAL')) { // necessary because cli installer has to define it earlier
271 define('MOODLE_INTERNAL', true);
274 // Early profiling start, based exclusively on config.php $CFG settings
275 if (!empty($CFG->earlyprofilingenabled)) {
276 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
277 if (profiling_start()) {
278 register_shutdown_function('profiling_stop');
283 * Database connection. Used for all access to the database.
284 * @global moodle_database $DB
285 * @name $DB
287 global $DB;
290 * Moodle's wrapper round PHP's $_SESSION.
292 * @global object $SESSION
293 * @name $SESSION
295 global $SESSION;
298 * Holds the user table record for the current user. Will be the 'guest'
299 * user record for people who are not logged in.
301 * $USER is stored in the session.
303 * Items found in the user record:
304 * - $USER->email - The user's email address.
305 * - $USER->id - The unique integer identified of this user in the 'user' table.
306 * - $USER->email - The user's email address.
307 * - $USER->firstname - The user's first name.
308 * - $USER->lastname - The user's last name.
309 * - $USER->username - The user's login username.
310 * - $USER->secret - The user's ?.
311 * - $USER->lang - The user's language choice.
313 * @global object $USER
314 * @name $USER
316 global $USER;
319 * Frontpage course record
321 global $SITE;
324 * A central store of information about the current page we are
325 * generating in response to the user's request.
327 * @global moodle_page $PAGE
328 * @name $PAGE
330 global $PAGE;
333 * The current course. An alias for $PAGE->course.
334 * @global object $COURSE
335 * @name $COURSE
337 global $COURSE;
340 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
341 * it to generate HTML for output.
343 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
344 * for the magic that does that. After $OUTPUT has been initialised, any attempt
345 * to change something that affects the current theme ($PAGE->course, logged in use,
346 * httpsrequried ... will result in an exception.)
348 * Please note the $OUTPUT is replacing the old global $THEME object.
350 * @global object $OUTPUT
351 * @name $OUTPUT
353 global $OUTPUT;
356 * Cache used within grouplib to cache data within current request only.
358 * @global object $GROUPLLIB_CACHE
359 * @name $GROUPLIB_CACHE
361 global $GROUPLIB_CACHE;
364 * Full script path including all params, slash arguments, scheme and host.
366 * Note: Do NOT use for getting of current page URL or detection of https,
367 * instead use $PAGE->url or strpos($CFG->httpswwwroot, 'https:') === 0
369 * @global string $FULLME
370 * @name $FULLME
372 global $FULLME;
375 * Script path including query string and slash arguments without host.
376 * @global string $ME
377 * @name $ME
379 global $ME;
382 * $FULLME without slasharguments and query string.
383 * @global string $FULLSCRIPT
384 * @name $FULLSCRIPT
386 global $FULLSCRIPT;
389 * Relative moodle script path '/course/view.php'
390 * @global string $SCRIPT
391 * @name $SCRIPT
393 global $SCRIPT;
395 // Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides
396 $CFG->config_php_settings = (array)$CFG;
397 // Forced plugin settings override values from config_plugins table
398 unset($CFG->config_php_settings['forced_plugin_settings']);
399 if (!isset($CFG->forced_plugin_settings)) {
400 $CFG->forced_plugin_settings = array();
402 // Set httpswwwroot default value (this variable will replace $CFG->wwwroot
403 // inside some URLs used in HTTPSPAGEREQUIRED pages.
404 $CFG->httpswwwroot = $CFG->wwwroot;
406 require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
408 if (NO_OUTPUT_BUFFERING) {
409 // we have to call this always before starting session because it discards headers!
410 disable_output_buffering();
413 // Increase memory limits if possible
414 raise_memory_limit(MEMORY_STANDARD);
416 // Time to start counting
417 init_performance_info();
419 // Put $OUTPUT in place, so errors can be displayed.
420 $OUTPUT = new bootstrap_renderer();
422 // set handler for uncaught exceptions - equivalent to print_error() call
423 if (!PHPUNIT_TEST or PHPUNIT_UTIL) {
424 set_exception_handler('default_exception_handler');
425 set_error_handler('default_error_handler', E_ALL | E_STRICT);
428 // If there are any errors in the standard libraries we want to know!
429 error_reporting(E_ALL | E_STRICT);
431 // Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
432 // http://www.google.com/webmasters/faq.html#prefetchblock
433 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
434 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
435 echo('Prefetch request forbidden.');
436 exit(1);
439 if (!isset($CFG->prefix)) { // Just in case it isn't defined in config.php
440 $CFG->prefix = '';
443 // location of all languages except core English pack
444 if (!isset($CFG->langotherroot)) {
445 $CFG->langotherroot = $CFG->dataroot.'/lang';
448 // location of local lang pack customisations (dirs with _local suffix)
449 if (!isset($CFG->langlocalroot)) {
450 $CFG->langlocalroot = $CFG->dataroot.'/lang';
453 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
454 //the problem is that we need specific version of quickforms and hacked excel files :-(
455 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
456 //point zend include path to moodles lib/zend so that includes and requires will search there for files before anywhere else
457 //please note zend library is supposed to be used only from web service protocol classes, it may be removed in future
458 ini_set('include_path', $CFG->libdir.'/zend' . PATH_SEPARATOR . ini_get('include_path'));
460 // Load up standard libraries
461 require_once($CFG->libdir .'/textlib.class.php'); // Functions to handle multibyte strings
462 require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output
463 require_once($CFG->libdir .'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
464 require_once($CFG->libdir .'/weblib.php'); // Functions relating to HTTP and content
465 require_once($CFG->libdir .'/outputlib.php'); // Functions for generating output
466 require_once($CFG->libdir .'/navigationlib.php'); // Class for generating Navigation structure
467 require_once($CFG->libdir .'/dmllib.php'); // Database access
468 require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
469 require_once($CFG->libdir .'/accesslib.php'); // Access control functions
470 require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
471 require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
472 require_once($CFG->libdir .'/enrollib.php'); // Enrolment related functions
473 require_once($CFG->libdir .'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
474 require_once($CFG->libdir .'/blocklib.php'); // Library for controlling blocks
475 require_once($CFG->libdir .'/eventslib.php'); // Events functions
476 require_once($CFG->libdir .'/grouplib.php'); // Groups functions
477 require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie related stuff
478 require_once($CFG->libdir .'/editorlib.php'); // All text editor related functions and classes
479 require_once($CFG->libdir .'/messagelib.php'); // Messagelib functions
480 require_once($CFG->libdir .'/modinfolib.php'); // Cached information on course-module instances
481 require_once($CFG->dirroot.'/cache/lib.php'); // Cache API
483 // make sure PHP is not severly misconfigured
484 setup_validate_php_configuration();
486 // Connect to the database
487 setup_DB();
489 if (PHPUNIT_TEST and !PHPUNIT_UTIL) {
490 // make sure tests do not run in parallel
491 phpunit_util::acquire_test_lock();
492 $dbhash = null;
493 try {
494 if ($dbhash = $DB->get_field('config', 'value', array('name'=>'phpunittest'))) {
495 // reset DB tables
496 phpunit_util::reset_database();
498 } catch (Exception $e) {
499 if ($dbhash) {
500 // we ned to reinit if reset fails
501 $DB->set_field('config', 'value', 'na', array('name'=>'phpunittest'));
504 unset($dbhash);
507 // Disable errors for now - needed for installation when debug enabled in config.php
508 if (isset($CFG->debug)) {
509 $originalconfigdebug = $CFG->debug;
510 unset($CFG->debug);
511 } else {
512 $originalconfigdebug = null;
515 // Load up any configuration from the config table
517 if (PHPUNIT_TEST) {
518 phpunit_util::initialise_cfg();
519 } else {
520 initialise_cfg();
523 // Verify upgrade is not running unless we are in a script that needs to execute in any case
524 if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
525 if ($CFG->upgraderunning < time()) {
526 unset_config('upgraderunning');
527 } else {
528 print_error('upgraderunning');
532 // Turn on SQL logging if required
533 if (!empty($CFG->logsql)) {
534 $DB->set_logging(true);
537 // Prevent warnings from roles when upgrading with debug on
538 if (isset($CFG->debug)) {
539 $originaldatabasedebug = $CFG->debug;
540 unset($CFG->debug);
541 } else {
542 $originaldatabasedebug = null;
545 // enable circular reference collector in PHP 5.3,
546 // it helps a lot when using large complex OOP structures such as in amos or gradebook
547 if (function_exists('gc_enable')) {
548 gc_enable();
551 // Register default shutdown tasks - such as Apache memory release helper, perf logging, etc.
552 if (function_exists('register_shutdown_function')) {
553 register_shutdown_function('moodle_request_shutdown');
556 // Set error reporting back to normal
557 if ($originaldatabasedebug === null) {
558 $CFG->debug = DEBUG_MINIMAL;
559 } else {
560 $CFG->debug = $originaldatabasedebug;
562 if ($originalconfigdebug !== null) {
563 $CFG->debug = $originalconfigdebug;
565 unset($originalconfigdebug);
566 unset($originaldatabasedebug);
567 error_reporting($CFG->debug);
569 // find out if PHP configured to display warnings,
570 // this is a security problem because some moodle scripts may
571 // disclose sensitive information
572 if (ini_get_bool('display_errors')) {
573 define('WARN_DISPLAY_ERRORS_ENABLED', true);
575 // If we want to display Moodle errors, then try and set PHP errors to match
576 if (!isset($CFG->debugdisplay)) {
577 // keep it "as is" during installation
578 } else if (NO_DEBUG_DISPLAY) {
579 // some parts of Moodle cannot display errors and debug at all.
580 ini_set('display_errors', '0');
581 ini_set('log_errors', '1');
582 } else if (empty($CFG->debugdisplay)) {
583 ini_set('display_errors', '0');
584 ini_set('log_errors', '1');
585 } else {
586 // This is very problematic in XHTML strict mode!
587 ini_set('display_errors', '1');
590 // detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
591 if (!empty($CFG->version) and $CFG->version < 2007101509) {
592 print_error('upgraderequires19', 'error');
593 die;
596 // Calculate and set $CFG->ostype to be used everywhere. Possible values are:
597 // - WINDOWS: for any Windows flavour.
598 // - UNIX: for the rest
599 // Also, $CFG->os can continue being used if more specialization is required
600 if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
601 $CFG->ostype = 'WINDOWS';
602 } else {
603 $CFG->ostype = 'UNIX';
605 $CFG->os = PHP_OS;
607 // Configure ampersands in URLs
608 ini_set('arg_separator.output', '&amp;');
610 // Work around for a PHP bug see MDL-11237
611 ini_set('pcre.backtrack_limit', 20971520); // 20 MB
613 // Location of standard files
614 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
615 $CFG->moddata = 'moddata';
617 // A hack to get around magic_quotes_gpc being turned on
618 // It is strongly recommended to disable "magic_quotes_gpc"!
619 if (ini_get_bool('magic_quotes_gpc')) {
620 function stripslashes_deep($value) {
621 $value = is_array($value) ?
622 array_map('stripslashes_deep', $value) :
623 stripslashes($value);
624 return $value;
626 $_POST = array_map('stripslashes_deep', $_POST);
627 $_GET = array_map('stripslashes_deep', $_GET);
628 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
629 $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
630 if (!empty($_SERVER['REQUEST_URI'])) {
631 $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']);
633 if (!empty($_SERVER['QUERY_STRING'])) {
634 $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']);
636 if (!empty($_SERVER['HTTP_REFERER'])) {
637 $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']);
639 if (!empty($_SERVER['PATH_INFO'])) {
640 $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']);
642 if (!empty($_SERVER['PHP_SELF'])) {
643 $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']);
645 if (!empty($_SERVER['PATH_TRANSLATED'])) {
646 $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']);
650 // neutralise nasty chars in PHP_SELF
651 if (isset($_SERVER['PHP_SELF'])) {
652 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
653 if ($phppos !== false) {
654 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
656 unset($phppos);
659 // initialise ME's - this must be done BEFORE starting of session!
660 initialise_fullme();
662 // define SYSCONTEXTID in config.php if you want to save some queries,
663 // after install it must match the system context record id.
664 if (!defined('SYSCONTEXTID')) {
665 get_system_context();
668 // Defining the site - aka frontpage course
669 try {
670 $SITE = get_site();
671 } catch (dml_exception $e) {
672 $SITE = null;
673 if (empty($CFG->version)) {
674 $SITE = new stdClass();
675 $SITE->id = 1;
676 } else {
677 throw $e;
680 // And the 'default' course - this will usually get reset later in require_login() etc.
681 $COURSE = clone($SITE);
682 /** @deprecated Id of the frontpage course, use $SITE->id instead */
683 define('SITEID', $SITE->id);
685 // init session prevention flag - this is defined on pages that do not want session
686 if (CLI_SCRIPT) {
687 // no sessions in CLI scripts possible
688 define('NO_MOODLE_COOKIES', true);
690 } else if (!defined('NO_MOODLE_COOKIES')) {
691 if (empty($CFG->version) or $CFG->version < 2009011900) {
692 // no session before sessions table gets created
693 define('NO_MOODLE_COOKIES', true);
694 } else if (CLI_SCRIPT) {
695 // CLI scripts can not have session
696 define('NO_MOODLE_COOKIES', true);
697 } else {
698 define('NO_MOODLE_COOKIES', false);
702 // start session and prepare global $SESSION, $USER
703 session_get_instance();
704 $SESSION = &$_SESSION['SESSION'];
705 $USER = &$_SESSION['USER'];
707 // Late profiling, only happening if early one wasn't started
708 if (!empty($CFG->profilingenabled)) {
709 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
710 if (profiling_start()) {
711 register_shutdown_function('profiling_stop');
715 // Process theme change in the URL.
716 if (!empty($CFG->allowthemechangeonurl) and !empty($_GET['theme'])) {
717 // we have to use _GET directly because we do not want this to interfere with _POST
718 $urlthemename = optional_param('theme', '', PARAM_PLUGIN);
719 try {
720 $themeconfig = theme_config::load($urlthemename);
721 // Makes sure the theme can be loaded without errors.
722 if ($themeconfig->name === $urlthemename) {
723 $SESSION->theme = $urlthemename;
724 } else {
725 unset($SESSION->theme);
727 unset($themeconfig);
728 unset($urlthemename);
729 } catch (Exception $e) {
730 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
733 unset($urlthemename);
735 // Ensure a valid theme is set.
736 if (!isset($CFG->theme)) {
737 $CFG->theme = 'standardwhite';
740 // Set language/locale of printed times. If user has chosen a language that
741 // that is different from the site language, then use the locale specified
742 // in the language file. Otherwise, if the admin hasn't specified a locale
743 // then use the one from the default language. Otherwise (and this is the
744 // majority of cases), use the stored locale specified by admin.
745 // note: do not accept lang parameter from POST
746 if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
747 if (get_string_manager()->translation_exists($lang, false)) {
748 $SESSION->lang = $lang;
751 unset($lang);
753 setup_lang_from_browser();
755 if (empty($CFG->lang)) {
756 if (empty($SESSION->lang)) {
757 $CFG->lang = 'en';
758 } else {
759 $CFG->lang = $SESSION->lang;
763 // Set the default site locale, a lot of the stuff may depend on this
764 // it is definitely too late to call this first in require_login()!
765 moodle_setlocale();
767 // Create the $PAGE global - this marks the PAGE and OUTPUT fully initialised, this MUST be done at the end of setup!
768 if (!empty($CFG->moodlepageclass)) {
769 if (!empty($CFG->moodlepageclassfile)) {
770 require_once($CFG->moodlepageclassfile);
772 $classname = $CFG->moodlepageclass;
773 } else {
774 $classname = 'moodle_page';
776 $PAGE = new $classname();
777 unset($classname);
780 if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
781 if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') { // Temporary measure to help with XHTML validation
782 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
783 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
784 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
785 if ($user = get_complete_user_data("username", "w3cvalidator")) {
786 $user->ignoresesskey = true;
787 } else {
788 $user = guest_user();
790 session_set_user($user);
796 // Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
797 // LogFormat to get the current logged in username in moodle.
798 if ($USER && function_exists('apache_note')
799 && !empty($CFG->apacheloguser) && isset($USER->username)) {
800 $apachelog_userid = $USER->id;
801 $apachelog_username = clean_filename($USER->username);
802 $apachelog_name = '';
803 if (isset($USER->firstname)) {
804 // We can assume both will be set
805 // - even if to empty.
806 $apachelog_name = clean_filename($USER->firstname . " " .
807 $USER->lastname);
809 if (session_is_loggedinas()) {
810 $realuser = session_get_realuser();
811 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
812 $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
813 $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
815 switch ($CFG->apacheloguser) {
816 case 3:
817 $logname = $apachelog_username;
818 break;
819 case 2:
820 $logname = $apachelog_name;
821 break;
822 case 1:
823 default:
824 $logname = $apachelog_userid;
825 break;
827 apache_note('MOODLEUSER', $logname);
830 // Use a custom script replacement if one exists
831 if (!empty($CFG->customscripts)) {
832 if (($customscript = custom_script_path()) !== false) {
833 require ($customscript);
837 if (PHPUNIT_TEST) {
838 // no ip blocking, these are CLI only
839 } else if (CLI_SCRIPT and !defined('WEB_CRON_EMULATED_CLI')) {
840 // no ip blocking
841 } else if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
842 // in this case, ip in allowed list will be performed first
843 // for example, client IP is 192.168.1.1
844 // 192.168 subnet is an entry in allowed list
845 // 192.168.1.1 is banned in blocked list
846 // This ip will be banned finally
847 if (!empty($CFG->allowedip)) {
848 if (!remoteip_in_list($CFG->allowedip)) {
849 die(get_string('ipblocked', 'admin'));
852 // need further check, client ip may a part of
853 // allowed subnet, but a IP address are listed
854 // in blocked list.
855 if (!empty($CFG->blockedip)) {
856 if (remoteip_in_list($CFG->blockedip)) {
857 die(get_string('ipblocked', 'admin'));
861 } else {
862 // in this case, IPs in blocked list will be performed first
863 // for example, client IP is 192.168.1.1
864 // 192.168 subnet is an entry in blocked list
865 // 192.168.1.1 is allowed in allowed list
866 // This ip will be allowed finally
867 if (!empty($CFG->blockedip)) {
868 if (remoteip_in_list($CFG->blockedip)) {
869 // if the allowed ip list is not empty
870 // IPs are not included in the allowed list will be
871 // blocked too
872 if (!empty($CFG->allowedip)) {
873 if (!remoteip_in_list($CFG->allowedip)) {
874 die(get_string('ipblocked', 'admin'));
876 } else {
877 die(get_string('ipblocked', 'admin'));
881 // if blocked list is null
882 // allowed list should be tested
883 if(!empty($CFG->allowedip)) {
884 if (!remoteip_in_list($CFG->allowedip)) {
885 die(get_string('ipblocked', 'admin'));
891 // // try to detect IE6 and prevent gzip because it is extremely buggy browser
892 if (!empty($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false) {
893 @ini_set('zlib.output_compression', 'Off');
894 if (function_exists('apache_setenv')) {
895 @apache_setenv('no-gzip', 1);
900 // note: we can not block non utf-8 installations here, because empty mysql database
901 // might be converted to utf-8 in admin/index.php during installation
905 // this is a funny trick to make Eclipse believe that $OUTPUT and other globals
906 // contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
907 if (false) {
908 $DB = new moodle_database();
909 $OUTPUT = new core_renderer(null, null);
910 $PAGE = new moodle_page();