MDL-38041 behat: Capturing also PHP debug messages
[moodle.git] / lib / setup.php
blob213ac7030edc07cfcc98a2db5808e806b5dd80b9
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 // Ignore $CFG->behat_wwwroot and use the same wwwroot.
94 if (!empty($CFG->behat_switchcompletely)) {
95 $CFG->behat_wwwroot = $CFG->wwwroot;
97 } else if (empty($CFG->behat_wwwroot)) {
98 // Default URL for acceptance testing, only accessible from localhost.
99 $CFG->behat_wwwroot = 'http://localhost:8000';
103 // Test environment is requested if:
104 // * Behat is running (constant set hooking the behat init process before requiring config.php).
105 // * If we are accessing though the built-in web server (cli-server).
106 // * If $CFG->behat_switchcompletely has been set (maintains CLI scripts behaviour, which ATM is only preventive).
107 // Test environment is enabled if:
108 // * User has previously enabled through admin/tool/behat/cli/util.php --enable.
109 // Both are required to switch to test mode
110 if (!empty($CFG->behat_dataroot) && !empty($CFG->behat_prefix) && file_exists($CFG->behat_dataroot)) {
112 $CFG->behat_dataroot = realpath($CFG->behat_dataroot);
114 $switchcompletely = !empty($CFG->behat_switchcompletely) && php_sapi_name() !== 'cli';
115 $builtinserver = php_sapi_name() === 'cli-server';
116 $behatrunning = defined('BEHAT_RUNNING');
117 $testenvironmentrequested = $switchcompletely || $builtinserver || $behatrunning;
119 // Only switch to test environment if it has been enabled.
120 $testenvironmentenabled = file_exists($CFG->behat_dataroot . '/behat/test_environment_enabled.txt');
122 if ($testenvironmentenabled && $testenvironmentrequested) {
123 $CFG->wwwroot = $CFG->behat_wwwroot;
124 $CFG->passwordsaltmain = 'moodle';
125 $CFG->originaldataroot = $CFG->dataroot;
126 $CFG->prefix = $CFG->behat_prefix;
127 $CFG->dataroot = $CFG->behat_dataroot;
131 // Define admin directory
132 if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
133 $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
136 // Set up some paths.
137 $CFG->libdir = $CFG->dirroot .'/lib';
139 // Allow overriding of tempdir but be backwards compatible
140 if (!isset($CFG->tempdir)) {
141 $CFG->tempdir = "$CFG->dataroot/temp";
144 // Allow overriding of cachedir but be backwards compatible
145 if (!isset($CFG->cachedir)) {
146 $CFG->cachedir = "$CFG->dataroot/cache";
149 // The current directory in PHP version 4.3.0 and above isn't necessarily the
150 // directory of the script when run from the command line. The require_once()
151 // would fail, so we'll have to chdir()
152 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
153 // do it only once - skip the second time when continuing after prevous abort
154 if (!defined('ABORT_AFTER_CONFIG') and !defined('ABORT_AFTER_CONFIG_CANCEL')) {
155 chdir(dirname($_SERVER['argv'][0]));
159 // sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
160 ini_set('precision', 14); // needed for upgrades and gradebook
162 // Scripts may request no debug and error messages in output
163 // please note it must be defined before including the config.php script
164 // and in some cases you also need to set custom default exception handler
165 if (!defined('NO_DEBUG_DISPLAY')) {
166 define('NO_DEBUG_DISPLAY', false);
169 // Some scripts such as upgrade may want to prevent output buffering
170 if (!defined('NO_OUTPUT_BUFFERING')) {
171 define('NO_OUTPUT_BUFFERING', false);
174 // PHPUnit tests need custom init
175 if (!defined('PHPUNIT_TEST')) {
176 define('PHPUNIT_TEST', false);
179 // When set to true MUC (Moodle caching) will be disabled as much as possible.
180 // A special cache factory will be used to handle this situation and will use special "disabled" equivalents objects.
181 // This ensure we don't attempt to read or create the config file, don't use stores, don't provide persistence or
182 // storage of any kind.
183 if (!defined('CACHE_DISABLE_ALL')) {
184 define('CACHE_DISABLE_ALL', false);
187 // When set to true MUC (Moodle caching) will not use any of the defined or default stores.
188 // The Cache API will continue to function however this will force the use of the cachestore_dummy so all requests
189 // will be interacting with a static property and will never go to the proper cache stores.
190 // Useful if you need to avoid the stores for one reason or another.
191 if (!defined('CACHE_DISABLE_STORES')) {
192 define('CACHE_DISABLE_STORES', false);
195 // Servers should define a default timezone in php.ini, but if they don't then make sure something is defined.
196 // This is a quick hack. Ideally we should ask the admin for a value. See MDL-22625 for more on this.
197 if (function_exists('date_default_timezone_set') and function_exists('date_default_timezone_get')) {
198 $olddebug = error_reporting(0);
199 date_default_timezone_set(date_default_timezone_get());
200 error_reporting($olddebug);
201 unset($olddebug);
204 // Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
205 // In your new CLI scripts just add "define('CLI_SCRIPT', true);" before requiring config.php.
206 // Please note that one script can not be accessed from both CLI and web interface.
207 if (!defined('CLI_SCRIPT')) {
208 define('CLI_SCRIPT', false);
210 if (defined('WEB_CRON_EMULATED_CLI')) {
211 if (!isset($_SERVER['REMOTE_ADDR'])) {
212 echo('Web cron can not be executed as CLI script any more, please use admin/cli/cron.php instead'."\n");
213 exit(1);
215 } else if (isset($_SERVER['REMOTE_ADDR'])) {
216 if (CLI_SCRIPT) {
217 echo('Command line scripts can not be executed from the web interface');
218 exit(1);
220 } else {
221 if (!CLI_SCRIPT) {
222 echo('Command line scripts must define CLI_SCRIPT before requiring config.php'."\n");
223 exit(1);
227 // Detect CLI maintenance mode - this is useful when you need to mess with database, such as during upgrades
228 if (file_exists("$CFG->dataroot/climaintenance.html")) {
229 if (!CLI_SCRIPT) {
230 header('Content-type: text/html; charset=utf-8');
231 header('X-UA-Compatible: IE=edge');
232 /// Headers to make it not cacheable and json
233 header('Cache-Control: no-store, no-cache, must-revalidate');
234 header('Cache-Control: post-check=0, pre-check=0', false);
235 header('Pragma: no-cache');
236 header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
237 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
238 header('Accept-Ranges: none');
239 readfile("$CFG->dataroot/climaintenance.html");
240 die;
241 } else {
242 if (!defined('CLI_MAINTENANCE')) {
243 define('CLI_MAINTENANCE', true);
246 } else {
247 if (!defined('CLI_MAINTENANCE')) {
248 define('CLI_MAINTENANCE', false);
252 if (CLI_SCRIPT) {
253 // sometimes people use different PHP binary for web and CLI, make 100% sure they have the supported PHP version
254 if (version_compare(phpversion(), '5.3.3') < 0) {
255 $phpversion = phpversion();
256 // do NOT localise - lang strings would not work here and we CAN NOT move it to later place
257 echo "Moodle 2.5 or later requires at least PHP 5.3.3 (currently using version $phpversion).\n";
258 echo "Some servers may have multiple PHP versions installed, are you using the correct executable?\n";
259 exit(1);
263 // Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
264 if (!defined('AJAX_SCRIPT')) {
265 define('AJAX_SCRIPT', false);
268 // File permissions on created directories in the $CFG->dataroot
269 if (empty($CFG->directorypermissions)) {
270 $CFG->directorypermissions = 02777; // Must be octal (that's why it's here)
272 if (empty($CFG->filepermissions)) {
273 $CFG->filepermissions = ($CFG->directorypermissions & 0666); // strip execute flags
275 // better also set default umask because recursive mkdir() does not apply permissions recursively otherwise
276 umask(0000);
278 // exact version of currently used yui2 and 3 library
279 $CFG->yui2version = '2.9.0';
280 $CFG->yui3version = '3.9.1';
283 // special support for highly optimised scripts that do not need libraries and DB connection
284 if (defined('ABORT_AFTER_CONFIG')) {
285 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
286 // hide debugging if not enabled in config.php - we do not want to disclose sensitive info
287 if (isset($CFG->debug)) {
288 error_reporting($CFG->debug);
289 } else {
290 error_reporting(0);
292 if (NO_DEBUG_DISPLAY) {
293 // Some parts of Moodle cannot display errors and debug at all.
294 ini_set('display_errors', '0');
295 ini_set('log_errors', '1');
296 } else if (empty($CFG->debugdisplay)) {
297 ini_set('display_errors', '0');
298 ini_set('log_errors', '1');
299 } else {
300 ini_set('display_errors', '1');
302 require_once("$CFG->dirroot/lib/configonlylib.php");
303 return;
307 /** Used by library scripts to check they are being called by Moodle */
308 if (!defined('MOODLE_INTERNAL')) { // necessary because cli installer has to define it earlier
309 define('MOODLE_INTERNAL', true);
312 // Early profiling start, based exclusively on config.php $CFG settings
313 if (!empty($CFG->earlyprofilingenabled)) {
314 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
315 if (profiling_start()) {
316 register_shutdown_function('profiling_stop');
321 * Database connection. Used for all access to the database.
322 * @global moodle_database $DB
323 * @name $DB
325 global $DB;
328 * Moodle's wrapper round PHP's $_SESSION.
330 * @global object $SESSION
331 * @name $SESSION
333 global $SESSION;
336 * Holds the user table record for the current user. Will be the 'guest'
337 * user record for people who are not logged in.
339 * $USER is stored in the session.
341 * Items found in the user record:
342 * - $USER->email - The user's email address.
343 * - $USER->id - The unique integer identified of this user in the 'user' table.
344 * - $USER->email - The user's email address.
345 * - $USER->firstname - The user's first name.
346 * - $USER->lastname - The user's last name.
347 * - $USER->username - The user's login username.
348 * - $USER->secret - The user's ?.
349 * - $USER->lang - The user's language choice.
351 * @global object $USER
352 * @name $USER
354 global $USER;
357 * Frontpage course record
359 global $SITE;
362 * A central store of information about the current page we are
363 * generating in response to the user's request.
365 * @global moodle_page $PAGE
366 * @name $PAGE
368 global $PAGE;
371 * The current course. An alias for $PAGE->course.
372 * @global object $COURSE
373 * @name $COURSE
375 global $COURSE;
378 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
379 * it to generate HTML for output.
381 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
382 * for the magic that does that. After $OUTPUT has been initialised, any attempt
383 * to change something that affects the current theme ($PAGE->course, logged in use,
384 * httpsrequried ... will result in an exception.)
386 * Please note the $OUTPUT is replacing the old global $THEME object.
388 * @global object $OUTPUT
389 * @name $OUTPUT
391 global $OUTPUT;
394 * Full script path including all params, slash arguments, scheme and host.
396 * Note: Do NOT use for getting of current page URL or detection of https,
397 * instead use $PAGE->url or strpos($CFG->httpswwwroot, 'https:') === 0
399 * @global string $FULLME
400 * @name $FULLME
402 global $FULLME;
405 * Script path including query string and slash arguments without host.
406 * @global string $ME
407 * @name $ME
409 global $ME;
412 * $FULLME without slasharguments and query string.
413 * @global string $FULLSCRIPT
414 * @name $FULLSCRIPT
416 global $FULLSCRIPT;
419 * Relative moodle script path '/course/view.php'
420 * @global string $SCRIPT
421 * @name $SCRIPT
423 global $SCRIPT;
425 // Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides
426 $CFG->config_php_settings = (array)$CFG;
427 // Forced plugin settings override values from config_plugins table
428 unset($CFG->config_php_settings['forced_plugin_settings']);
429 if (!isset($CFG->forced_plugin_settings)) {
430 $CFG->forced_plugin_settings = array();
432 // Set httpswwwroot default value (this variable will replace $CFG->wwwroot
433 // inside some URLs used in HTTPSPAGEREQUIRED pages.
434 $CFG->httpswwwroot = $CFG->wwwroot;
436 require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
438 if (NO_OUTPUT_BUFFERING) {
439 // we have to call this always before starting session because it discards headers!
440 disable_output_buffering();
443 // Increase memory limits if possible
444 raise_memory_limit(MEMORY_STANDARD);
446 // Time to start counting
447 init_performance_info();
449 // Put $OUTPUT in place, so errors can be displayed.
450 $OUTPUT = new bootstrap_renderer();
452 // set handler for uncaught exceptions - equivalent to print_error() call
453 if (!PHPUNIT_TEST or PHPUNIT_UTIL) {
454 set_exception_handler('default_exception_handler');
455 set_error_handler('default_error_handler', E_ALL | E_STRICT);
458 // Acceptance tests needs special output to capture the errors.
459 if (!empty($CFG->originaldataroot) && !defined('BEHAT_RUNNING')) {
460 require_once(__DIR__ . '/behat/lib.php');
461 set_error_handler('behat_error_handler', E_ALL | E_STRICT);
464 // If there are any errors in the standard libraries we want to know!
465 error_reporting(E_ALL | E_STRICT);
467 // Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
468 // http://www.google.com/webmasters/faq.html#prefetchblock
469 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
470 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
471 echo('Prefetch request forbidden.');
472 exit(1);
475 if (!isset($CFG->prefix)) { // Just in case it isn't defined in config.php
476 $CFG->prefix = '';
479 // location of all languages except core English pack
480 if (!isset($CFG->langotherroot)) {
481 $CFG->langotherroot = $CFG->dataroot.'/lang';
484 // location of local lang pack customisations (dirs with _local suffix)
485 if (!isset($CFG->langlocalroot)) {
486 $CFG->langlocalroot = $CFG->dataroot.'/lang';
489 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
490 //the problem is that we need specific version of quickforms and hacked excel files :-(
491 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
492 //point zend include path to moodles lib/zend so that includes and requires will search there for files before anywhere else
493 //please note zend library is supposed to be used only from web service protocol classes, it may be removed in future
494 ini_set('include_path', $CFG->libdir.'/zend' . PATH_SEPARATOR . ini_get('include_path'));
496 // Load up standard libraries
497 require_once($CFG->libdir .'/textlib.class.php'); // Functions to handle multibyte strings
498 require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output
499 require_once($CFG->libdir .'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
500 require_once($CFG->libdir .'/weblib.php'); // Functions relating to HTTP and content
501 require_once($CFG->libdir .'/outputlib.php'); // Functions for generating output
502 require_once($CFG->libdir .'/navigationlib.php'); // Class for generating Navigation structure
503 require_once($CFG->libdir .'/dmllib.php'); // Database access
504 require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
505 require_once($CFG->libdir .'/accesslib.php'); // Access control functions
506 require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
507 require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
508 require_once($CFG->libdir .'/enrollib.php'); // Enrolment related functions
509 require_once($CFG->libdir .'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
510 require_once($CFG->libdir .'/blocklib.php'); // Library for controlling blocks
511 require_once($CFG->libdir .'/eventslib.php'); // Events functions
512 require_once($CFG->libdir .'/grouplib.php'); // Groups functions
513 require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie related stuff
514 require_once($CFG->libdir .'/editorlib.php'); // All text editor related functions and classes
515 require_once($CFG->libdir .'/messagelib.php'); // Messagelib functions
516 require_once($CFG->libdir .'/modinfolib.php'); // Cached information on course-module instances
517 require_once($CFG->dirroot.'/cache/lib.php'); // Cache API
519 // make sure PHP is not severly misconfigured
520 setup_validate_php_configuration();
522 // Connect to the database
523 setup_DB();
525 if (PHPUNIT_TEST and !PHPUNIT_UTIL) {
526 // make sure tests do not run in parallel
527 test_lock::acquire('phpunit');
528 $dbhash = null;
529 try {
530 if ($dbhash = $DB->get_field('config', 'value', array('name'=>'phpunittest'))) {
531 // reset DB tables
532 phpunit_util::reset_database();
534 } catch (Exception $e) {
535 if ($dbhash) {
536 // we ned to reinit if reset fails
537 $DB->set_field('config', 'value', 'na', array('name'=>'phpunittest'));
540 unset($dbhash);
543 // Disable errors for now - needed for installation when debug enabled in config.php
544 if (isset($CFG->debug)) {
545 $originalconfigdebug = $CFG->debug;
546 unset($CFG->debug);
547 } else {
548 $originalconfigdebug = null;
551 // Load up any configuration from the config table
553 if (PHPUNIT_TEST) {
554 phpunit_util::initialise_cfg();
555 } else {
556 initialise_cfg();
559 // Verify upgrade is not running unless we are in a script that needs to execute in any case
560 if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
561 if ($CFG->upgraderunning < time()) {
562 unset_config('upgraderunning');
563 } else {
564 print_error('upgraderunning');
568 // Turn on SQL logging if required
569 if (!empty($CFG->logsql)) {
570 $DB->set_logging(true);
573 // Prevent warnings from roles when upgrading with debug on
574 if (isset($CFG->debug)) {
575 $originaldatabasedebug = $CFG->debug;
576 unset($CFG->debug);
577 } else {
578 $originaldatabasedebug = null;
581 // enable circular reference collector in PHP 5.3,
582 // it helps a lot when using large complex OOP structures such as in amos or gradebook
583 if (function_exists('gc_enable')) {
584 gc_enable();
587 // Register default shutdown tasks - such as Apache memory release helper, perf logging, etc.
588 if (function_exists('register_shutdown_function')) {
589 register_shutdown_function('moodle_request_shutdown');
592 // Set error reporting back to normal
593 if ($originaldatabasedebug === null) {
594 $CFG->debug = DEBUG_MINIMAL;
595 } else {
596 $CFG->debug = $originaldatabasedebug;
598 if ($originalconfigdebug !== null) {
599 $CFG->debug = $originalconfigdebug;
601 unset($originalconfigdebug);
602 unset($originaldatabasedebug);
603 error_reporting($CFG->debug);
605 // find out if PHP configured to display warnings,
606 // this is a security problem because some moodle scripts may
607 // disclose sensitive information
608 if (ini_get_bool('display_errors')) {
609 define('WARN_DISPLAY_ERRORS_ENABLED', true);
611 // If we want to display Moodle errors, then try and set PHP errors to match
612 if (!isset($CFG->debugdisplay)) {
613 // keep it "as is" during installation
614 } else if (NO_DEBUG_DISPLAY) {
615 // some parts of Moodle cannot display errors and debug at all.
616 ini_set('display_errors', '0');
617 ini_set('log_errors', '1');
618 } else if (empty($CFG->debugdisplay)) {
619 ini_set('display_errors', '0');
620 ini_set('log_errors', '1');
621 } else {
622 // This is very problematic in XHTML strict mode!
623 ini_set('display_errors', '1');
626 // detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
627 if (!empty($CFG->version) and $CFG->version < 2007101509) {
628 print_error('upgraderequires19', 'error');
629 die;
632 // Calculate and set $CFG->ostype to be used everywhere. Possible values are:
633 // - WINDOWS: for any Windows flavour.
634 // - UNIX: for the rest
635 // Also, $CFG->os can continue being used if more specialization is required
636 if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
637 $CFG->ostype = 'WINDOWS';
638 } else {
639 $CFG->ostype = 'UNIX';
641 $CFG->os = PHP_OS;
643 // Configure ampersands in URLs
644 ini_set('arg_separator.output', '&amp;');
646 // Work around for a PHP bug see MDL-11237
647 ini_set('pcre.backtrack_limit', 20971520); // 20 MB
649 // Location of standard files
650 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
651 $CFG->moddata = 'moddata';
653 // A hack to get around magic_quotes_gpc being turned on
654 // It is strongly recommended to disable "magic_quotes_gpc"!
655 if (ini_get_bool('magic_quotes_gpc')) {
656 function stripslashes_deep($value) {
657 $value = is_array($value) ?
658 array_map('stripslashes_deep', $value) :
659 stripslashes($value);
660 return $value;
662 $_POST = array_map('stripslashes_deep', $_POST);
663 $_GET = array_map('stripslashes_deep', $_GET);
664 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
665 $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
666 if (!empty($_SERVER['REQUEST_URI'])) {
667 $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']);
669 if (!empty($_SERVER['QUERY_STRING'])) {
670 $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']);
672 if (!empty($_SERVER['HTTP_REFERER'])) {
673 $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']);
675 if (!empty($_SERVER['PATH_INFO'])) {
676 $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']);
678 if (!empty($_SERVER['PHP_SELF'])) {
679 $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']);
681 if (!empty($_SERVER['PATH_TRANSLATED'])) {
682 $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']);
686 // neutralise nasty chars in PHP_SELF
687 if (isset($_SERVER['PHP_SELF'])) {
688 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
689 if ($phppos !== false) {
690 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
692 unset($phppos);
695 // initialise ME's - this must be done BEFORE starting of session!
696 initialise_fullme();
698 // define SYSCONTEXTID in config.php if you want to save some queries,
699 // after install it must match the system context record id.
700 if (!defined('SYSCONTEXTID')) {
701 get_system_context();
704 // Defining the site - aka frontpage course
705 try {
706 $SITE = get_site();
707 } catch (dml_exception $e) {
708 $SITE = null;
709 if (empty($CFG->version)) {
710 $SITE = new stdClass();
711 $SITE->id = 1;
712 $SITE->shortname = null;
713 } else {
714 throw $e;
717 // And the 'default' course - this will usually get reset later in require_login() etc.
718 $COURSE = clone($SITE);
719 /** @deprecated Id of the frontpage course, use $SITE->id instead */
720 define('SITEID', $SITE->id);
722 // init session prevention flag - this is defined on pages that do not want session
723 if (CLI_SCRIPT) {
724 // no sessions in CLI scripts possible
725 define('NO_MOODLE_COOKIES', true);
727 } else if (!defined('NO_MOODLE_COOKIES')) {
728 if (empty($CFG->version) or $CFG->version < 2009011900) {
729 // no session before sessions table gets created
730 define('NO_MOODLE_COOKIES', true);
731 } else if (CLI_SCRIPT) {
732 // CLI scripts can not have session
733 define('NO_MOODLE_COOKIES', true);
734 } else {
735 define('NO_MOODLE_COOKIES', false);
739 // start session and prepare global $SESSION, $USER
740 session_get_instance();
741 $SESSION = &$_SESSION['SESSION'];
742 $USER = &$_SESSION['USER'];
744 // Late profiling, only happening if early one wasn't started
745 if (!empty($CFG->profilingenabled)) {
746 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
747 if (profiling_start()) {
748 register_shutdown_function('profiling_stop');
752 // Process theme change in the URL.
753 if (!empty($CFG->allowthemechangeonurl) and !empty($_GET['theme'])) {
754 // we have to use _GET directly because we do not want this to interfere with _POST
755 $urlthemename = optional_param('theme', '', PARAM_PLUGIN);
756 try {
757 $themeconfig = theme_config::load($urlthemename);
758 // Makes sure the theme can be loaded without errors.
759 if ($themeconfig->name === $urlthemename) {
760 $SESSION->theme = $urlthemename;
761 } else {
762 unset($SESSION->theme);
764 unset($themeconfig);
765 unset($urlthemename);
766 } catch (Exception $e) {
767 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
770 unset($urlthemename);
772 // Ensure a valid theme is set.
773 if (!isset($CFG->theme)) {
774 $CFG->theme = 'standardwhite';
777 // Set language/locale of printed times. If user has chosen a language that
778 // that is different from the site language, then use the locale specified
779 // in the language file. Otherwise, if the admin hasn't specified a locale
780 // then use the one from the default language. Otherwise (and this is the
781 // majority of cases), use the stored locale specified by admin.
782 // note: do not accept lang parameter from POST
783 if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
784 if (get_string_manager()->translation_exists($lang, false)) {
785 $SESSION->lang = $lang;
788 unset($lang);
790 setup_lang_from_browser();
792 if (empty($CFG->lang)) {
793 if (empty($SESSION->lang)) {
794 $CFG->lang = 'en';
795 } else {
796 $CFG->lang = $SESSION->lang;
800 // Set the default site locale, a lot of the stuff may depend on this
801 // it is definitely too late to call this first in require_login()!
802 moodle_setlocale();
804 // Create the $PAGE global - this marks the PAGE and OUTPUT fully initialised, this MUST be done at the end of setup!
805 if (!empty($CFG->moodlepageclass)) {
806 if (!empty($CFG->moodlepageclassfile)) {
807 require_once($CFG->moodlepageclassfile);
809 $classname = $CFG->moodlepageclass;
810 } else {
811 $classname = 'moodle_page';
813 $PAGE = new $classname();
814 unset($classname);
817 if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
818 if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') { // Temporary measure to help with XHTML validation
819 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
820 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
821 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
822 if ($user = get_complete_user_data("username", "w3cvalidator")) {
823 $user->ignoresesskey = true;
824 } else {
825 $user = guest_user();
827 session_set_user($user);
833 // Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
834 // LogFormat to get the current logged in username in moodle.
835 if ($USER && function_exists('apache_note')
836 && !empty($CFG->apacheloguser) && isset($USER->username)) {
837 $apachelog_userid = $USER->id;
838 $apachelog_username = clean_filename($USER->username);
839 $apachelog_name = '';
840 if (isset($USER->firstname)) {
841 // We can assume both will be set
842 // - even if to empty.
843 $apachelog_name = clean_filename($USER->firstname . " " .
844 $USER->lastname);
846 if (session_is_loggedinas()) {
847 $realuser = session_get_realuser();
848 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
849 $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
850 $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
852 switch ($CFG->apacheloguser) {
853 case 3:
854 $logname = $apachelog_username;
855 break;
856 case 2:
857 $logname = $apachelog_name;
858 break;
859 case 1:
860 default:
861 $logname = $apachelog_userid;
862 break;
864 apache_note('MOODLEUSER', $logname);
867 // Use a custom script replacement if one exists
868 if (!empty($CFG->customscripts)) {
869 if (($customscript = custom_script_path()) !== false) {
870 require ($customscript);
874 if (PHPUNIT_TEST) {
875 // no ip blocking, these are CLI only
876 } else if (CLI_SCRIPT and !defined('WEB_CRON_EMULATED_CLI')) {
877 // no ip blocking
878 } else if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
879 // in this case, ip in allowed list will be performed first
880 // for example, client IP is 192.168.1.1
881 // 192.168 subnet is an entry in allowed list
882 // 192.168.1.1 is banned in blocked list
883 // This ip will be banned finally
884 if (!empty($CFG->allowedip)) {
885 if (!remoteip_in_list($CFG->allowedip)) {
886 die(get_string('ipblocked', 'admin'));
889 // need further check, client ip may a part of
890 // allowed subnet, but a IP address are listed
891 // in blocked list.
892 if (!empty($CFG->blockedip)) {
893 if (remoteip_in_list($CFG->blockedip)) {
894 die(get_string('ipblocked', 'admin'));
898 } else {
899 // in this case, IPs in blocked list will be performed first
900 // for example, client IP is 192.168.1.1
901 // 192.168 subnet is an entry in blocked list
902 // 192.168.1.1 is allowed in allowed list
903 // This ip will be allowed finally
904 if (!empty($CFG->blockedip)) {
905 if (remoteip_in_list($CFG->blockedip)) {
906 // if the allowed ip list is not empty
907 // IPs are not included in the allowed list will be
908 // blocked too
909 if (!empty($CFG->allowedip)) {
910 if (!remoteip_in_list($CFG->allowedip)) {
911 die(get_string('ipblocked', 'admin'));
913 } else {
914 die(get_string('ipblocked', 'admin'));
918 // if blocked list is null
919 // allowed list should be tested
920 if(!empty($CFG->allowedip)) {
921 if (!remoteip_in_list($CFG->allowedip)) {
922 die(get_string('ipblocked', 'admin'));
928 // // try to detect IE6 and prevent gzip because it is extremely buggy browser
929 if (!empty($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false) {
930 @ini_set('zlib.output_compression', 'Off');
931 if (function_exists('apache_setenv')) {
932 @apache_setenv('no-gzip', 1);
936 // Switch to CLI maintenance mode if required, we need to do it here after all the settings are initialised.
937 if (isset($CFG->maintenance_later) and $CFG->maintenance_later <= time()) {
938 if (!file_exists("$CFG->dataroot/climaintenance.html")) {
939 require_once("$CFG->libdir/adminlib.php");
940 enable_cli_maintenance_mode();
942 unset_config('maintenance_later');
943 if (AJAX_SCRIPT) {
944 die;
945 } else if (!CLI_SCRIPT) {
946 redirect(new moodle_url('/'));
950 // note: we can not block non utf-8 installations here, because empty mysql database
951 // might be converted to utf-8 in admin/index.php during installation
955 // this is a funny trick to make Eclipse believe that $OUTPUT and other globals
956 // contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
957 if (false) {
958 $DB = new moodle_database();
959 $OUTPUT = new core_renderer(null, null);
960 $PAGE = new moodle_page();