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 // Normalise dataroot - we do not want any symbolic links, trailing / or any other weirdness there
63 if (!isset($CFG->dataroot
)) {
64 if (isset($_SERVER['REMOTE_ADDR'])) {
65 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
67 echo('Fatal error: $CFG->dataroot is not specified in config.php! Exiting.'."\n");
70 $CFG->dataroot
= realpath($CFG->dataroot
);
71 if ($CFG->dataroot
=== false) {
72 if (isset($_SERVER['REMOTE_ADDR'])) {
73 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
75 echo('Fatal error: $CFG->dataroot is not configured properly, directory does not exist or is not accessible! Exiting.'."\n");
77 } else if (!is_writable($CFG->dataroot
)) {
78 if (isset($_SERVER['REMOTE_ADDR'])) {
79 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
81 echo('Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.'."\n");
85 // wwwroot is mandatory
86 if (!isset($CFG->wwwroot
) or $CFG->wwwroot
=== 'http://example.com/moodle') {
87 if (isset($_SERVER['REMOTE_ADDR'])) {
88 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
90 echo('Fatal error: $CFG->wwwroot is not configured! Exiting.'."\n");
94 // Ignore $CFG->behat_wwwroot and use the same wwwroot.
95 if (!empty($CFG->behat_switchcompletely
)) {
96 $CFG->behat_wwwroot
= $CFG->wwwroot
;
98 } else if (empty($CFG->behat_wwwroot
)) {
99 // Default URL for acceptance testing, only accessible from localhost.
100 $CFG->behat_wwwroot
= 'http://localhost:8000';
104 // Test environment is requested if:
105 // * Behat is running (constant set hooking the behat init process before requiring config.php).
106 // * If we are accessing though the built-in web server (cli-server).
107 // * If $CFG->behat_switchcompletely has been set (maintains CLI scripts behaviour, which ATM is only preventive).
108 // Test environment is enabled if:
109 // * User has previously enabled through admin/tool/behat/cli/util.php --enable.
110 // Both are required to switch to test mode
111 if (!defined('BEHAT_SITE_RUNNING') && !empty($CFG->behat_dataroot
) &&
112 !empty($CFG->behat_prefix
) && file_exists($CFG->behat_dataroot
)) {
114 $CFG->behat_dataroot
= realpath($CFG->behat_dataroot
);
116 $switchcompletely = !empty($CFG->behat_switchcompletely
) && php_sapi_name() !== 'cli';
117 $builtinserver = php_sapi_name() === 'cli-server';
118 $behatrunning = defined('BEHAT_TEST');
119 $testenvironmentrequested = $switchcompletely ||
$builtinserver ||
$behatrunning;
121 // Only switch to test environment if it has been enabled.
122 $testenvironmentenabled = file_exists($CFG->behat_dataroot
. '/behat/test_environment_enabled.txt');
124 if ($testenvironmentenabled && $testenvironmentrequested) {
126 // Constant used to inform that the behat test site is being used,
127 // this includes all the processes executed by the behat CLI command like
128 // the site reset, the steps executed by the browser drivers when simulating
129 // a user session and a real session when browsing manually to $CFG->behat_wwwroot
130 // like the browser driver does automatically.
131 // Different from BEHAT_TEST as only this last one can perform CLI
132 // actions like reset the site or use data generators.
133 define('BEHAT_SITE_RUNNING', true);
135 // Clean extra config.php settings.
136 require_once(__DIR__
. '/../lib/behat/lib.php');
137 behat_clean_init_config();
139 $CFG->wwwroot
= $CFG->behat_wwwroot
;
140 $CFG->passwordsaltmain
= 'moodle';
141 $CFG->prefix
= $CFG->behat_prefix
;
142 $CFG->dataroot
= $CFG->behat_dataroot
;
146 // Make sure there is some database table prefix.
147 if (!isset($CFG->prefix
)) {
151 // Define admin directory
152 if (!isset($CFG->admin
)) { // Just in case it isn't defined in config.php
153 $CFG->admin
= 'admin'; // This is relative to the wwwroot and dirroot
156 // Set up some paths.
157 $CFG->libdir
= $CFG->dirroot
.'/lib';
159 // Allow overriding of tempdir but be backwards compatible
160 if (!isset($CFG->tempdir
)) {
161 $CFG->tempdir
= "$CFG->dataroot/temp";
164 // Allow overriding of cachedir but be backwards compatible
165 if (!isset($CFG->cachedir
)) {
166 $CFG->cachedir
= "$CFG->dataroot/cache";
169 // Allow overriding of localcachedir.
170 if (!isset($CFG->localcachedir
)) {
171 $CFG->localcachedir
= "$CFG->dataroot/localcache";
174 // Location of all languages except core English pack.
175 if (!isset($CFG->langotherroot
)) {
176 $CFG->langotherroot
= $CFG->dataroot
.'/lang';
179 // Location of local lang pack customisations (dirs with _local suffix).
180 if (!isset($CFG->langlocalroot
)) {
181 $CFG->langlocalroot
= $CFG->dataroot
.'/lang';
184 // The current directory in PHP version 4.3.0 and above isn't necessarily the
185 // directory of the script when run from the command line. The require_once()
186 // would fail, so we'll have to chdir()
187 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
188 // do it only once - skip the second time when continuing after prevous abort
189 if (!defined('ABORT_AFTER_CONFIG') and !defined('ABORT_AFTER_CONFIG_CANCEL')) {
190 chdir(dirname($_SERVER['argv'][0]));
194 // sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
195 ini_set('precision', 14); // needed for upgrades and gradebook
197 // Scripts may request no debug and error messages in output
198 // please note it must be defined before including the config.php script
199 // and in some cases you also need to set custom default exception handler
200 if (!defined('NO_DEBUG_DISPLAY')) {
201 if (defined('AJAX_SCRIPT') and AJAX_SCRIPT
) {
202 // Moodle AJAX scripts are expected to return json data, any PHP notices or errors break it badly,
203 // developers simply must learn to watch error log.
204 define('NO_DEBUG_DISPLAY', true);
206 define('NO_DEBUG_DISPLAY', false);
210 // Some scripts such as upgrade may want to prevent output buffering
211 if (!defined('NO_OUTPUT_BUFFERING')) {
212 define('NO_OUTPUT_BUFFERING', false);
215 // PHPUnit tests need custom init
216 if (!defined('PHPUNIT_TEST')) {
217 define('PHPUNIT_TEST', false);
220 // When set to true MUC (Moodle caching) will be disabled as much as possible.
221 // A special cache factory will be used to handle this situation and will use special "disabled" equivalents objects.
222 // This ensure we don't attempt to read or create the config file, don't use stores, don't provide persistence or
223 // storage of any kind.
224 if (!defined('CACHE_DISABLE_ALL')) {
225 define('CACHE_DISABLE_ALL', false);
228 // When set to true MUC (Moodle caching) will not use any of the defined or default stores.
229 // The Cache API will continue to function however this will force the use of the cachestore_dummy so all requests
230 // will be interacting with a static property and will never go to the proper cache stores.
231 // Useful if you need to avoid the stores for one reason or another.
232 if (!defined('CACHE_DISABLE_STORES')) {
233 define('CACHE_DISABLE_STORES', false);
236 // Servers should define a default timezone in php.ini, but if they don't then make sure something is defined.
237 // This is a quick hack. Ideally we should ask the admin for a value. See MDL-22625 for more on this.
238 if (function_exists('date_default_timezone_set') and function_exists('date_default_timezone_get')) {
239 $olddebug = error_reporting(0);
240 date_default_timezone_set(date_default_timezone_get());
241 error_reporting($olddebug);
245 // Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
246 // In your new CLI scripts just add "define('CLI_SCRIPT', true);" before requiring config.php.
247 // Please note that one script can not be accessed from both CLI and web interface.
248 if (!defined('CLI_SCRIPT')) {
249 define('CLI_SCRIPT', false);
251 if (defined('WEB_CRON_EMULATED_CLI')) {
252 if (!isset($_SERVER['REMOTE_ADDR'])) {
253 echo('Web cron can not be executed as CLI script any more, please use admin/cli/cron.php instead'."\n");
256 } else if (isset($_SERVER['REMOTE_ADDR'])) {
258 echo('Command line scripts can not be executed from the web interface');
263 echo('Command line scripts must define CLI_SCRIPT before requiring config.php'."\n");
268 // Detect CLI maintenance mode - this is useful when you need to mess with database, such as during upgrades
269 if (file_exists("$CFG->dataroot/climaintenance.html")) {
271 header('Content-type: text/html; charset=utf-8');
272 header('X-UA-Compatible: IE=edge');
273 /// Headers to make it not cacheable and json
274 header('Cache-Control: no-store, no-cache, must-revalidate');
275 header('Cache-Control: post-check=0, pre-check=0', false);
276 header('Pragma: no-cache');
277 header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
278 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
279 header('Accept-Ranges: none');
280 readfile("$CFG->dataroot/climaintenance.html");
283 if (!defined('CLI_MAINTENANCE')) {
284 define('CLI_MAINTENANCE', true);
288 if (!defined('CLI_MAINTENANCE')) {
289 define('CLI_MAINTENANCE', false);
294 // sometimes people use different PHP binary for web and CLI, make 100% sure they have the supported PHP version
295 if (version_compare(phpversion(), '5.3.3') < 0) {
296 $phpversion = phpversion();
297 // do NOT localise - lang strings would not work here and we CAN NOT move it to later place
298 echo "Moodle 2.5 or later requires at least PHP 5.3.3 (currently using version $phpversion).\n";
299 echo "Some servers may have multiple PHP versions installed, are you using the correct executable?\n";
304 // Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
305 if (!defined('AJAX_SCRIPT')) {
306 define('AJAX_SCRIPT', false);
309 // File permissions on created directories in the $CFG->dataroot
310 if (!isset($CFG->directorypermissions
)) {
311 $CFG->directorypermissions
= 02777; // Must be octal (that's why it's here)
313 if (!isset($CFG->filepermissions
)) {
314 $CFG->filepermissions
= ($CFG->directorypermissions
& 0666); // strip execute flags
316 // Better also set default umask because developers often forget to include directory
317 // permissions in mkdir() and chmod() after creating new files.
318 if (!isset($CFG->umaskpermissions
)) {
319 $CFG->umaskpermissions
= (($CFG->directorypermissions
& 0777) ^
0777);
321 umask($CFG->umaskpermissions
);
323 // Exact version of currently used yui2 and 3 library.
324 $CFG->yui2version
= '2.9.0';
325 $CFG->yui3version
= '3.13.0';
327 // Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides.
328 if (!isset($CFG->config_php_settings
)) {
329 $CFG->config_php_settings
= (array)$CFG;
330 // Forced plugin settings override values from config_plugins table.
331 unset($CFG->config_php_settings
['forced_plugin_settings']);
332 if (!isset($CFG->forced_plugin_settings
)) {
333 $CFG->forced_plugin_settings
= array();
337 if (isset($CFG->debug
)) {
338 $CFG->debug
= (int)$CFG->debug
;
342 $CFG->debugdeveloper
= (($CFG->debug
& (E_ALL | E_STRICT
)) === (E_ALL | E_STRICT
)); // DEBUG_DEVELOPER is not available yet.
344 if (!defined('MOODLE_INTERNAL')) { // Necessary because cli installer has to define it earlier.
345 /** Used by library scripts to check they are being called by Moodle. */
346 define('MOODLE_INTERNAL', true);
349 // core_component can be used in any scripts, it does not need anything else.
350 require_once($CFG->libdir
.'/classes/component.php');
352 // special support for highly optimised scripts that do not need libraries and DB connection
353 if (defined('ABORT_AFTER_CONFIG')) {
354 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
355 // hide debugging if not enabled in config.php - we do not want to disclose sensitive info
356 error_reporting($CFG->debug
);
357 if (NO_DEBUG_DISPLAY
) {
358 // Some parts of Moodle cannot display errors and debug at all.
359 ini_set('display_errors', '0');
360 ini_set('log_errors', '1');
361 } else if (empty($CFG->debugdisplay
)) {
362 ini_set('display_errors', '0');
363 ini_set('log_errors', '1');
365 ini_set('display_errors', '1');
367 require_once("$CFG->dirroot/lib/configonlylib.php");
372 // Early profiling start, based exclusively on config.php $CFG settings
373 if (!empty($CFG->earlyprofilingenabled
)) {
374 require_once($CFG->libdir
. '/xhprof/xhprof_moodle.php');
379 * Database connection. Used for all access to the database.
380 * @global moodle_database $DB
386 * Moodle's wrapper round PHP's $_SESSION.
388 * @global object $SESSION
394 * Holds the user table record for the current user. Will be the 'guest'
395 * user record for people who are not logged in.
397 * $USER is stored in the session.
399 * Items found in the user record:
400 * - $USER->email - The user's email address.
401 * - $USER->id - The unique integer identified of this user in the 'user' table.
402 * - $USER->email - The user's email address.
403 * - $USER->firstname - The user's first name.
404 * - $USER->lastname - The user's last name.
405 * - $USER->username - The user's login username.
406 * - $USER->secret - The user's ?.
407 * - $USER->lang - The user's language choice.
409 * @global object $USER
415 * Frontpage course record
420 * A central store of information about the current page we are
421 * generating in response to the user's request.
423 * @global moodle_page $PAGE
429 * The current course. An alias for $PAGE->course.
430 * @global object $COURSE
436 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
437 * it to generate HTML for output.
439 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
440 * for the magic that does that. After $OUTPUT has been initialised, any attempt
441 * to change something that affects the current theme ($PAGE->course, logged in use,
442 * httpsrequried ... will result in an exception.)
444 * Please note the $OUTPUT is replacing the old global $THEME object.
446 * @global object $OUTPUT
452 * Full script path including all params, slash arguments, scheme and host.
454 * Note: Do NOT use for getting of current page URL or detection of https,
455 * instead use $PAGE->url or strpos($CFG->httpswwwroot, 'https:') === 0
457 * @global string $FULLME
463 * Script path including query string and slash arguments without host.
470 * $FULLME without slasharguments and query string.
471 * @global string $FULLSCRIPT
477 * Relative moodle script path '/course/view.php'
478 * @global string $SCRIPT
483 // Set httpswwwroot default value (this variable will replace $CFG->wwwroot
484 // inside some URLs used in HTTPSPAGEREQUIRED pages.
485 $CFG->httpswwwroot
= $CFG->wwwroot
;
487 require_once($CFG->libdir
.'/setuplib.php'); // Functions that MUST be loaded first
489 if (NO_OUTPUT_BUFFERING
) {
490 // we have to call this always before starting session because it discards headers!
491 disable_output_buffering();
494 // Increase memory limits if possible
495 raise_memory_limit(MEMORY_STANDARD
);
497 // Time to start counting
498 init_performance_info();
500 // Put $OUTPUT in place, so errors can be displayed.
501 $OUTPUT = new bootstrap_renderer();
503 // set handler for uncaught exceptions - equivalent to print_error() call
504 if (!PHPUNIT_TEST
or PHPUNIT_UTIL
) {
505 set_exception_handler('default_exception_handler');
506 set_error_handler('default_error_handler', E_ALL | E_STRICT
);
509 // Acceptance tests needs special output to capture the errors,
510 // but not necessary for behat CLI command.
511 if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST')) {
512 require_once(__DIR__
. '/behat/lib.php');
513 set_error_handler('behat_error_handler', E_ALL | E_STRICT
);
516 // If there are any errors in the standard libraries we want to know!
517 error_reporting(E_ALL | E_STRICT
);
519 // Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
520 // http://www.google.com/webmasters/faq.html#prefetchblock
521 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
522 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
523 echo('Prefetch request forbidden.');
527 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
528 //the problem is that we need specific version of quickforms and hacked excel files :-(
529 ini_set('include_path', $CFG->libdir
.'/pear' . PATH_SEPARATOR
. ini_get('include_path'));
530 //point zend include path to moodles lib/zend so that includes and requires will search there for files before anywhere else
531 //please note zend library is supposed to be used only from web service protocol classes, it may be removed in future
532 ini_set('include_path', $CFG->libdir
.'/zend' . PATH_SEPARATOR
. ini_get('include_path'));
534 // Register our classloader, in theory somebody might want to replace it to load other hacked core classes.
535 if (defined('COMPONENT_CLASSLOADER')) {
536 spl_autoload_register(COMPONENT_CLASSLOADER
);
538 spl_autoload_register('core_component::classloader');
541 // Load up standard libraries
542 require_once($CFG->libdir
.'/filterlib.php'); // Functions for filtering test as it is output
543 require_once($CFG->libdir
.'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
544 require_once($CFG->libdir
.'/weblib.php'); // Functions relating to HTTP and content
545 require_once($CFG->libdir
.'/outputlib.php'); // Functions for generating output
546 require_once($CFG->libdir
.'/navigationlib.php'); // Class for generating Navigation structure
547 require_once($CFG->libdir
.'/dmllib.php'); // Database access
548 require_once($CFG->libdir
.'/datalib.php'); // Legacy lib with a big-mix of functions.
549 require_once($CFG->libdir
.'/accesslib.php'); // Access control functions
550 require_once($CFG->libdir
.'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
551 require_once($CFG->libdir
.'/moodlelib.php'); // Other general-purpose functions
552 require_once($CFG->libdir
.'/enrollib.php'); // Enrolment related functions
553 require_once($CFG->libdir
.'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
554 require_once($CFG->libdir
.'/blocklib.php'); // Library for controlling blocks
555 require_once($CFG->libdir
.'/eventslib.php'); // Events functions
556 require_once($CFG->libdir
.'/grouplib.php'); // Groups functions
557 require_once($CFG->libdir
.'/sessionlib.php'); // All session and cookie related stuff
558 require_once($CFG->libdir
.'/editorlib.php'); // All text editor related functions and classes
559 require_once($CFG->libdir
.'/messagelib.php'); // Messagelib functions
560 require_once($CFG->libdir
.'/modinfolib.php'); // Cached information on course-module instances
561 require_once($CFG->dirroot
.'/cache/lib.php'); // Cache API
563 // make sure PHP is not severly misconfigured
564 setup_validate_php_configuration();
566 // Connect to the database
569 if (PHPUNIT_TEST
and !PHPUNIT_UTIL
) {
570 // make sure tests do not run in parallel
571 test_lock
::acquire('phpunit');
574 if ($dbhash = $DB->get_field('config', 'value', array('name'=>'phpunittest'))) {
576 phpunit_util
::reset_database();
578 } catch (Exception
$e) {
580 // we ned to reinit if reset fails
581 $DB->set_field('config', 'value', 'na', array('name'=>'phpunittest'));
587 // Load up any configuration from the config table or MUC cache.
589 phpunit_util
::initialise_cfg();
594 if (isset($CFG->debug
)) {
595 $CFG->debug
= (int)$CFG->debug
;
596 error_reporting($CFG->debug
);
600 $CFG->debugdeveloper
= (($CFG->debug
& DEBUG_DEVELOPER
) === DEBUG_DEVELOPER
);
602 // Find out if PHP configured to display warnings,
603 // this is a security problem because some moodle scripts may
604 // disclose sensitive information.
605 if (ini_get_bool('display_errors')) {
606 define('WARN_DISPLAY_ERRORS_ENABLED', true);
608 // If we want to display Moodle errors, then try and set PHP errors to match.
609 if (!isset($CFG->debugdisplay
)) {
610 // Keep it "as is" during installation.
611 } else if (NO_DEBUG_DISPLAY
) {
612 // Some parts of Moodle cannot display errors and debug at all.
613 ini_set('display_errors', '0');
614 ini_set('log_errors', '1');
615 } else if (empty($CFG->debugdisplay
)) {
616 ini_set('display_errors', '0');
617 ini_set('log_errors', '1');
619 // This is very problematic in XHTML strict mode!
620 ini_set('display_errors', '1');
623 // Register our shutdown manager, do NOT use register_shutdown_function().
624 core_shutdown_manager
::initialize();
626 // Verify upgrade is not running unless we are in a script that needs to execute in any case
627 if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning
)) {
628 if ($CFG->upgraderunning
< time()) {
629 unset_config('upgraderunning');
631 print_error('upgraderunning');
635 // Turn on SQL logging if required
636 if (!empty($CFG->logsql
)) {
637 $DB->set_logging(true);
640 // enable circular reference collector in PHP 5.3,
641 // it helps a lot when using large complex OOP structures such as in amos or gradebook
642 if (function_exists('gc_enable')) {
646 // detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
647 if (!empty($CFG->version
) and $CFG->version
< 2007101509) {
648 print_error('upgraderequires19', 'error');
652 // Calculate and set $CFG->ostype to be used everywhere. Possible values are:
653 // - WINDOWS: for any Windows flavour.
654 // - UNIX: for the rest
655 // Also, $CFG->os can continue being used if more specialization is required
656 if (stristr(PHP_OS
, 'win') && !stristr(PHP_OS
, 'darwin')) {
657 $CFG->ostype
= 'WINDOWS';
659 $CFG->ostype
= 'UNIX';
663 // Configure ampersands in URLs
664 ini_set('arg_separator.output', '&');
666 // Work around for a PHP bug see MDL-11237
667 ini_set('pcre.backtrack_limit', 20971520); // 20 MB
669 // Location of standard files
670 $CFG->wordlist
= $CFG->libdir
.'/wordlist.txt';
671 $CFG->moddata
= 'moddata';
673 // A hack to get around magic_quotes_gpc being turned on
674 // It is strongly recommended to disable "magic_quotes_gpc"!
675 if (ini_get_bool('magic_quotes_gpc')) {
676 function stripslashes_deep($value) {
677 $value = is_array($value) ?
678 array_map('stripslashes_deep', $value) :
679 stripslashes($value);
682 $_POST = array_map('stripslashes_deep', $_POST);
683 $_GET = array_map('stripslashes_deep', $_GET);
684 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
685 $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
686 if (!empty($_SERVER['REQUEST_URI'])) {
687 $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']);
689 if (!empty($_SERVER['QUERY_STRING'])) {
690 $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']);
692 if (!empty($_SERVER['HTTP_REFERER'])) {
693 $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']);
695 if (!empty($_SERVER['PATH_INFO'])) {
696 $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']);
698 if (!empty($_SERVER['PHP_SELF'])) {
699 $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']);
701 if (!empty($_SERVER['PATH_TRANSLATED'])) {
702 $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']);
706 // neutralise nasty chars in PHP_SELF
707 if (isset($_SERVER['PHP_SELF'])) {
708 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
709 if ($phppos !== false) {
710 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+
4);
715 // initialise ME's - this must be done BEFORE starting of session!
718 // define SYSCONTEXTID in config.php if you want to save some queries,
719 // after install it must match the system context record id.
720 if (!defined('SYSCONTEXTID')) {
721 context_system
::instance();
724 // Defining the site - aka frontpage course
727 } catch (moodle_exception
$e) {
729 if (empty($CFG->version
)) {
730 $SITE = new stdClass();
732 $SITE->shortname
= null;
737 // And the 'default' course - this will usually get reset later in require_login() etc.
738 $COURSE = clone($SITE);
739 /** @deprecated Id of the frontpage course, use $SITE->id instead */
740 define('SITEID', $SITE->id
);
742 // init session prevention flag - this is defined on pages that do not want session
744 // no sessions in CLI scripts possible
745 define('NO_MOODLE_COOKIES', true);
747 } else if (!defined('NO_MOODLE_COOKIES')) {
748 if (empty($CFG->version
) or $CFG->version
< 2009011900) {
749 // no session before sessions table gets created
750 define('NO_MOODLE_COOKIES', true);
751 } else if (CLI_SCRIPT
) {
752 // CLI scripts can not have session
753 define('NO_MOODLE_COOKIES', true);
755 define('NO_MOODLE_COOKIES', false);
759 // Start session and prepare global $SESSION, $USER.
760 if (empty($CFG->sessiontimeout
)) {
761 $CFG->sessiontimeout
= 7200;
763 \core\session\manager
::start();
764 if (!PHPUNIT_TEST
and !defined('BEHAT_TEST')) {
765 $SESSION =& $_SESSION['SESSION'];
766 $USER =& $_SESSION['USER'];
769 // Initialise some variables that are supposed to be set in config.php only.
770 if (!isset($CFG->filelifetime
)) {
771 $CFG->filelifetime
= 60*60*6;
774 // Late profiling, only happening if early one wasn't started
775 if (!empty($CFG->profilingenabled
)) {
776 require_once($CFG->libdir
. '/xhprof/xhprof_moodle.php');
780 // Process theme change in the URL.
781 if (!empty($CFG->allowthemechangeonurl
) and !empty($_GET['theme'])) {
782 // we have to use _GET directly because we do not want this to interfere with _POST
783 $urlthemename = optional_param('theme', '', PARAM_PLUGIN
);
785 $themeconfig = theme_config
::load($urlthemename);
786 // Makes sure the theme can be loaded without errors.
787 if ($themeconfig->name
=== $urlthemename) {
788 $SESSION->theme
= $urlthemename;
790 unset($SESSION->theme
);
793 unset($urlthemename);
794 } catch (Exception
$e) {
795 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER
, $e->getTrace());
798 unset($urlthemename);
800 // Ensure a valid theme is set.
801 if (!isset($CFG->theme
)) {
802 $CFG->theme
= 'standard';
805 // Set language/locale of printed times. If user has chosen a language that
806 // that is different from the site language, then use the locale specified
807 // in the language file. Otherwise, if the admin hasn't specified a locale
808 // then use the one from the default language. Otherwise (and this is the
809 // majority of cases), use the stored locale specified by admin.
810 // note: do not accept lang parameter from POST
811 if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR
))) {
812 if (get_string_manager()->translation_exists($lang, false)) {
813 $SESSION->lang
= $lang;
818 setup_lang_from_browser();
820 if (empty($CFG->lang
)) {
821 if (empty($SESSION->lang
)) {
824 $CFG->lang
= $SESSION->lang
;
828 // Set the default site locale, a lot of the stuff may depend on this
829 // it is definitely too late to call this first in require_login()!
832 // Create the $PAGE global - this marks the PAGE and OUTPUT fully initialised, this MUST be done at the end of setup!
833 if (!empty($CFG->moodlepageclass
)) {
834 if (!empty($CFG->moodlepageclassfile
)) {
835 require_once($CFG->moodlepageclassfile
);
837 $classname = $CFG->moodlepageclass
;
839 $classname = 'moodle_page';
841 $PAGE = new $classname();
845 if (!empty($CFG->debugvalidators
) and !empty($CFG->guestloginbutton
)) {
846 if ($CFG->theme
== 'standard') { // Temporary measure to help with XHTML validation
847 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id
)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
848 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
849 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
850 if ($user = get_complete_user_data("username", "w3cvalidator")) {
851 $user->ignoresesskey
= true;
853 $user = guest_user();
855 \core\session\manager
::set_user($user);
861 // Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
862 // LogFormat to get the current logged in username in moodle.
863 if ($USER && function_exists('apache_note')
864 && !empty($CFG->apacheloguser
) && isset($USER->username
)) {
865 $apachelog_userid = $USER->id
;
866 $apachelog_username = clean_filename($USER->username
);
867 $apachelog_name = '';
868 if (isset($USER->firstname
)) {
869 // We can assume both will be set
870 // - even if to empty.
871 $apachelog_name = clean_filename($USER->firstname
. " " .
874 if (\core\session\manager
::is_loggedinas()) {
875 $realuser = \core\session\manager
::get_realuser();
876 $apachelog_username = clean_filename($realuser->username
." as ".$apachelog_username);
877 $apachelog_name = clean_filename($realuser->firstname
." ".$realuser->lastname
." as ".$apachelog_name);
878 $apachelog_userid = clean_filename($realuser->id
." as ".$apachelog_userid);
880 switch ($CFG->apacheloguser
) {
882 $logname = $apachelog_username;
885 $logname = $apachelog_name;
889 $logname = $apachelog_userid;
892 apache_note('MOODLEUSER', $logname);
895 // Use a custom script replacement if one exists
896 if (!empty($CFG->customscripts
)) {
897 if (($customscript = custom_script_path()) !== false) {
898 require ($customscript);
903 // no ip blocking, these are CLI only
904 } else if (CLI_SCRIPT
and !defined('WEB_CRON_EMULATED_CLI')) {
906 } else if (!empty($CFG->allowbeforeblock
)) { // allowed list processed before blocked list?
907 // in this case, ip in allowed list will be performed first
908 // for example, client IP is 192.168.1.1
909 // 192.168 subnet is an entry in allowed list
910 // 192.168.1.1 is banned in blocked list
911 // This ip will be banned finally
912 if (!empty($CFG->allowedip
)) {
913 if (!remoteip_in_list($CFG->allowedip
)) {
914 die(get_string('ipblocked', 'admin'));
917 // need further check, client ip may a part of
918 // allowed subnet, but a IP address are listed
920 if (!empty($CFG->blockedip
)) {
921 if (remoteip_in_list($CFG->blockedip
)) {
922 die(get_string('ipblocked', 'admin'));
927 // in this case, IPs in blocked list will be performed first
928 // for example, client IP is 192.168.1.1
929 // 192.168 subnet is an entry in blocked list
930 // 192.168.1.1 is allowed in allowed list
931 // This ip will be allowed finally
932 if (!empty($CFG->blockedip
)) {
933 if (remoteip_in_list($CFG->blockedip
)) {
934 // if the allowed ip list is not empty
935 // IPs are not included in the allowed list will be
937 if (!empty($CFG->allowedip
)) {
938 if (!remoteip_in_list($CFG->allowedip
)) {
939 die(get_string('ipblocked', 'admin'));
942 die(get_string('ipblocked', 'admin'));
946 // if blocked list is null
947 // allowed list should be tested
948 if(!empty($CFG->allowedip
)) {
949 if (!remoteip_in_list($CFG->allowedip
)) {
950 die(get_string('ipblocked', 'admin'));
956 // // try to detect IE6 and prevent gzip because it is extremely buggy browser
957 if (!empty($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false) {
958 @ini_set
('zlib.output_compression', 'Off');
959 if (function_exists('apache_setenv')) {
960 @apache_setenv
('no-gzip', 1);
964 // Switch to CLI maintenance mode if required, we need to do it here after all the settings are initialised.
965 if (isset($CFG->maintenance_later
) and $CFG->maintenance_later
<= time()) {
966 if (!file_exists("$CFG->dataroot/climaintenance.html")) {
967 require_once("$CFG->libdir/adminlib.php");
968 enable_cli_maintenance_mode();
970 unset_config('maintenance_later');
973 } else if (!CLI_SCRIPT
) {
974 redirect(new moodle_url('/'));
978 // note: we can not block non utf-8 installations here, because empty mysql database
979 // might be converted to utf-8 in admin/index.php during installation
983 // this is a funny trick to make Eclipse believe that $OUTPUT and other globals
984 // contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
986 $DB = new moodle_database();
987 $OUTPUT = new core_renderer(null, null);
988 $PAGE = new moodle_page();