Merge branch 'MDL-41565-master' of git://github.com/FMCorz/moodle
[moodle.git] / lib / setup.php
blobecf491765594782d154eab47da68e8e5812fbae5
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 (shared by cluster nodes).
41 * - $CFG->localcachedir - Path to moodle's local cache directory (not shared by cluster nodes).
43 * @global object $CFG
44 * @name $CFG
46 global $CFG; // this should be done much earlier in config.php before creating new $CFG instance
48 if (!isset($CFG)) {
49 if (defined('PHPUNIT_TEST') and PHPUNIT_TEST) {
50 echo('There is a missing "global $CFG;" at the beginning of the config.php file.'."\n");
51 exit(1);
52 } else {
53 // this should never happen, maybe somebody is accessing this file directly...
54 exit(1);
58 // We can detect real dirroot path reliably since PHP 4.0.2,
59 // it can not be anything else, there is no point in having this in config.php
60 $CFG->dirroot = dirname(dirname(__FILE__));
62 // Normalise dataroot - we do not want any symbolic links, trailing / or any other weirdness there
63 if (!isset($CFG->dataroot)) {
64 if (isset($_SERVER['REMOTE_ADDR'])) {
65 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
67 echo('Fatal error: $CFG->dataroot is not specified in config.php! Exiting.'."\n");
68 exit(1);
70 $CFG->dataroot = realpath($CFG->dataroot);
71 if ($CFG->dataroot === false) {
72 if (isset($_SERVER['REMOTE_ADDR'])) {
73 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
75 echo('Fatal error: $CFG->dataroot is not configured properly, directory does not exist or is not accessible! Exiting.'."\n");
76 exit(1);
77 } else if (!is_writable($CFG->dataroot)) {
78 if (isset($_SERVER['REMOTE_ADDR'])) {
79 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
81 echo('Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.'."\n");
82 exit(1);
85 // wwwroot is mandatory
86 if (!isset($CFG->wwwroot) or $CFG->wwwroot === 'http://example.com/moodle') {
87 if (isset($_SERVER['REMOTE_ADDR'])) {
88 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
90 echo('Fatal error: $CFG->wwwroot is not configured! Exiting.'."\n");
91 exit(1);
94 // Ignore $CFG->behat_wwwroot and use the same wwwroot.
95 if (!empty($CFG->behat_switchcompletely)) {
96 $CFG->behat_wwwroot = $CFG->wwwroot;
98 } else if (empty($CFG->behat_wwwroot)) {
99 // Default URL for acceptance testing, only accessible from localhost.
100 $CFG->behat_wwwroot = 'http://localhost:8000';
104 // Test environment is requested if:
105 // * Behat is running (constant set hooking the behat init process before requiring config.php).
106 // * If we are accessing though the built-in web server (cli-server).
107 // * If $CFG->behat_switchcompletely has been set (maintains CLI scripts behaviour, which ATM is only preventive).
108 // Test environment is enabled if:
109 // * User has previously enabled through admin/tool/behat/cli/util.php --enable.
110 // Both are required to switch to test mode
111 if (!defined('BEHAT_SITE_RUNNING') && !empty($CFG->behat_dataroot) &&
112 !empty($CFG->behat_prefix) && file_exists($CFG->behat_dataroot)) {
114 $CFG->behat_dataroot = realpath($CFG->behat_dataroot);
116 $switchcompletely = !empty($CFG->behat_switchcompletely) && php_sapi_name() !== 'cli';
117 $builtinserver = php_sapi_name() === 'cli-server';
118 $behatrunning = defined('BEHAT_TEST');
119 $testenvironmentrequested = $switchcompletely || $builtinserver || $behatrunning;
121 // Only switch to test environment if it has been enabled.
122 $testenvironmentenabled = file_exists($CFG->behat_dataroot . '/behat/test_environment_enabled.txt');
124 if ($testenvironmentenabled && $testenvironmentrequested) {
126 // Constant used to inform that the behat test site is being used,
127 // this includes all the processes executed by the behat CLI command like
128 // the site reset, the steps executed by the browser drivers when simulating
129 // a user session and a real session when browsing manually to $CFG->behat_wwwroot
130 // like the browser driver does automatically.
131 // Different from BEHAT_TEST as only this last one can perform CLI
132 // actions like reset the site or use data generators.
133 define('BEHAT_SITE_RUNNING', true);
135 // Clean extra config.php settings.
136 require_once(__DIR__ . '/../lib/behat/lib.php');
137 behat_clean_init_config();
139 $CFG->wwwroot = $CFG->behat_wwwroot;
140 $CFG->passwordsaltmain = 'moodle';
141 $CFG->prefix = $CFG->behat_prefix;
142 $CFG->dataroot = $CFG->behat_dataroot;
146 // Make sure there is some database table prefix.
147 if (!isset($CFG->prefix)) {
148 $CFG->prefix = '';
151 // Define admin directory
152 if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
153 $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
156 // Set up some paths.
157 $CFG->libdir = $CFG->dirroot .'/lib';
159 // Allow overriding of tempdir but be backwards compatible
160 if (!isset($CFG->tempdir)) {
161 $CFG->tempdir = "$CFG->dataroot/temp";
164 // Allow overriding of cachedir but be backwards compatible
165 if (!isset($CFG->cachedir)) {
166 $CFG->cachedir = "$CFG->dataroot/cache";
169 // Allow overriding of localcachedir.
170 if (!isset($CFG->localcachedir)) {
171 $CFG->localcachedir = "$CFG->dataroot/localcache";
174 // Location of all languages except core English pack.
175 if (!isset($CFG->langotherroot)) {
176 $CFG->langotherroot = $CFG->dataroot.'/lang';
179 // Location of local lang pack customisations (dirs with _local suffix).
180 if (!isset($CFG->langlocalroot)) {
181 $CFG->langlocalroot = $CFG->dataroot.'/lang';
184 // The current directory in PHP version 4.3.0 and above isn't necessarily the
185 // directory of the script when run from the command line. The require_once()
186 // would fail, so we'll have to chdir()
187 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
188 // do it only once - skip the second time when continuing after prevous abort
189 if (!defined('ABORT_AFTER_CONFIG') and !defined('ABORT_AFTER_CONFIG_CANCEL')) {
190 chdir(dirname($_SERVER['argv'][0]));
194 // sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
195 ini_set('precision', 14); // needed for upgrades and gradebook
197 // Scripts may request no debug and error messages in output
198 // please note it must be defined before including the config.php script
199 // and in some cases you also need to set custom default exception handler
200 if (!defined('NO_DEBUG_DISPLAY')) {
201 if (defined('AJAX_SCRIPT') and AJAX_SCRIPT) {
202 // Moodle AJAX scripts are expected to return json data, any PHP notices or errors break it badly,
203 // developers simply must learn to watch error log.
204 define('NO_DEBUG_DISPLAY', true);
205 } else {
206 define('NO_DEBUG_DISPLAY', false);
210 // Some scripts such as upgrade may want to prevent output buffering
211 if (!defined('NO_OUTPUT_BUFFERING')) {
212 define('NO_OUTPUT_BUFFERING', false);
215 // PHPUnit tests need custom init
216 if (!defined('PHPUNIT_TEST')) {
217 define('PHPUNIT_TEST', false);
220 // When set to true MUC (Moodle caching) will be disabled as much as possible.
221 // A special cache factory will be used to handle this situation and will use special "disabled" equivalents objects.
222 // This ensure we don't attempt to read or create the config file, don't use stores, don't provide persistence or
223 // storage of any kind.
224 if (!defined('CACHE_DISABLE_ALL')) {
225 define('CACHE_DISABLE_ALL', false);
228 // When set to true MUC (Moodle caching) will not use any of the defined or default stores.
229 // The Cache API will continue to function however this will force the use of the cachestore_dummy so all requests
230 // will be interacting with a static property and will never go to the proper cache stores.
231 // Useful if you need to avoid the stores for one reason or another.
232 if (!defined('CACHE_DISABLE_STORES')) {
233 define('CACHE_DISABLE_STORES', false);
236 // Servers should define a default timezone in php.ini, but if they don't then make sure something is defined.
237 // This is a quick hack. Ideally we should ask the admin for a value. See MDL-22625 for more on this.
238 if (function_exists('date_default_timezone_set') and function_exists('date_default_timezone_get')) {
239 $olddebug = error_reporting(0);
240 date_default_timezone_set(date_default_timezone_get());
241 error_reporting($olddebug);
242 unset($olddebug);
245 // Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
246 // In your new CLI scripts just add "define('CLI_SCRIPT', true);" before requiring config.php.
247 // Please note that one script can not be accessed from both CLI and web interface.
248 if (!defined('CLI_SCRIPT')) {
249 define('CLI_SCRIPT', false);
251 if (defined('WEB_CRON_EMULATED_CLI')) {
252 if (!isset($_SERVER['REMOTE_ADDR'])) {
253 echo('Web cron can not be executed as CLI script any more, please use admin/cli/cron.php instead'."\n");
254 exit(1);
256 } else if (isset($_SERVER['REMOTE_ADDR'])) {
257 if (CLI_SCRIPT) {
258 echo('Command line scripts can not be executed from the web interface');
259 exit(1);
261 } else {
262 if (!CLI_SCRIPT) {
263 echo('Command line scripts must define CLI_SCRIPT before requiring config.php'."\n");
264 exit(1);
268 // Detect CLI maintenance mode - this is useful when you need to mess with database, such as during upgrades
269 if (file_exists("$CFG->dataroot/climaintenance.html")) {
270 if (!CLI_SCRIPT) {
271 header('Content-type: text/html; charset=utf-8');
272 header('X-UA-Compatible: IE=edge');
273 /// Headers to make it not cacheable and json
274 header('Cache-Control: no-store, no-cache, must-revalidate');
275 header('Cache-Control: post-check=0, pre-check=0', false);
276 header('Pragma: no-cache');
277 header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
278 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
279 header('Accept-Ranges: none');
280 readfile("$CFG->dataroot/climaintenance.html");
281 die;
282 } else {
283 if (!defined('CLI_MAINTENANCE')) {
284 define('CLI_MAINTENANCE', true);
287 } else {
288 if (!defined('CLI_MAINTENANCE')) {
289 define('CLI_MAINTENANCE', false);
293 if (CLI_SCRIPT) {
294 // sometimes people use different PHP binary for web and CLI, make 100% sure they have the supported PHP version
295 if (version_compare(phpversion(), '5.3.3') < 0) {
296 $phpversion = phpversion();
297 // do NOT localise - lang strings would not work here and we CAN NOT move it to later place
298 echo "Moodle 2.5 or later requires at least PHP 5.3.3 (currently using version $phpversion).\n";
299 echo "Some servers may have multiple PHP versions installed, are you using the correct executable?\n";
300 exit(1);
304 // Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
305 if (!defined('AJAX_SCRIPT')) {
306 define('AJAX_SCRIPT', false);
309 // File permissions on created directories in the $CFG->dataroot
310 if (!isset($CFG->directorypermissions)) {
311 $CFG->directorypermissions = 02777; // Must be octal (that's why it's here)
313 if (!isset($CFG->filepermissions)) {
314 $CFG->filepermissions = ($CFG->directorypermissions & 0666); // strip execute flags
316 // Better also set default umask because developers often forget to include directory
317 // permissions in mkdir() and chmod() after creating new files.
318 if (!isset($CFG->umaskpermissions)) {
319 $CFG->umaskpermissions = (($CFG->directorypermissions & 0777) ^ 0777);
321 umask($CFG->umaskpermissions);
323 // exact version of currently used yui2 and 3 library
324 $CFG->yui2version = '2.9.0';
325 $CFG->yui3version = '3.9.1';
327 // Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides.
328 if (!isset($CFG->config_php_settings)) {
329 $CFG->config_php_settings = (array)$CFG;
330 // Forced plugin settings override values from config_plugins table.
331 unset($CFG->config_php_settings['forced_plugin_settings']);
332 if (!isset($CFG->forced_plugin_settings)) {
333 $CFG->forced_plugin_settings = array();
337 if (isset($CFG->debug)) {
338 $CFG->debug = (int)$CFG->debug;
339 } else {
340 $CFG->debug = 0;
342 $CFG->debugdeveloper = (($CFG->debug & (E_ALL | E_STRICT)) === (E_ALL | E_STRICT)); // DEBUG_DEVELOPER is not available yet.
344 if (!defined('MOODLE_INTERNAL')) { // Necessary because cli installer has to define it earlier.
345 /** Used by library scripts to check they are being called by Moodle. */
346 define('MOODLE_INTERNAL', true);
349 // core_component can be used in any scripts, it does not need anything else.
350 require_once($CFG->libdir .'/classes/component.php');
352 // special support for highly optimised scripts that do not need libraries and DB connection
353 if (defined('ABORT_AFTER_CONFIG')) {
354 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
355 // hide debugging if not enabled in config.php - we do not want to disclose sensitive info
356 error_reporting($CFG->debug);
357 if (NO_DEBUG_DISPLAY) {
358 // Some parts of Moodle cannot display errors and debug at all.
359 ini_set('display_errors', '0');
360 ini_set('log_errors', '1');
361 } else if (empty($CFG->debugdisplay)) {
362 ini_set('display_errors', '0');
363 ini_set('log_errors', '1');
364 } else {
365 ini_set('display_errors', '1');
367 require_once("$CFG->dirroot/lib/configonlylib.php");
368 return;
372 // Early profiling start, based exclusively on config.php $CFG settings
373 if (!empty($CFG->earlyprofilingenabled)) {
374 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
375 if (profiling_start()) {
376 register_shutdown_function('profiling_stop');
381 * Database connection. Used for all access to the database.
382 * @global moodle_database $DB
383 * @name $DB
385 global $DB;
388 * Moodle's wrapper round PHP's $_SESSION.
390 * @global object $SESSION
391 * @name $SESSION
393 global $SESSION;
396 * Holds the user table record for the current user. Will be the 'guest'
397 * user record for people who are not logged in.
399 * $USER is stored in the session.
401 * Items found in the user record:
402 * - $USER->email - The user's email address.
403 * - $USER->id - The unique integer identified of this user in the 'user' table.
404 * - $USER->email - The user's email address.
405 * - $USER->firstname - The user's first name.
406 * - $USER->lastname - The user's last name.
407 * - $USER->username - The user's login username.
408 * - $USER->secret - The user's ?.
409 * - $USER->lang - The user's language choice.
411 * @global object $USER
412 * @name $USER
414 global $USER;
417 * Frontpage course record
419 global $SITE;
422 * A central store of information about the current page we are
423 * generating in response to the user's request.
425 * @global moodle_page $PAGE
426 * @name $PAGE
428 global $PAGE;
431 * The current course. An alias for $PAGE->course.
432 * @global object $COURSE
433 * @name $COURSE
435 global $COURSE;
438 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
439 * it to generate HTML for output.
441 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
442 * for the magic that does that. After $OUTPUT has been initialised, any attempt
443 * to change something that affects the current theme ($PAGE->course, logged in use,
444 * httpsrequried ... will result in an exception.)
446 * Please note the $OUTPUT is replacing the old global $THEME object.
448 * @global object $OUTPUT
449 * @name $OUTPUT
451 global $OUTPUT;
454 * Full script path including all params, slash arguments, scheme and host.
456 * Note: Do NOT use for getting of current page URL or detection of https,
457 * instead use $PAGE->url or strpos($CFG->httpswwwroot, 'https:') === 0
459 * @global string $FULLME
460 * @name $FULLME
462 global $FULLME;
465 * Script path including query string and slash arguments without host.
466 * @global string $ME
467 * @name $ME
469 global $ME;
472 * $FULLME without slasharguments and query string.
473 * @global string $FULLSCRIPT
474 * @name $FULLSCRIPT
476 global $FULLSCRIPT;
479 * Relative moodle script path '/course/view.php'
480 * @global string $SCRIPT
481 * @name $SCRIPT
483 global $SCRIPT;
485 // Set httpswwwroot default value (this variable will replace $CFG->wwwroot
486 // inside some URLs used in HTTPSPAGEREQUIRED pages.
487 $CFG->httpswwwroot = $CFG->wwwroot;
489 require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
491 if (NO_OUTPUT_BUFFERING) {
492 // we have to call this always before starting session because it discards headers!
493 disable_output_buffering();
496 // Increase memory limits if possible
497 raise_memory_limit(MEMORY_STANDARD);
499 // Time to start counting
500 init_performance_info();
502 // Put $OUTPUT in place, so errors can be displayed.
503 $OUTPUT = new bootstrap_renderer();
505 // set handler for uncaught exceptions - equivalent to print_error() call
506 if (!PHPUNIT_TEST or PHPUNIT_UTIL) {
507 set_exception_handler('default_exception_handler');
508 set_error_handler('default_error_handler', E_ALL | E_STRICT);
511 // Acceptance tests needs special output to capture the errors,
512 // but not necessary for behat CLI command.
513 if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST')) {
514 require_once(__DIR__ . '/behat/lib.php');
515 set_error_handler('behat_error_handler', E_ALL | E_STRICT);
518 // If there are any errors in the standard libraries we want to know!
519 error_reporting(E_ALL | E_STRICT);
521 // Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
522 // http://www.google.com/webmasters/faq.html#prefetchblock
523 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
524 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
525 echo('Prefetch request forbidden.');
526 exit(1);
529 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
530 //the problem is that we need specific version of quickforms and hacked excel files :-(
531 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
532 //point zend include path to moodles lib/zend so that includes and requires will search there for files before anywhere else
533 //please note zend library is supposed to be used only from web service protocol classes, it may be removed in future
534 ini_set('include_path', $CFG->libdir.'/zend' . PATH_SEPARATOR . ini_get('include_path'));
536 // Register our classloader, in theory somebody might want to replace it to load other hacked core classes.
537 if (defined('COMPONENT_CLASSLOADER')) {
538 spl_autoload_register(COMPONENT_CLASSLOADER);
539 } else {
540 spl_autoload_register('core_component::classloader');
543 // Load up standard libraries
544 require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output
545 require_once($CFG->libdir .'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
546 require_once($CFG->libdir .'/weblib.php'); // Functions relating to HTTP and content
547 require_once($CFG->libdir .'/outputlib.php'); // Functions for generating output
548 require_once($CFG->libdir .'/navigationlib.php'); // Class for generating Navigation structure
549 require_once($CFG->libdir .'/dmllib.php'); // Database access
550 require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
551 require_once($CFG->libdir .'/accesslib.php'); // Access control functions
552 require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
553 require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
554 require_once($CFG->libdir .'/enrollib.php'); // Enrolment related functions
555 require_once($CFG->libdir .'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
556 require_once($CFG->libdir .'/blocklib.php'); // Library for controlling blocks
557 require_once($CFG->libdir .'/eventslib.php'); // Events functions
558 require_once($CFG->libdir .'/grouplib.php'); // Groups functions
559 require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie related stuff
560 require_once($CFG->libdir .'/editorlib.php'); // All text editor related functions and classes
561 require_once($CFG->libdir .'/messagelib.php'); // Messagelib functions
562 require_once($CFG->libdir .'/modinfolib.php'); // Cached information on course-module instances
563 require_once($CFG->dirroot.'/cache/lib.php'); // Cache API
565 // make sure PHP is not severly misconfigured
566 setup_validate_php_configuration();
568 // Connect to the database
569 setup_DB();
571 if (PHPUNIT_TEST and !PHPUNIT_UTIL) {
572 // make sure tests do not run in parallel
573 test_lock::acquire('phpunit');
574 $dbhash = null;
575 try {
576 if ($dbhash = $DB->get_field('config', 'value', array('name'=>'phpunittest'))) {
577 // reset DB tables
578 phpunit_util::reset_database();
580 } catch (Exception $e) {
581 if ($dbhash) {
582 // we ned to reinit if reset fails
583 $DB->set_field('config', 'value', 'na', array('name'=>'phpunittest'));
586 unset($dbhash);
589 // Load up any configuration from the config table or MUC cache.
590 if (PHPUNIT_TEST) {
591 phpunit_util::initialise_cfg();
592 } else {
593 initialise_cfg();
596 if (isset($CFG->debug)) {
597 $CFG->debug = (int)$CFG->debug;
598 error_reporting($CFG->debug);
599 } else {
600 $CFG->debug = 0;
602 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
604 // Find out if PHP configured to display warnings,
605 // this is a security problem because some moodle scripts may
606 // disclose sensitive information.
607 if (ini_get_bool('display_errors')) {
608 define('WARN_DISPLAY_ERRORS_ENABLED', true);
610 // If we want to display Moodle errors, then try and set PHP errors to match.
611 if (!isset($CFG->debugdisplay)) {
612 // Keep it "as is" during installation.
613 } else if (NO_DEBUG_DISPLAY) {
614 // Some parts of Moodle cannot display errors and debug at all.
615 ini_set('display_errors', '0');
616 ini_set('log_errors', '1');
617 } else if (empty($CFG->debugdisplay)) {
618 ini_set('display_errors', '0');
619 ini_set('log_errors', '1');
620 } else {
621 // This is very problematic in XHTML strict mode!
622 ini_set('display_errors', '1');
625 // Verify upgrade is not running unless we are in a script that needs to execute in any case
626 if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
627 if ($CFG->upgraderunning < time()) {
628 unset_config('upgraderunning');
629 } else {
630 print_error('upgraderunning');
634 // Turn on SQL logging if required
635 if (!empty($CFG->logsql)) {
636 $DB->set_logging(true);
639 // enable circular reference collector in PHP 5.3,
640 // it helps a lot when using large complex OOP structures such as in amos or gradebook
641 if (function_exists('gc_enable')) {
642 gc_enable();
645 // Register default shutdown tasks - such as Apache memory release helper, perf logging, etc.
646 if (function_exists('register_shutdown_function')) {
647 register_shutdown_function('moodle_request_shutdown');
650 // detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
651 if (!empty($CFG->version) and $CFG->version < 2007101509) {
652 print_error('upgraderequires19', 'error');
653 die;
656 // Calculate and set $CFG->ostype to be used everywhere. Possible values are:
657 // - WINDOWS: for any Windows flavour.
658 // - UNIX: for the rest
659 // Also, $CFG->os can continue being used if more specialization is required
660 if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
661 $CFG->ostype = 'WINDOWS';
662 } else {
663 $CFG->ostype = 'UNIX';
665 $CFG->os = PHP_OS;
667 // Configure ampersands in URLs
668 ini_set('arg_separator.output', '&amp;');
670 // Work around for a PHP bug see MDL-11237
671 ini_set('pcre.backtrack_limit', 20971520); // 20 MB
673 // Location of standard files
674 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
675 $CFG->moddata = 'moddata';
677 // A hack to get around magic_quotes_gpc being turned on
678 // It is strongly recommended to disable "magic_quotes_gpc"!
679 if (ini_get_bool('magic_quotes_gpc')) {
680 function stripslashes_deep($value) {
681 $value = is_array($value) ?
682 array_map('stripslashes_deep', $value) :
683 stripslashes($value);
684 return $value;
686 $_POST = array_map('stripslashes_deep', $_POST);
687 $_GET = array_map('stripslashes_deep', $_GET);
688 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
689 $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
690 if (!empty($_SERVER['REQUEST_URI'])) {
691 $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']);
693 if (!empty($_SERVER['QUERY_STRING'])) {
694 $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']);
696 if (!empty($_SERVER['HTTP_REFERER'])) {
697 $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']);
699 if (!empty($_SERVER['PATH_INFO'])) {
700 $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']);
702 if (!empty($_SERVER['PHP_SELF'])) {
703 $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']);
705 if (!empty($_SERVER['PATH_TRANSLATED'])) {
706 $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']);
710 // neutralise nasty chars in PHP_SELF
711 if (isset($_SERVER['PHP_SELF'])) {
712 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
713 if ($phppos !== false) {
714 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
716 unset($phppos);
719 // initialise ME's - this must be done BEFORE starting of session!
720 initialise_fullme();
722 // define SYSCONTEXTID in config.php if you want to save some queries,
723 // after install it must match the system context record id.
724 if (!defined('SYSCONTEXTID')) {
725 context_system::instance();
728 // Defining the site - aka frontpage course
729 try {
730 $SITE = get_site();
731 } catch (dml_exception $e) {
732 $SITE = null;
733 if (empty($CFG->version)) {
734 $SITE = new stdClass();
735 $SITE->id = 1;
736 $SITE->shortname = null;
737 } else {
738 throw $e;
741 // And the 'default' course - this will usually get reset later in require_login() etc.
742 $COURSE = clone($SITE);
743 /** @deprecated Id of the frontpage course, use $SITE->id instead */
744 define('SITEID', $SITE->id);
746 // init session prevention flag - this is defined on pages that do not want session
747 if (CLI_SCRIPT) {
748 // no sessions in CLI scripts possible
749 define('NO_MOODLE_COOKIES', true);
751 } else if (!defined('NO_MOODLE_COOKIES')) {
752 if (empty($CFG->version) or $CFG->version < 2009011900) {
753 // no session before sessions table gets created
754 define('NO_MOODLE_COOKIES', true);
755 } else if (CLI_SCRIPT) {
756 // CLI scripts can not have session
757 define('NO_MOODLE_COOKIES', true);
758 } else {
759 define('NO_MOODLE_COOKIES', false);
763 // start session and prepare global $SESSION, $USER
764 session_get_instance();
765 $SESSION = &$_SESSION['SESSION'];
766 $USER = &$_SESSION['USER'];
768 // Late profiling, only happening if early one wasn't started
769 if (!empty($CFG->profilingenabled)) {
770 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
771 if (profiling_start()) {
772 register_shutdown_function('profiling_stop');
776 // Process theme change in the URL.
777 if (!empty($CFG->allowthemechangeonurl) and !empty($_GET['theme'])) {
778 // we have to use _GET directly because we do not want this to interfere with _POST
779 $urlthemename = optional_param('theme', '', PARAM_PLUGIN);
780 try {
781 $themeconfig = theme_config::load($urlthemename);
782 // Makes sure the theme can be loaded without errors.
783 if ($themeconfig->name === $urlthemename) {
784 $SESSION->theme = $urlthemename;
785 } else {
786 unset($SESSION->theme);
788 unset($themeconfig);
789 unset($urlthemename);
790 } catch (Exception $e) {
791 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
794 unset($urlthemename);
796 // Ensure a valid theme is set.
797 if (!isset($CFG->theme)) {
798 $CFG->theme = 'standardwhite';
801 // Set language/locale of printed times. If user has chosen a language that
802 // that is different from the site language, then use the locale specified
803 // in the language file. Otherwise, if the admin hasn't specified a locale
804 // then use the one from the default language. Otherwise (and this is the
805 // majority of cases), use the stored locale specified by admin.
806 // note: do not accept lang parameter from POST
807 if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
808 if (get_string_manager()->translation_exists($lang, false)) {
809 $SESSION->lang = $lang;
812 unset($lang);
814 setup_lang_from_browser();
816 if (empty($CFG->lang)) {
817 if (empty($SESSION->lang)) {
818 $CFG->lang = 'en';
819 } else {
820 $CFG->lang = $SESSION->lang;
824 // Set the default site locale, a lot of the stuff may depend on this
825 // it is definitely too late to call this first in require_login()!
826 moodle_setlocale();
828 // Create the $PAGE global - this marks the PAGE and OUTPUT fully initialised, this MUST be done at the end of setup!
829 if (!empty($CFG->moodlepageclass)) {
830 if (!empty($CFG->moodlepageclassfile)) {
831 require_once($CFG->moodlepageclassfile);
833 $classname = $CFG->moodlepageclass;
834 } else {
835 $classname = 'moodle_page';
837 $PAGE = new $classname();
838 unset($classname);
841 if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
842 if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') { // Temporary measure to help with XHTML validation
843 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
844 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
845 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
846 if ($user = get_complete_user_data("username", "w3cvalidator")) {
847 $user->ignoresesskey = true;
848 } else {
849 $user = guest_user();
851 session_set_user($user);
857 // Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
858 // LogFormat to get the current logged in username in moodle.
859 if ($USER && function_exists('apache_note')
860 && !empty($CFG->apacheloguser) && isset($USER->username)) {
861 $apachelog_userid = $USER->id;
862 $apachelog_username = clean_filename($USER->username);
863 $apachelog_name = '';
864 if (isset($USER->firstname)) {
865 // We can assume both will be set
866 // - even if to empty.
867 $apachelog_name = clean_filename($USER->firstname . " " .
868 $USER->lastname);
870 if (session_is_loggedinas()) {
871 $realuser = session_get_realuser();
872 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
873 $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
874 $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
876 switch ($CFG->apacheloguser) {
877 case 3:
878 $logname = $apachelog_username;
879 break;
880 case 2:
881 $logname = $apachelog_name;
882 break;
883 case 1:
884 default:
885 $logname = $apachelog_userid;
886 break;
888 apache_note('MOODLEUSER', $logname);
891 // Use a custom script replacement if one exists
892 if (!empty($CFG->customscripts)) {
893 if (($customscript = custom_script_path()) !== false) {
894 require ($customscript);
898 if (PHPUNIT_TEST) {
899 // no ip blocking, these are CLI only
900 } else if (CLI_SCRIPT and !defined('WEB_CRON_EMULATED_CLI')) {
901 // no ip blocking
902 } else if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
903 // in this case, ip in allowed list will be performed first
904 // for example, client IP is 192.168.1.1
905 // 192.168 subnet is an entry in allowed list
906 // 192.168.1.1 is banned in blocked list
907 // This ip will be banned finally
908 if (!empty($CFG->allowedip)) {
909 if (!remoteip_in_list($CFG->allowedip)) {
910 die(get_string('ipblocked', 'admin'));
913 // need further check, client ip may a part of
914 // allowed subnet, but a IP address are listed
915 // in blocked list.
916 if (!empty($CFG->blockedip)) {
917 if (remoteip_in_list($CFG->blockedip)) {
918 die(get_string('ipblocked', 'admin'));
922 } else {
923 // in this case, IPs in blocked list will be performed first
924 // for example, client IP is 192.168.1.1
925 // 192.168 subnet is an entry in blocked list
926 // 192.168.1.1 is allowed in allowed list
927 // This ip will be allowed finally
928 if (!empty($CFG->blockedip)) {
929 if (remoteip_in_list($CFG->blockedip)) {
930 // if the allowed ip list is not empty
931 // IPs are not included in the allowed list will be
932 // blocked too
933 if (!empty($CFG->allowedip)) {
934 if (!remoteip_in_list($CFG->allowedip)) {
935 die(get_string('ipblocked', 'admin'));
937 } else {
938 die(get_string('ipblocked', 'admin'));
942 // if blocked list is null
943 // allowed list should be tested
944 if(!empty($CFG->allowedip)) {
945 if (!remoteip_in_list($CFG->allowedip)) {
946 die(get_string('ipblocked', 'admin'));
952 // // try to detect IE6 and prevent gzip because it is extremely buggy browser
953 if (!empty($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false) {
954 @ini_set('zlib.output_compression', 'Off');
955 if (function_exists('apache_setenv')) {
956 @apache_setenv('no-gzip', 1);
960 // Switch to CLI maintenance mode if required, we need to do it here after all the settings are initialised.
961 if (isset($CFG->maintenance_later) and $CFG->maintenance_later <= time()) {
962 if (!file_exists("$CFG->dataroot/climaintenance.html")) {
963 require_once("$CFG->libdir/adminlib.php");
964 enable_cli_maintenance_mode();
966 unset_config('maintenance_later');
967 if (AJAX_SCRIPT) {
968 die;
969 } else if (!CLI_SCRIPT) {
970 redirect(new moodle_url('/'));
974 // note: we can not block non utf-8 installations here, because empty mysql database
975 // might be converted to utf-8 in admin/index.php during installation
979 // this is a funny trick to make Eclipse believe that $OUTPUT and other globals
980 // contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
981 if (false) {
982 $DB = new moodle_database();
983 $OUTPUT = new core_renderer(null, null);
984 $PAGE = new moodle_page();