Merge branch 'MDL-39790_master' of git://github.com/totara/openbadges into MOODLE_25_...
[moodle.git] / lib / setup.php
blob0b9cbd2f40a1d7600488736ac9a1bdf0fbc9fa43
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 (!defined('BEHAT_SITE_RUNNING') && !empty($CFG->behat_dataroot) &&
111 !empty($CFG->behat_prefix) && file_exists($CFG->behat_dataroot)) {
113 $CFG->behat_dataroot = realpath($CFG->behat_dataroot);
115 $switchcompletely = !empty($CFG->behat_switchcompletely) && php_sapi_name() !== 'cli';
116 $builtinserver = php_sapi_name() === 'cli-server';
117 $behatrunning = defined('BEHAT_TEST');
118 $testenvironmentrequested = $switchcompletely || $builtinserver || $behatrunning;
120 // Only switch to test environment if it has been enabled.
121 $testenvironmentenabled = file_exists($CFG->behat_dataroot . '/behat/test_environment_enabled.txt');
123 if ($testenvironmentenabled && $testenvironmentrequested) {
125 // Constant used to inform that the behat test site is being used,
126 // this includes all the processes executed by the behat CLI command like
127 // the site reset, the steps executed by the browser drivers when simulating
128 // a user session and a real session when browsing manually to $CFG->behat_wwwroot
129 // like the browser driver does automatically.
130 // Different from BEHAT_TEST as only this last one can perform CLI
131 // actions like reset the site or use data generators.
132 define('BEHAT_SITE_RUNNING', true);
134 $CFG->wwwroot = $CFG->behat_wwwroot;
135 $CFG->passwordsaltmain = 'moodle';
136 $CFG->prefix = $CFG->behat_prefix;
137 $CFG->dataroot = $CFG->behat_dataroot;
141 // Define admin directory
142 if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
143 $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
146 // Set up some paths.
147 $CFG->libdir = $CFG->dirroot .'/lib';
149 // Allow overriding of tempdir but be backwards compatible
150 if (!isset($CFG->tempdir)) {
151 $CFG->tempdir = "$CFG->dataroot/temp";
154 // Allow overriding of cachedir but be backwards compatible
155 if (!isset($CFG->cachedir)) {
156 $CFG->cachedir = "$CFG->dataroot/cache";
159 // The current directory in PHP version 4.3.0 and above isn't necessarily the
160 // directory of the script when run from the command line. The require_once()
161 // would fail, so we'll have to chdir()
162 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
163 // do it only once - skip the second time when continuing after prevous abort
164 if (!defined('ABORT_AFTER_CONFIG') and !defined('ABORT_AFTER_CONFIG_CANCEL')) {
165 chdir(dirname($_SERVER['argv'][0]));
169 // sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
170 ini_set('precision', 14); // needed for upgrades and gradebook
172 // Scripts may request no debug and error messages in output
173 // please note it must be defined before including the config.php script
174 // and in some cases you also need to set custom default exception handler
175 if (!defined('NO_DEBUG_DISPLAY')) {
176 define('NO_DEBUG_DISPLAY', false);
179 // Some scripts such as upgrade may want to prevent output buffering
180 if (!defined('NO_OUTPUT_BUFFERING')) {
181 define('NO_OUTPUT_BUFFERING', false);
184 // PHPUnit tests need custom init
185 if (!defined('PHPUNIT_TEST')) {
186 define('PHPUNIT_TEST', false);
189 // When set to true MUC (Moodle caching) will be disabled as much as possible.
190 // A special cache factory will be used to handle this situation and will use special "disabled" equivalents objects.
191 // This ensure we don't attempt to read or create the config file, don't use stores, don't provide persistence or
192 // storage of any kind.
193 if (!defined('CACHE_DISABLE_ALL')) {
194 define('CACHE_DISABLE_ALL', false);
197 // When set to true MUC (Moodle caching) will not use any of the defined or default stores.
198 // The Cache API will continue to function however this will force the use of the cachestore_dummy so all requests
199 // will be interacting with a static property and will never go to the proper cache stores.
200 // Useful if you need to avoid the stores for one reason or another.
201 if (!defined('CACHE_DISABLE_STORES')) {
202 define('CACHE_DISABLE_STORES', false);
205 // Servers should define a default timezone in php.ini, but if they don't then make sure something is defined.
206 // This is a quick hack. Ideally we should ask the admin for a value. See MDL-22625 for more on this.
207 if (function_exists('date_default_timezone_set') and function_exists('date_default_timezone_get')) {
208 $olddebug = error_reporting(0);
209 date_default_timezone_set(date_default_timezone_get());
210 error_reporting($olddebug);
211 unset($olddebug);
214 // Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
215 // In your new CLI scripts just add "define('CLI_SCRIPT', true);" before requiring config.php.
216 // Please note that one script can not be accessed from both CLI and web interface.
217 if (!defined('CLI_SCRIPT')) {
218 define('CLI_SCRIPT', false);
220 if (defined('WEB_CRON_EMULATED_CLI')) {
221 if (!isset($_SERVER['REMOTE_ADDR'])) {
222 echo('Web cron can not be executed as CLI script any more, please use admin/cli/cron.php instead'."\n");
223 exit(1);
225 } else if (isset($_SERVER['REMOTE_ADDR'])) {
226 if (CLI_SCRIPT) {
227 echo('Command line scripts can not be executed from the web interface');
228 exit(1);
230 } else {
231 if (!CLI_SCRIPT) {
232 echo('Command line scripts must define CLI_SCRIPT before requiring config.php'."\n");
233 exit(1);
237 // Detect CLI maintenance mode - this is useful when you need to mess with database, such as during upgrades
238 if (file_exists("$CFG->dataroot/climaintenance.html")) {
239 if (!CLI_SCRIPT) {
240 header('Content-type: text/html; charset=utf-8');
241 header('X-UA-Compatible: IE=edge');
242 /// Headers to make it not cacheable and json
243 header('Cache-Control: no-store, no-cache, must-revalidate');
244 header('Cache-Control: post-check=0, pre-check=0', false);
245 header('Pragma: no-cache');
246 header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
247 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
248 header('Accept-Ranges: none');
249 readfile("$CFG->dataroot/climaintenance.html");
250 die;
251 } else {
252 if (!defined('CLI_MAINTENANCE')) {
253 define('CLI_MAINTENANCE', true);
256 } else {
257 if (!defined('CLI_MAINTENANCE')) {
258 define('CLI_MAINTENANCE', false);
262 if (CLI_SCRIPT) {
263 // sometimes people use different PHP binary for web and CLI, make 100% sure they have the supported PHP version
264 if (version_compare(phpversion(), '5.3.3') < 0) {
265 $phpversion = phpversion();
266 // do NOT localise - lang strings would not work here and we CAN NOT move it to later place
267 echo "Moodle 2.5 or later requires at least PHP 5.3.3 (currently using version $phpversion).\n";
268 echo "Some servers may have multiple PHP versions installed, are you using the correct executable?\n";
269 exit(1);
273 // Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
274 if (!defined('AJAX_SCRIPT')) {
275 define('AJAX_SCRIPT', false);
278 // File permissions on created directories in the $CFG->dataroot
279 if (empty($CFG->directorypermissions)) {
280 $CFG->directorypermissions = 02777; // Must be octal (that's why it's here)
282 if (empty($CFG->filepermissions)) {
283 $CFG->filepermissions = ($CFG->directorypermissions & 0666); // strip execute flags
285 // better also set default umask because recursive mkdir() does not apply permissions recursively otherwise
286 umask(0000);
288 // exact version of currently used yui2 and 3 library
289 $CFG->yui2version = '2.9.0';
290 $CFG->yui3version = '3.9.1';
293 // special support for highly optimised scripts that do not need libraries and DB connection
294 if (defined('ABORT_AFTER_CONFIG')) {
295 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
296 // hide debugging if not enabled in config.php - we do not want to disclose sensitive info
297 if (isset($CFG->debug)) {
298 error_reporting($CFG->debug);
299 } else {
300 error_reporting(0);
302 if (NO_DEBUG_DISPLAY) {
303 // Some parts of Moodle cannot display errors and debug at all.
304 ini_set('display_errors', '0');
305 ini_set('log_errors', '1');
306 } else if (empty($CFG->debugdisplay)) {
307 ini_set('display_errors', '0');
308 ini_set('log_errors', '1');
309 } else {
310 ini_set('display_errors', '1');
312 require_once("$CFG->dirroot/lib/configonlylib.php");
313 return;
317 /** Used by library scripts to check they are being called by Moodle */
318 if (!defined('MOODLE_INTERNAL')) { // necessary because cli installer has to define it earlier
319 define('MOODLE_INTERNAL', true);
322 // Early profiling start, based exclusively on config.php $CFG settings
323 if (!empty($CFG->earlyprofilingenabled)) {
324 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
325 if (profiling_start()) {
326 register_shutdown_function('profiling_stop');
331 * Database connection. Used for all access to the database.
332 * @global moodle_database $DB
333 * @name $DB
335 global $DB;
338 * Moodle's wrapper round PHP's $_SESSION.
340 * @global object $SESSION
341 * @name $SESSION
343 global $SESSION;
346 * Holds the user table record for the current user. Will be the 'guest'
347 * user record for people who are not logged in.
349 * $USER is stored in the session.
351 * Items found in the user record:
352 * - $USER->email - The user's email address.
353 * - $USER->id - The unique integer identified of this user in the 'user' table.
354 * - $USER->email - The user's email address.
355 * - $USER->firstname - The user's first name.
356 * - $USER->lastname - The user's last name.
357 * - $USER->username - The user's login username.
358 * - $USER->secret - The user's ?.
359 * - $USER->lang - The user's language choice.
361 * @global object $USER
362 * @name $USER
364 global $USER;
367 * Frontpage course record
369 global $SITE;
372 * A central store of information about the current page we are
373 * generating in response to the user's request.
375 * @global moodle_page $PAGE
376 * @name $PAGE
378 global $PAGE;
381 * The current course. An alias for $PAGE->course.
382 * @global object $COURSE
383 * @name $COURSE
385 global $COURSE;
388 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
389 * it to generate HTML for output.
391 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
392 * for the magic that does that. After $OUTPUT has been initialised, any attempt
393 * to change something that affects the current theme ($PAGE->course, logged in use,
394 * httpsrequried ... will result in an exception.)
396 * Please note the $OUTPUT is replacing the old global $THEME object.
398 * @global object $OUTPUT
399 * @name $OUTPUT
401 global $OUTPUT;
404 * Full script path including all params, slash arguments, scheme and host.
406 * Note: Do NOT use for getting of current page URL or detection of https,
407 * instead use $PAGE->url or strpos($CFG->httpswwwroot, 'https:') === 0
409 * @global string $FULLME
410 * @name $FULLME
412 global $FULLME;
415 * Script path including query string and slash arguments without host.
416 * @global string $ME
417 * @name $ME
419 global $ME;
422 * $FULLME without slasharguments and query string.
423 * @global string $FULLSCRIPT
424 * @name $FULLSCRIPT
426 global $FULLSCRIPT;
429 * Relative moodle script path '/course/view.php'
430 * @global string $SCRIPT
431 * @name $SCRIPT
433 global $SCRIPT;
435 // Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides
436 $CFG->config_php_settings = (array)$CFG;
437 // Forced plugin settings override values from config_plugins table
438 unset($CFG->config_php_settings['forced_plugin_settings']);
439 if (!isset($CFG->forced_plugin_settings)) {
440 $CFG->forced_plugin_settings = array();
442 // Set httpswwwroot default value (this variable will replace $CFG->wwwroot
443 // inside some URLs used in HTTPSPAGEREQUIRED pages.
444 $CFG->httpswwwroot = $CFG->wwwroot;
446 require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
448 if (NO_OUTPUT_BUFFERING) {
449 // we have to call this always before starting session because it discards headers!
450 disable_output_buffering();
453 // Increase memory limits if possible
454 raise_memory_limit(MEMORY_STANDARD);
456 // Time to start counting
457 init_performance_info();
459 // Put $OUTPUT in place, so errors can be displayed.
460 $OUTPUT = new bootstrap_renderer();
462 // set handler for uncaught exceptions - equivalent to print_error() call
463 if (!PHPUNIT_TEST or PHPUNIT_UTIL) {
464 set_exception_handler('default_exception_handler');
465 set_error_handler('default_error_handler', E_ALL | E_STRICT);
468 // Acceptance tests needs special output to capture the errors,
469 // but not necessary for behat CLI command.
470 if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST')) {
471 require_once(__DIR__ . '/behat/lib.php');
472 set_error_handler('behat_error_handler', E_ALL | E_STRICT);
475 // If there are any errors in the standard libraries we want to know!
476 error_reporting(E_ALL | E_STRICT);
478 // Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
479 // http://www.google.com/webmasters/faq.html#prefetchblock
480 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
481 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
482 echo('Prefetch request forbidden.');
483 exit(1);
486 if (!isset($CFG->prefix)) { // Just in case it isn't defined in config.php
487 $CFG->prefix = '';
490 // location of all languages except core English pack
491 if (!isset($CFG->langotherroot)) {
492 $CFG->langotherroot = $CFG->dataroot.'/lang';
495 // location of local lang pack customisations (dirs with _local suffix)
496 if (!isset($CFG->langlocalroot)) {
497 $CFG->langlocalroot = $CFG->dataroot.'/lang';
500 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
501 //the problem is that we need specific version of quickforms and hacked excel files :-(
502 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
503 //point zend include path to moodles lib/zend so that includes and requires will search there for files before anywhere else
504 //please note zend library is supposed to be used only from web service protocol classes, it may be removed in future
505 ini_set('include_path', $CFG->libdir.'/zend' . PATH_SEPARATOR . ini_get('include_path'));
507 // Load up standard libraries
508 require_once($CFG->libdir .'/textlib.class.php'); // Functions to handle multibyte strings
509 require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output
510 require_once($CFG->libdir .'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
511 require_once($CFG->libdir .'/weblib.php'); // Functions relating to HTTP and content
512 require_once($CFG->libdir .'/outputlib.php'); // Functions for generating output
513 require_once($CFG->libdir .'/navigationlib.php'); // Class for generating Navigation structure
514 require_once($CFG->libdir .'/dmllib.php'); // Database access
515 require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
516 require_once($CFG->libdir .'/accesslib.php'); // Access control functions
517 require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
518 require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
519 require_once($CFG->libdir .'/enrollib.php'); // Enrolment related functions
520 require_once($CFG->libdir .'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
521 require_once($CFG->libdir .'/blocklib.php'); // Library for controlling blocks
522 require_once($CFG->libdir .'/eventslib.php'); // Events functions
523 require_once($CFG->libdir .'/grouplib.php'); // Groups functions
524 require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie related stuff
525 require_once($CFG->libdir .'/editorlib.php'); // All text editor related functions and classes
526 require_once($CFG->libdir .'/messagelib.php'); // Messagelib functions
527 require_once($CFG->libdir .'/modinfolib.php'); // Cached information on course-module instances
528 require_once($CFG->dirroot.'/cache/lib.php'); // Cache API
530 // make sure PHP is not severly misconfigured
531 setup_validate_php_configuration();
533 // Connect to the database
534 setup_DB();
536 if (PHPUNIT_TEST and !PHPUNIT_UTIL) {
537 // make sure tests do not run in parallel
538 test_lock::acquire('phpunit');
539 $dbhash = null;
540 try {
541 if ($dbhash = $DB->get_field('config', 'value', array('name'=>'phpunittest'))) {
542 // reset DB tables
543 phpunit_util::reset_database();
545 } catch (Exception $e) {
546 if ($dbhash) {
547 // we ned to reinit if reset fails
548 $DB->set_field('config', 'value', 'na', array('name'=>'phpunittest'));
551 unset($dbhash);
554 // Disable errors for now - needed for installation when debug enabled in config.php
555 if (isset($CFG->debug)) {
556 $originalconfigdebug = $CFG->debug;
557 unset($CFG->debug);
558 } else {
559 $originalconfigdebug = null;
562 // Load up any configuration from the config table
564 if (PHPUNIT_TEST) {
565 phpunit_util::initialise_cfg();
566 } else {
567 initialise_cfg();
570 // Verify upgrade is not running unless we are in a script that needs to execute in any case
571 if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
572 if ($CFG->upgraderunning < time()) {
573 unset_config('upgraderunning');
574 } else {
575 print_error('upgraderunning');
579 // Turn on SQL logging if required
580 if (!empty($CFG->logsql)) {
581 $DB->set_logging(true);
584 // Prevent warnings from roles when upgrading with debug on
585 if (isset($CFG->debug)) {
586 $originaldatabasedebug = $CFG->debug;
587 unset($CFG->debug);
588 } else {
589 $originaldatabasedebug = null;
592 // enable circular reference collector in PHP 5.3,
593 // it helps a lot when using large complex OOP structures such as in amos or gradebook
594 if (function_exists('gc_enable')) {
595 gc_enable();
598 // Register default shutdown tasks - such as Apache memory release helper, perf logging, etc.
599 if (function_exists('register_shutdown_function')) {
600 register_shutdown_function('moodle_request_shutdown');
603 // Set error reporting back to normal
604 if ($originaldatabasedebug === null) {
605 $CFG->debug = DEBUG_MINIMAL;
606 } else {
607 $CFG->debug = $originaldatabasedebug;
609 if ($originalconfigdebug !== null) {
610 $CFG->debug = $originalconfigdebug;
612 unset($originalconfigdebug);
613 unset($originaldatabasedebug);
614 error_reporting($CFG->debug);
616 // find out if PHP configured to display warnings,
617 // this is a security problem because some moodle scripts may
618 // disclose sensitive information
619 if (ini_get_bool('display_errors')) {
620 define('WARN_DISPLAY_ERRORS_ENABLED', true);
622 // If we want to display Moodle errors, then try and set PHP errors to match
623 if (!isset($CFG->debugdisplay)) {
624 // keep it "as is" during installation
625 } else if (NO_DEBUG_DISPLAY) {
626 // some parts of Moodle cannot display errors and debug at all.
627 ini_set('display_errors', '0');
628 ini_set('log_errors', '1');
629 } else if (empty($CFG->debugdisplay)) {
630 ini_set('display_errors', '0');
631 ini_set('log_errors', '1');
632 } else {
633 // This is very problematic in XHTML strict mode!
634 ini_set('display_errors', '1');
637 // detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
638 if (!empty($CFG->version) and $CFG->version < 2007101509) {
639 print_error('upgraderequires19', 'error');
640 die;
643 // Calculate and set $CFG->ostype to be used everywhere. Possible values are:
644 // - WINDOWS: for any Windows flavour.
645 // - UNIX: for the rest
646 // Also, $CFG->os can continue being used if more specialization is required
647 if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
648 $CFG->ostype = 'WINDOWS';
649 } else {
650 $CFG->ostype = 'UNIX';
652 $CFG->os = PHP_OS;
654 // Configure ampersands in URLs
655 ini_set('arg_separator.output', '&amp;');
657 // Work around for a PHP bug see MDL-11237
658 ini_set('pcre.backtrack_limit', 20971520); // 20 MB
660 // Location of standard files
661 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
662 $CFG->moddata = 'moddata';
664 // A hack to get around magic_quotes_gpc being turned on
665 // It is strongly recommended to disable "magic_quotes_gpc"!
666 if (ini_get_bool('magic_quotes_gpc')) {
667 function stripslashes_deep($value) {
668 $value = is_array($value) ?
669 array_map('stripslashes_deep', $value) :
670 stripslashes($value);
671 return $value;
673 $_POST = array_map('stripslashes_deep', $_POST);
674 $_GET = array_map('stripslashes_deep', $_GET);
675 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
676 $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
677 if (!empty($_SERVER['REQUEST_URI'])) {
678 $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']);
680 if (!empty($_SERVER['QUERY_STRING'])) {
681 $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']);
683 if (!empty($_SERVER['HTTP_REFERER'])) {
684 $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']);
686 if (!empty($_SERVER['PATH_INFO'])) {
687 $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']);
689 if (!empty($_SERVER['PHP_SELF'])) {
690 $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']);
692 if (!empty($_SERVER['PATH_TRANSLATED'])) {
693 $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']);
697 // neutralise nasty chars in PHP_SELF
698 if (isset($_SERVER['PHP_SELF'])) {
699 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
700 if ($phppos !== false) {
701 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
703 unset($phppos);
706 // initialise ME's - this must be done BEFORE starting of session!
707 initialise_fullme();
709 // define SYSCONTEXTID in config.php if you want to save some queries,
710 // after install it must match the system context record id.
711 if (!defined('SYSCONTEXTID')) {
712 get_system_context();
715 // Defining the site - aka frontpage course
716 try {
717 $SITE = get_site();
718 } catch (dml_exception $e) {
719 $SITE = null;
720 if (empty($CFG->version)) {
721 $SITE = new stdClass();
722 $SITE->id = 1;
723 $SITE->shortname = null;
724 } else {
725 throw $e;
728 // And the 'default' course - this will usually get reset later in require_login() etc.
729 $COURSE = clone($SITE);
730 /** @deprecated Id of the frontpage course, use $SITE->id instead */
731 define('SITEID', $SITE->id);
733 // init session prevention flag - this is defined on pages that do not want session
734 if (CLI_SCRIPT) {
735 // no sessions in CLI scripts possible
736 define('NO_MOODLE_COOKIES', true);
738 } else if (!defined('NO_MOODLE_COOKIES')) {
739 if (empty($CFG->version) or $CFG->version < 2009011900) {
740 // no session before sessions table gets created
741 define('NO_MOODLE_COOKIES', true);
742 } else if (CLI_SCRIPT) {
743 // CLI scripts can not have session
744 define('NO_MOODLE_COOKIES', true);
745 } else {
746 define('NO_MOODLE_COOKIES', false);
750 // start session and prepare global $SESSION, $USER
751 session_get_instance();
752 $SESSION = &$_SESSION['SESSION'];
753 $USER = &$_SESSION['USER'];
755 // Late profiling, only happening if early one wasn't started
756 if (!empty($CFG->profilingenabled)) {
757 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
758 if (profiling_start()) {
759 register_shutdown_function('profiling_stop');
763 // Process theme change in the URL.
764 if (!empty($CFG->allowthemechangeonurl) and !empty($_GET['theme'])) {
765 // we have to use _GET directly because we do not want this to interfere with _POST
766 $urlthemename = optional_param('theme', '', PARAM_PLUGIN);
767 try {
768 $themeconfig = theme_config::load($urlthemename);
769 // Makes sure the theme can be loaded without errors.
770 if ($themeconfig->name === $urlthemename) {
771 $SESSION->theme = $urlthemename;
772 } else {
773 unset($SESSION->theme);
775 unset($themeconfig);
776 unset($urlthemename);
777 } catch (Exception $e) {
778 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
781 unset($urlthemename);
783 // Ensure a valid theme is set.
784 if (!isset($CFG->theme)) {
785 $CFG->theme = 'standardwhite';
788 // Set language/locale of printed times. If user has chosen a language that
789 // that is different from the site language, then use the locale specified
790 // in the language file. Otherwise, if the admin hasn't specified a locale
791 // then use the one from the default language. Otherwise (and this is the
792 // majority of cases), use the stored locale specified by admin.
793 // note: do not accept lang parameter from POST
794 if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
795 if (get_string_manager()->translation_exists($lang, false)) {
796 $SESSION->lang = $lang;
799 unset($lang);
801 setup_lang_from_browser();
803 if (empty($CFG->lang)) {
804 if (empty($SESSION->lang)) {
805 $CFG->lang = 'en';
806 } else {
807 $CFG->lang = $SESSION->lang;
811 // Set the default site locale, a lot of the stuff may depend on this
812 // it is definitely too late to call this first in require_login()!
813 moodle_setlocale();
815 // Create the $PAGE global - this marks the PAGE and OUTPUT fully initialised, this MUST be done at the end of setup!
816 if (!empty($CFG->moodlepageclass)) {
817 if (!empty($CFG->moodlepageclassfile)) {
818 require_once($CFG->moodlepageclassfile);
820 $classname = $CFG->moodlepageclass;
821 } else {
822 $classname = 'moodle_page';
824 $PAGE = new $classname();
825 unset($classname);
828 if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
829 if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') { // Temporary measure to help with XHTML validation
830 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
831 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
832 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
833 if ($user = get_complete_user_data("username", "w3cvalidator")) {
834 $user->ignoresesskey = true;
835 } else {
836 $user = guest_user();
838 session_set_user($user);
844 // Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
845 // LogFormat to get the current logged in username in moodle.
846 if ($USER && function_exists('apache_note')
847 && !empty($CFG->apacheloguser) && isset($USER->username)) {
848 $apachelog_userid = $USER->id;
849 $apachelog_username = clean_filename($USER->username);
850 $apachelog_name = '';
851 if (isset($USER->firstname)) {
852 // We can assume both will be set
853 // - even if to empty.
854 $apachelog_name = clean_filename($USER->firstname . " " .
855 $USER->lastname);
857 if (session_is_loggedinas()) {
858 $realuser = session_get_realuser();
859 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
860 $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
861 $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
863 switch ($CFG->apacheloguser) {
864 case 3:
865 $logname = $apachelog_username;
866 break;
867 case 2:
868 $logname = $apachelog_name;
869 break;
870 case 1:
871 default:
872 $logname = $apachelog_userid;
873 break;
875 apache_note('MOODLEUSER', $logname);
878 // Use a custom script replacement if one exists
879 if (!empty($CFG->customscripts)) {
880 if (($customscript = custom_script_path()) !== false) {
881 require ($customscript);
885 if (PHPUNIT_TEST) {
886 // no ip blocking, these are CLI only
887 } else if (CLI_SCRIPT and !defined('WEB_CRON_EMULATED_CLI')) {
888 // no ip blocking
889 } else if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
890 // in this case, ip in allowed list will be performed first
891 // for example, client IP is 192.168.1.1
892 // 192.168 subnet is an entry in allowed list
893 // 192.168.1.1 is banned in blocked list
894 // This ip will be banned finally
895 if (!empty($CFG->allowedip)) {
896 if (!remoteip_in_list($CFG->allowedip)) {
897 die(get_string('ipblocked', 'admin'));
900 // need further check, client ip may a part of
901 // allowed subnet, but a IP address are listed
902 // in blocked list.
903 if (!empty($CFG->blockedip)) {
904 if (remoteip_in_list($CFG->blockedip)) {
905 die(get_string('ipblocked', 'admin'));
909 } else {
910 // in this case, IPs in blocked list will be performed first
911 // for example, client IP is 192.168.1.1
912 // 192.168 subnet is an entry in blocked list
913 // 192.168.1.1 is allowed in allowed list
914 // This ip will be allowed finally
915 if (!empty($CFG->blockedip)) {
916 if (remoteip_in_list($CFG->blockedip)) {
917 // if the allowed ip list is not empty
918 // IPs are not included in the allowed list will be
919 // blocked too
920 if (!empty($CFG->allowedip)) {
921 if (!remoteip_in_list($CFG->allowedip)) {
922 die(get_string('ipblocked', 'admin'));
924 } else {
925 die(get_string('ipblocked', 'admin'));
929 // if blocked list is null
930 // allowed list should be tested
931 if(!empty($CFG->allowedip)) {
932 if (!remoteip_in_list($CFG->allowedip)) {
933 die(get_string('ipblocked', 'admin'));
939 // // try to detect IE6 and prevent gzip because it is extremely buggy browser
940 if (!empty($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false) {
941 @ini_set('zlib.output_compression', 'Off');
942 if (function_exists('apache_setenv')) {
943 @apache_setenv('no-gzip', 1);
947 // Switch to CLI maintenance mode if required, we need to do it here after all the settings are initialised.
948 if (isset($CFG->maintenance_later) and $CFG->maintenance_later <= time()) {
949 if (!file_exists("$CFG->dataroot/climaintenance.html")) {
950 require_once("$CFG->libdir/adminlib.php");
951 enable_cli_maintenance_mode();
953 unset_config('maintenance_later');
954 if (AJAX_SCRIPT) {
955 die;
956 } else if (!CLI_SCRIPT) {
957 redirect(new moodle_url('/'));
961 // note: we can not block non utf-8 installations here, because empty mysql database
962 // might be converted to utf-8 in admin/index.php during installation
966 // this is a funny trick to make Eclipse believe that $OUTPUT and other globals
967 // contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
968 if (false) {
969 $DB = new moodle_database();
970 $OUTPUT = new core_renderer(null, null);
971 $PAGE = new moodle_page();