3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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.
26 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
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).
46 global $CFG; // this should be done much earlier in config.php before creating new $CFG instance
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");
53 // this should never happen, maybe somebody is accessing this file directly...
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 // File permissions on created directories in the $CFG->dataroot
63 if (!isset($CFG->directorypermissions)) {
64 $CFG->directorypermissions = 02777; // Must be octal (that's why it's here)
66 if (!isset($CFG->filepermissions)) {
67 $CFG->filepermissions = ($CFG->directorypermissions & 0666); // strip execute flags
69 // Better also set default umask because developers often forget to include directory
70 // permissions in mkdir() and chmod() after creating new files.
71 if (!isset($CFG->umaskpermissions)) {
72 $CFG->umaskpermissions = (($CFG->directorypermissions & 0777) ^ 0777);
74 umask($CFG->umaskpermissions);
76 if (defined('BEHAT_SITE_RUNNING')) {
77 // We already switched to behat test site previously.
79 } else if (!empty($CFG->behat_wwwroot) or !empty($CFG->behat_dataroot) or !empty($CFG->behat_prefix)) {
80 // The behat is configured on this server, we need to find out if this is the behat test
81 // site based on the URL used for access.
82 require_once(__DIR__ . '/../lib/behat/lib.php');
83 if (behat_is_test_site()) {
84 // Checking the integrity of the provided $CFG->behat_* vars and the
85 // selected wwwroot to prevent conflicts with production and phpunit environments.
86 behat_check_config_vars();
88 // Check that the directory does not contains other things.
89 if (!file_exists("$CFG->behat_dataroot/behattestdir.txt")) {
90 if ($dh = opendir($CFG->behat_dataroot)) {
91 while (($file = readdir($dh)) !== false) {
92 if ($file === 'behat' or $file === '.' or $file === '..' or $file === '.DS_Store') {
95 behat_error(BEHAT_EXITCODE_CONFIG, '$CFG->behat_dataroot directory is not empty, ensure this is the directory where you want to install behat test dataroot');
102 if (defined('BEHAT_UTIL')) {
103 // Now we create dataroot directory structure for behat tests.
104 testing_initdataroot($CFG->behat_dataroot, 'behat');
106 behat_error(BEHAT_EXITCODE_INSTALL);
110 if (!defined('BEHAT_UTIL') and !defined('BEHAT_TEST')) {
111 // Somebody tries to access test site directly, tell them if not enabled.
112 if (!file_exists($CFG->behat_dataroot . '/behat/test_environment_enabled.txt')) {
113 behat_error(BEHAT_EXITCODE_CONFIG, 'Behat is configured but not enabled on this test site.');
117 // Constant used to inform that the behat test site is being used,
118 // this includes all the processes executed by the behat CLI command like
119 // the site reset, the steps executed by the browser drivers when simulating
120 // a user session and a real session when browsing manually to $CFG->behat_wwwroot
121 // like the browser driver does automatically.
122 // Different from BEHAT_TEST as only this last one can perform CLI
123 // actions like reset the site or use data generators.
124 define('BEHAT_SITE_RUNNING', true);
126 // Clean extra config.php settings.
127 behat_clean_init_config();
129 // Now we can begin switching $CFG->X for $CFG->behat_X.
130 $CFG->wwwroot = $CFG->behat_wwwroot;
131 $CFG->passwordsaltmain = 'moodle';
132 $CFG->prefix = $CFG->behat_prefix;
133 $CFG->dataroot = $CFG->behat_dataroot;
137 // Normalise dataroot - we do not want any symbolic links, trailing / or any other weirdness there
138 if (!isset($CFG->dataroot)) {
139 if (isset($_SERVER['REMOTE_ADDR'])) {
140 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
142 echo('Fatal error: $CFG->dataroot is not specified in config.php! Exiting.'."\n");
145 $CFG->dataroot = realpath($CFG->dataroot);
146 if ($CFG->dataroot === false) {
147 if (isset($_SERVER['REMOTE_ADDR'])) {
148 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
150 echo('Fatal error: $CFG->dataroot is not configured properly, directory does not exist or is not accessible! Exiting.'."\n");
152 } else if (!is_writable($CFG->dataroot)) {
153 if (isset($_SERVER['REMOTE_ADDR'])) {
154 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
156 echo('Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.'."\n");
160 // wwwroot is mandatory
161 if (!isset($CFG->wwwroot) or $CFG->wwwroot === 'http://example.com/moodle') {
162 if (isset($_SERVER['REMOTE_ADDR'])) {
163 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
165 echo('Fatal error: $CFG->wwwroot is not configured! Exiting.'."\n");
169 // Make sure there is some database table prefix.
170 if (!isset($CFG->prefix)) {
174 // Define admin directory
175 if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
176 $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
179 // Set up some paths.
180 $CFG->libdir = $CFG->dirroot .'/lib';
182 // Allow overriding of tempdir but be backwards compatible
183 if (!isset($CFG->tempdir)) {
184 $CFG->tempdir = "$CFG->dataroot/temp";
187 // Allow overriding of cachedir but be backwards compatible
188 if (!isset($CFG->cachedir)) {
189 $CFG->cachedir = "$CFG->dataroot/cache";
192 // Allow overriding of localcachedir.
193 if (!isset($CFG->localcachedir)) {
194 $CFG->localcachedir = "$CFG->dataroot/localcache";
197 // Location of all languages except core English pack.
198 if (!isset($CFG->langotherroot)) {
199 $CFG->langotherroot = $CFG->dataroot.'/lang';
202 // Location of local lang pack customisations (dirs with _local suffix).
203 if (!isset($CFG->langlocalroot)) {
204 $CFG->langlocalroot = $CFG->dataroot.'/lang';
207 // The current directory in PHP version 4.3.0 and above isn't necessarily the
208 // directory of the script when run from the command line. The require_once()
209 // would fail, so we'll have to chdir()
210 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
211 // do it only once - skip the second time when continuing after prevous abort
212 if (!defined('ABORT_AFTER_CONFIG') and !defined('ABORT_AFTER_CONFIG_CANCEL')) {
213 chdir(dirname($_SERVER['argv'][0]));
217 // sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
218 ini_set('precision', 14); // needed for upgrades and gradebook
219 ini_set('serialize_precision', 17); // Make float serialization consistent on all systems.
221 // Scripts may request no debug and error messages in output
222 // please note it must be defined before including the config.php script
223 // and in some cases you also need to set custom default exception handler
224 if (!defined('NO_DEBUG_DISPLAY')) {
225 if (defined('AJAX_SCRIPT') and AJAX_SCRIPT) {
226 // Moodle AJAX scripts are expected to return json data, any PHP notices or errors break it badly,
227 // developers simply must learn to watch error log.
228 define('NO_DEBUG_DISPLAY', true);
230 define('NO_DEBUG_DISPLAY', false);
234 // Some scripts such as upgrade may want to prevent output buffering
235 if (!defined('NO_OUTPUT_BUFFERING')) {
236 define('NO_OUTPUT_BUFFERING', false);
239 // PHPUnit tests need custom init
240 if (!defined('PHPUNIT_TEST')) {
241 define('PHPUNIT_TEST', false);
244 // Performance tests needs to always display performance info, even in redirections.
245 if (!defined('MDL_PERF_TEST')) {
246 define('MDL_PERF_TEST', false);
248 // We force the ones we need.
249 if (!defined('MDL_PERF')) {
250 define('MDL_PERF', true);
252 if (!defined('MDL_PERFDB')) {
253 define('MDL_PERFDB', true);
255 if (!defined('MDL_PERFTOFOOT')) {
256 define('MDL_PERFTOFOOT', true);
260 // When set to true MUC (Moodle caching) will be disabled as much as possible.
261 // A special cache factory will be used to handle this situation and will use special "disabled" equivalents objects.
262 // This ensure we don't attempt to read or create the config file, don't use stores, don't provide persistence or
263 // storage of any kind.
264 if (!defined('CACHE_DISABLE_ALL')) {
265 define('CACHE_DISABLE_ALL', false);
268 // When set to true MUC (Moodle caching) will not use any of the defined or default stores.
269 // The Cache API will continue to function however this will force the use of the cachestore_dummy so all requests
270 // will be interacting with a static property and will never go to the proper cache stores.
271 // Useful if you need to avoid the stores for one reason or another.
272 if (!defined('CACHE_DISABLE_STORES')) {
273 define('CACHE_DISABLE_STORES', false);
276 // Servers should define a default timezone in php.ini, but if they don't then make sure something is defined.
277 // This is a quick hack. Ideally we should ask the admin for a value. See MDL-22625 for more on this.
278 if (function_exists('date_default_timezone_set') and function_exists('date_default_timezone_get')) {
279 $olddebug = error_reporting(0);
280 date_default_timezone_set(date_default_timezone_get());
281 error_reporting($olddebug);
285 // Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
286 // In your new CLI scripts just add "define('CLI_SCRIPT', true);" before requiring config.php.
287 // Please note that one script can not be accessed from both CLI and web interface.
288 if (!defined('CLI_SCRIPT')) {
289 define('CLI_SCRIPT', false);
291 if (defined('WEB_CRON_EMULATED_CLI')) {
292 if (!isset($_SERVER['REMOTE_ADDR'])) {
293 echo('Web cron can not be executed as CLI script any more, please use admin/cli/cron.php instead'."\n");
296 } else if (isset($_SERVER['REMOTE_ADDR'])) {
298 echo('Command line scripts can not be executed from the web interface');
303 echo('Command line scripts must define CLI_SCRIPT before requiring config.php'."\n");
308 // Detect CLI maintenance mode - this is useful when you need to mess with database, such as during upgrades
309 if (file_exists("$CFG->dataroot/climaintenance.html")) {
311 header('Content-type: text/html; charset=utf-8');
312 header('X-UA-Compatible: IE=edge');
313 /// Headers to make it not cacheable and json
314 header('Cache-Control: no-store, no-cache, must-revalidate');
315 header('Cache-Control: post-check=0, pre-check=0', false);
316 header('Pragma: no-cache');
317 header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
318 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
319 header('Accept-Ranges: none');
320 readfile("$CFG->dataroot/climaintenance.html");
323 if (!defined('CLI_MAINTENANCE')) {
324 define('CLI_MAINTENANCE', true);
328 if (!defined('CLI_MAINTENANCE')) {
329 define('CLI_MAINTENANCE', false);
334 // sometimes people use different PHP binary for web and CLI, make 100% sure they have the supported PHP version
335 if (version_compare(phpversion(), '5.4.4') < 0) {
336 $phpversion = phpversion();
337 // do NOT localise - lang strings would not work here and we CAN NOT move it to later place
338 echo "Moodle 2.7 or later requires at least PHP 5.4.4 (currently using version $phpversion).\n";
339 echo "Some servers may have multiple PHP versions installed, are you using the correct executable?\n";
344 // Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
345 if (!defined('AJAX_SCRIPT')) {
346 define('AJAX_SCRIPT', false);
349 // Exact version of currently used yui2 and 3 library.
350 $CFG->yui2version = '2.9.0';
351 $CFG->yui3version = '3.13.0';
353 // Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides.
354 if (!isset($CFG->config_php_settings)) {
355 $CFG->config_php_settings = (array)$CFG;
356 // Forced plugin settings override values from config_plugins table.
357 unset($CFG->config_php_settings['forced_plugin_settings']);
358 if (!isset($CFG->forced_plugin_settings)) {
359 $CFG->forced_plugin_settings = array();
363 if (isset($CFG->debug)) {
364 $CFG->debug = (int)$CFG->debug;
368 $CFG->debugdeveloper = (($CFG->debug & (E_ALL | E_STRICT)) === (E_ALL | E_STRICT)); // DEBUG_DEVELOPER is not available yet.
370 if (!defined('MOODLE_INTERNAL')) { // Necessary because cli installer has to define it earlier.
371 /** Used by library scripts to check they are being called by Moodle. */
372 define('MOODLE_INTERNAL', true);
375 // core_component can be used in any scripts, it does not need anything else.
376 require_once($CFG->libdir .'/classes/component.php');
378 // special support for highly optimised scripts that do not need libraries and DB connection
379 if (defined('ABORT_AFTER_CONFIG')) {
380 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
381 // hide debugging if not enabled in config.php - we do not want to disclose sensitive info
382 error_reporting($CFG->debug);
383 if (NO_DEBUG_DISPLAY) {
384 // Some parts of Moodle cannot display errors and debug at all.
385 ini_set('display_errors', '0');
386 ini_set('log_errors', '1');
387 } else if (empty($CFG->debugdisplay)) {
388 ini_set('display_errors', '0');
389 ini_set('log_errors', '1');
391 ini_set('display_errors', '1');
393 require_once("$CFG->dirroot/lib/configonlylib.php");
398 // Early profiling start, based exclusively on config.php $CFG settings
399 if (!empty($CFG->earlyprofilingenabled)) {
400 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
405 * Database connection. Used for all access to the database.
406 * @global moodle_database $DB
412 * Moodle's wrapper round PHP's $_SESSION.
414 * @global object $SESSION
420 * Holds the user table record for the current user. Will be the 'guest'
421 * user record for people who are not logged in.
423 * $USER is stored in the session.
425 * Items found in the user record:
426 * - $USER->email - The user's email address.
427 * - $USER->id - The unique integer identified of this user in the 'user' table.
428 * - $USER->email - The user's email address.
429 * - $USER->firstname - The user's first name.
430 * - $USER->lastname - The user's last name.
431 * - $USER->username - The user's login username.
432 * - $USER->secret - The user's ?.
433 * - $USER->lang - The user's language choice.
435 * @global object $USER
441 * Frontpage course record
446 * A central store of information about the current page we are
447 * generating in response to the user's request.
449 * @global moodle_page $PAGE
455 * The current course. An alias for $PAGE->course.
456 * @global object $COURSE
462 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
463 * it to generate HTML for output.
465 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
466 * for the magic that does that. After $OUTPUT has been initialised, any attempt
467 * to change something that affects the current theme ($PAGE->course, logged in use,
468 * httpsrequried ... will result in an exception.)
470 * Please note the $OUTPUT is replacing the old global $THEME object.
472 * @global object $OUTPUT
478 * Full script path including all params, slash arguments, scheme and host.
480 * Note: Do NOT use for getting of current page URL or detection of https,
481 * instead use $PAGE->url or strpos($CFG->httpswwwroot, 'https:') === 0
483 * @global string $FULLME
489 * Script path including query string and slash arguments without host.
496 * $FULLME without slasharguments and query string.
497 * @global string $FULLSCRIPT
503 * Relative moodle script path '/course/view.php'
504 * @global string $SCRIPT
509 // Set httpswwwroot default value (this variable will replace $CFG->wwwroot
510 // inside some URLs used in HTTPSPAGEREQUIRED pages.
511 $CFG->httpswwwroot = $CFG->wwwroot;
513 require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
515 if (NO_OUTPUT_BUFFERING) {
516 // we have to call this always before starting session because it discards headers!
517 disable_output_buffering();
520 // Increase memory limits if possible
521 raise_memory_limit(MEMORY_STANDARD);
523 // Time to start counting
524 init_performance_info();
526 // Put $OUTPUT in place, so errors can be displayed.
527 $OUTPUT = new bootstrap_renderer();
529 // set handler for uncaught exceptions - equivalent to print_error() call
530 if (!PHPUNIT_TEST or PHPUNIT_UTIL) {
531 set_exception_handler('default_exception_handler');
532 set_error_handler('default_error_handler', E_ALL | E_STRICT);
535 // Acceptance tests needs special output to capture the errors,
536 // but not necessary for behat CLI command.
537 if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST')) {
538 require_once(__DIR__ . '/behat/lib.php');
539 set_error_handler('behat_error_handler', E_ALL | E_STRICT);
542 // If there are any errors in the standard libraries we want to know!
543 error_reporting(E_ALL | E_STRICT);
545 // Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
546 // http://www.google.com/webmasters/faq.html#prefetchblock
547 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
548 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
549 echo('Prefetch request forbidden.');
553 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
554 //the problem is that we need specific version of quickforms and hacked excel files :-(
555 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
556 //point zend include path to moodles lib/zend so that includes and requires will search there for files before anywhere else
557 //please note zend library is supposed to be used only from web service protocol classes, it may be removed in future
558 ini_set('include_path', $CFG->libdir.'/zend' . PATH_SEPARATOR . ini_get('include_path'));
560 // Register our classloader, in theory somebody might want to replace it to load other hacked core classes.
561 if (defined('COMPONENT_CLASSLOADER')) {
562 spl_autoload_register(COMPONENT_CLASSLOADER);
564 spl_autoload_register('core_component::classloader');
567 // Load up standard libraries
568 require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output
569 require_once($CFG->libdir .'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
570 require_once($CFG->libdir .'/weblib.php'); // Functions relating to HTTP and content
571 require_once($CFG->libdir .'/outputlib.php'); // Functions for generating output
572 require_once($CFG->libdir .'/navigationlib.php'); // Class for generating Navigation structure
573 require_once($CFG->libdir .'/dmllib.php'); // Database access
574 require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
575 require_once($CFG->libdir .'/accesslib.php'); // Access control functions
576 require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
577 require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
578 require_once($CFG->libdir .'/enrollib.php'); // Enrolment related functions
579 require_once($CFG->libdir .'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
580 require_once($CFG->libdir .'/blocklib.php'); // Library for controlling blocks
581 require_once($CFG->libdir .'/eventslib.php'); // Events functions
582 require_once($CFG->libdir .'/grouplib.php'); // Groups functions
583 require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie related stuff
584 require_once($CFG->libdir .'/editorlib.php'); // All text editor related functions and classes
585 require_once($CFG->libdir .'/messagelib.php'); // Messagelib functions
586 require_once($CFG->libdir .'/modinfolib.php'); // Cached information on course-module instances
587 require_once($CFG->dirroot.'/cache/lib.php'); // Cache API
589 // make sure PHP is not severly misconfigured
590 setup_validate_php_configuration();
592 // Connect to the database
595 if (PHPUNIT_TEST and !PHPUNIT_UTIL) {
596 // make sure tests do not run in parallel
597 test_lock::acquire('phpunit');
600 if ($dbhash = $DB->get_field('config', 'value', array('name'=>'phpunittest'))) {
602 phpunit_util::reset_database();
604 } catch (Exception $e) {
606 // we ned to reinit if reset fails
607 $DB->set_field('config', 'value', 'na', array('name'=>'phpunittest'));
613 // Load up any configuration from the config table or MUC cache.
615 phpunit_util::initialise_cfg();
620 if (isset($CFG->debug)) {
621 $CFG->debug = (int)$CFG->debug;
622 error_reporting($CFG->debug);
626 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
628 // Find out if PHP configured to display warnings,
629 // this is a security problem because some moodle scripts may
630 // disclose sensitive information.
631 if (ini_get_bool('display_errors')) {
632 define('WARN_DISPLAY_ERRORS_ENABLED', true);
634 // If we want to display Moodle errors, then try and set PHP errors to match.
635 if (!isset($CFG->debugdisplay)) {
636 // Keep it "as is" during installation.
637 } else if (NO_DEBUG_DISPLAY) {
638 // Some parts of Moodle cannot display errors and debug at all.
639 ini_set('display_errors', '0');
640 ini_set('log_errors', '1');
641 } else if (empty($CFG->debugdisplay)) {
642 ini_set('display_errors', '0');
643 ini_set('log_errors', '1');
645 // This is very problematic in XHTML strict mode!
646 ini_set('display_errors', '1');
649 // Register our shutdown manager, do NOT use register_shutdown_function().
650 core_shutdown_manager::initialize();
652 // Verify upgrade is not running unless we are in a script that needs to execute in any case
653 if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
654 if ($CFG->upgraderunning < time()) {
655 unset_config('upgraderunning');
657 print_error('upgraderunning');
661 // Turn on SQL logging if required
662 if (!empty($CFG->logsql)) {
663 $DB->set_logging(true);
666 // enable circular reference collector in PHP 5.3,
667 // it helps a lot when using large complex OOP structures such as in amos or gradebook
668 if (function_exists('gc_enable')) {
672 // detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
673 if (!empty($CFG->version) and $CFG->version < 2007101509) {
674 print_error('upgraderequires19', 'error');
678 // Calculate and set $CFG->ostype to be used everywhere. Possible values are:
679 // - WINDOWS: for any Windows flavour.
680 // - UNIX: for the rest
681 // Also, $CFG->os can continue being used if more specialization is required
682 if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
683 $CFG->ostype = 'WINDOWS';
685 $CFG->ostype = 'UNIX';
689 // Configure ampersands in URLs
690 ini_set('arg_separator.output', '&');
692 // Work around for a PHP bug see MDL-11237
693 ini_set('pcre.backtrack_limit', 20971520); // 20 MB
695 // Location of standard files
696 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
697 $CFG->moddata = 'moddata';
699 // A hack to get around magic_quotes_gpc being turned on
700 // It is strongly recommended to disable "magic_quotes_gpc"!
701 if (ini_get_bool('magic_quotes_gpc')) {
702 function stripslashes_deep($value) {
703 $value = is_array($value) ?
704 array_map('stripslashes_deep', $value) :
705 stripslashes($value);
708 $_POST = array_map('stripslashes_deep', $_POST);
709 $_GET = array_map('stripslashes_deep', $_GET);
710 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
711 $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
712 if (!empty($_SERVER['REQUEST_URI'])) {
713 $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']);
715 if (!empty($_SERVER['QUERY_STRING'])) {
716 $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']);
718 if (!empty($_SERVER['HTTP_REFERER'])) {
719 $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']);
721 if (!empty($_SERVER['PATH_INFO'])) {
722 $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']);
724 if (!empty($_SERVER['PHP_SELF'])) {
725 $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']);
727 if (!empty($_SERVER['PATH_TRANSLATED'])) {
728 $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']);
732 // neutralise nasty chars in PHP_SELF
733 if (isset($_SERVER['PHP_SELF'])) {
734 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
735 if ($phppos !== false) {
736 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
741 // initialise ME's - this must be done BEFORE starting of session!
744 // define SYSCONTEXTID in config.php if you want to save some queries,
745 // after install it must match the system context record id.
746 if (!defined('SYSCONTEXTID')) {
747 context_system::instance();
750 // Defining the site - aka frontpage course
753 } catch (moodle_exception $e) {
755 if (empty($CFG->version)) {
756 $SITE = new stdClass();
758 $SITE->shortname = null;
763 // And the 'default' course - this will usually get reset later in require_login() etc.
764 $COURSE = clone($SITE);
765 /** @deprecated Id of the frontpage course, use $SITE->id instead */
766 define('SITEID', $SITE->id);
768 // init session prevention flag - this is defined on pages that do not want session
770 // no sessions in CLI scripts possible
771 define('NO_MOODLE_COOKIES', true);
773 } else if (!defined('NO_MOODLE_COOKIES')) {
774 if (empty($CFG->version) or $CFG->version < 2009011900) {
775 // no session before sessions table gets created
776 define('NO_MOODLE_COOKIES', true);
777 } else if (CLI_SCRIPT) {
778 // CLI scripts can not have session
779 define('NO_MOODLE_COOKIES', true);
781 define('NO_MOODLE_COOKIES', false);
785 // Start session and prepare global $SESSION, $USER.
786 if (empty($CFG->sessiontimeout)) {
787 $CFG->sessiontimeout = 7200;
789 \core\session\manager::start();
790 if (!PHPUNIT_TEST and !defined('BEHAT_TEST')) {
791 $SESSION =& $_SESSION['SESSION'];
792 $USER =& $_SESSION['USER'];
795 // Initialise some variables that are supposed to be set in config.php only.
796 if (!isset($CFG->filelifetime)) {
797 $CFG->filelifetime = 60*60*6;
800 // Late profiling, only happening if early one wasn't started
801 if (!empty($CFG->profilingenabled)) {
802 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
806 // Hack to get around max_input_vars restrictions,
807 // we need to do this after session init to have some basic DDoS protection.
808 workaround_max_input_vars();
810 // Process theme change in the URL.
811 if (!empty($CFG->allowthemechangeonurl) and !empty($_GET['theme'])) {
812 // we have to use _GET directly because we do not want this to interfere with _POST
813 $urlthemename = optional_param('theme', '', PARAM_PLUGIN);
815 $themeconfig = theme_config::load($urlthemename);
816 // Makes sure the theme can be loaded without errors.
817 if ($themeconfig->name === $urlthemename) {
818 $SESSION->theme = $urlthemename;
820 unset($SESSION->theme);
823 unset($urlthemename);
824 } catch (Exception $e) {
825 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
828 unset($urlthemename);
830 // Ensure a valid theme is set.
831 if (!isset($CFG->theme)) {
832 $CFG->theme = 'standard';
835 // Set language/locale of printed times. If user has chosen a language that
836 // that is different from the site language, then use the locale specified
837 // in the language file. Otherwise, if the admin hasn't specified a locale
838 // then use the one from the default language. Otherwise (and this is the
839 // majority of cases), use the stored locale specified by admin.
840 // note: do not accept lang parameter from POST
841 if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
842 if (get_string_manager()->translation_exists($lang, false)) {
843 $SESSION->lang = $lang;
848 setup_lang_from_browser();
850 if (empty($CFG->lang)) {
851 if (empty($SESSION->lang)) {
854 $CFG->lang = $SESSION->lang;
858 // Set the default site locale, a lot of the stuff may depend on this
859 // it is definitely too late to call this first in require_login()!
862 // Create the $PAGE global - this marks the PAGE and OUTPUT fully initialised, this MUST be done at the end of setup!
863 if (!empty($CFG->moodlepageclass)) {
864 if (!empty($CFG->moodlepageclassfile)) {
865 require_once($CFG->moodlepageclassfile);
867 $classname = $CFG->moodlepageclass;
869 $classname = 'moodle_page';
871 $PAGE = new $classname();
875 if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
876 if ($CFG->theme == 'standard') { // Temporary measure to help with XHTML validation
877 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
878 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
879 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
880 if ($user = get_complete_user_data("username", "w3cvalidator")) {
881 $user->ignoresesskey = true;
883 $user = guest_user();
885 \core\session\manager::set_user($user);
891 // Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
892 // LogFormat to get the current logged in username in moodle.
893 if ($USER && function_exists('apache_note')
894 && !empty($CFG->apacheloguser) && isset($USER->username)) {
895 $apachelog_userid = $USER->id;
896 $apachelog_username = clean_filename($USER->username);
897 $apachelog_name = '';
898 if (isset($USER->firstname)) {
899 // We can assume both will be set
900 // - even if to empty.
901 $apachelog_name = clean_filename($USER->firstname . " " .
904 if (\core\session\manager::is_loggedinas()) {
905 $realuser = \core\session\manager::get_realuser();
906 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
907 $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
908 $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
910 switch ($CFG->apacheloguser) {
912 $logname = $apachelog_username;
915 $logname = $apachelog_name;
919 $logname = $apachelog_userid;
922 apache_note('MOODLEUSER', $logname);
925 // Use a custom script replacement if one exists
926 if (!empty($CFG->customscripts)) {
927 if (($customscript = custom_script_path()) !== false) {
928 require ($customscript);
933 // no ip blocking, these are CLI only
934 } else if (CLI_SCRIPT and !defined('WEB_CRON_EMULATED_CLI')) {
936 } else if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
937 // in this case, ip in allowed list will be performed first
938 // for example, client IP is 192.168.1.1
939 // 192.168 subnet is an entry in allowed list
940 // 192.168.1.1 is banned in blocked list
941 // This ip will be banned finally
942 if (!empty($CFG->allowedip)) {
943 if (!remoteip_in_list($CFG->allowedip)) {
944 die(get_string('ipblocked', 'admin'));
947 // need further check, client ip may a part of
948 // allowed subnet, but a IP address are listed
950 if (!empty($CFG->blockedip)) {
951 if (remoteip_in_list($CFG->blockedip)) {
952 die(get_string('ipblocked', 'admin'));
957 // in this case, IPs in blocked list will be performed first
958 // for example, client IP is 192.168.1.1
959 // 192.168 subnet is an entry in blocked list
960 // 192.168.1.1 is allowed in allowed list
961 // This ip will be allowed finally
962 if (!empty($CFG->blockedip)) {
963 if (remoteip_in_list($CFG->blockedip)) {
964 // if the allowed ip list is not empty
965 // IPs are not included in the allowed list will be
967 if (!empty($CFG->allowedip)) {
968 if (!remoteip_in_list($CFG->allowedip)) {
969 die(get_string('ipblocked', 'admin'));
972 die(get_string('ipblocked', 'admin'));
976 // if blocked list is null
977 // allowed list should be tested
978 if(!empty($CFG->allowedip)) {
979 if (!remoteip_in_list($CFG->allowedip)) {
980 die(get_string('ipblocked', 'admin'));
986 // // try to detect IE6 and prevent gzip because it is extremely buggy browser
987 if (!empty($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false) {
988 @ini_set('zlib.output_compression', 'Off');
989 if (function_exists('apache_setenv')) {
990 @apache_setenv('no-gzip', 1);
994 // Switch to CLI maintenance mode if required, we need to do it here after all the settings are initialised.
995 if (isset($CFG->maintenance_later) and $CFG->maintenance_later <= time()) {
996 if (!file_exists("$CFG->dataroot/climaintenance.html")) {
997 require_once("$CFG->libdir/adminlib.php");
998 enable_cli_maintenance_mode();
1000 unset_config('maintenance_later');
1003 } else if (!CLI_SCRIPT) {
1004 redirect(new moodle_url('/'));
1008 // note: we can not block non utf-8 installations here, because empty mysql database
1009 // might be converted to utf-8 in admin/index.php during installation
1013 // this is a funny trick to make Eclipse believe that $OUTPUT and other globals
1014 // contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
1016 $DB = new moodle_database();
1017 $OUTPUT = new core_renderer(null, null);
1018 $PAGE = new moodle_page();