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(__DIR__
);
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');
84 // Update config variables for parallel behat runs.
85 behat_update_vars_for_process();
87 if (behat_is_test_site()) {
90 // Checking the integrity of the provided $CFG->behat_* vars and the
91 // selected wwwroot to prevent conflicts with production and phpunit environments.
92 behat_check_config_vars();
94 // Check that the directory does not contains other things.
95 if (!file_exists("$CFG->behat_dataroot/behattestdir.txt")) {
96 if ($dh = opendir($CFG->behat_dataroot
)) {
97 while (($file = readdir($dh)) !== false) {
98 if ($file === 'behat' or $file === '.' or $file === '..' or $file === '.DS_Store' or is_numeric($file)) {
101 behat_error(BEHAT_EXITCODE_CONFIG
, "$CFG->behat_dataroot directory is not empty, ensure this is the " .
102 "directory where you want to install behat test dataroot");
109 if (defined('BEHAT_UTIL')) {
110 // Now we create dataroot directory structure for behat tests.
111 testing_initdataroot($CFG->behat_dataroot
, 'behat');
113 behat_error(BEHAT_EXITCODE_INSTALL
);
117 if (!defined('BEHAT_UTIL') and !defined('BEHAT_TEST')) {
118 // Somebody tries to access test site directly, tell them if not enabled.
119 if (!file_exists($CFG->behat_dataroot
. '/behat/test_environment_enabled.txt')) {
120 behat_error(BEHAT_EXITCODE_CONFIG
, 'Behat is configured but not enabled on this test site.');
124 // Constant used to inform that the behat test site is being used,
125 // this includes all the processes executed by the behat CLI command like
126 // the site reset, the steps executed by the browser drivers when simulating
127 // a user session and a real session when browsing manually to $CFG->behat_wwwroot
128 // like the browser driver does automatically.
129 // Different from BEHAT_TEST as only this last one can perform CLI
130 // actions like reset the site or use data generators.
131 define('BEHAT_SITE_RUNNING', true);
133 // Clean extra config.php settings.
134 behat_clean_init_config();
136 // Now we can begin switching $CFG->X for $CFG->behat_X.
137 $CFG->wwwroot
= $CFG->behat_wwwroot
;
138 $CFG->prefix
= $CFG->behat_prefix
;
139 $CFG->dataroot
= $CFG->behat_dataroot
;
143 // Normalise dataroot - we do not want any symbolic links, trailing / or any other weirdness there
144 if (!isset($CFG->dataroot
)) {
145 if (isset($_SERVER['REMOTE_ADDR'])) {
146 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
148 echo('Fatal error: $CFG->dataroot is not specified in config.php! Exiting.'."\n");
151 $CFG->dataroot
= realpath($CFG->dataroot
);
152 if ($CFG->dataroot
=== false) {
153 if (isset($_SERVER['REMOTE_ADDR'])) {
154 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
156 echo('Fatal error: $CFG->dataroot is not configured properly, directory does not exist or is not accessible! Exiting.'."\n");
158 } else if (!is_writable($CFG->dataroot
)) {
159 if (isset($_SERVER['REMOTE_ADDR'])) {
160 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
162 echo('Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.'."\n");
166 // wwwroot is mandatory
167 if (!isset($CFG->wwwroot
) or $CFG->wwwroot
=== 'http://example.com/moodle') {
168 if (isset($_SERVER['REMOTE_ADDR'])) {
169 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
171 echo('Fatal error: $CFG->wwwroot is not configured! Exiting.'."\n");
175 // Make sure there is some database table prefix.
176 if (!isset($CFG->prefix
)) {
180 // Define admin directory
181 if (!isset($CFG->admin
)) { // Just in case it isn't defined in config.php
182 $CFG->admin
= 'admin'; // This is relative to the wwwroot and dirroot
185 // Set up some paths.
186 $CFG->libdir
= $CFG->dirroot
.'/lib';
188 // Allow overriding of tempdir but be backwards compatible
189 if (!isset($CFG->tempdir
)) {
190 $CFG->tempdir
= "$CFG->dataroot/temp";
193 // Allow overriding of cachedir but be backwards compatible
194 if (!isset($CFG->cachedir
)) {
195 $CFG->cachedir
= "$CFG->dataroot/cache";
198 // Allow overriding of localcachedir.
199 if (!isset($CFG->localcachedir
)) {
200 $CFG->localcachedir
= "$CFG->dataroot/localcache";
203 // Location of all languages except core English pack.
204 if (!isset($CFG->langotherroot
)) {
205 $CFG->langotherroot
= $CFG->dataroot
.'/lang';
208 // Location of local lang pack customisations (dirs with _local suffix).
209 if (!isset($CFG->langlocalroot
)) {
210 $CFG->langlocalroot
= $CFG->dataroot
.'/lang';
213 // The current directory in PHP version 4.3.0 and above isn't necessarily the
214 // directory of the script when run from the command line. The require_once()
215 // would fail, so we'll have to chdir()
216 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
217 // do it only once - skip the second time when continuing after prevous abort
218 if (!defined('ABORT_AFTER_CONFIG') and !defined('ABORT_AFTER_CONFIG_CANCEL')) {
219 chdir(dirname($_SERVER['argv'][0]));
223 // sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
224 ini_set('precision', 14); // needed for upgrades and gradebook
225 ini_set('serialize_precision', 17); // Make float serialization consistent on all systems.
227 // Scripts may request no debug and error messages in output
228 // please note it must be defined before including the config.php script
229 // and in some cases you also need to set custom default exception handler
230 if (!defined('NO_DEBUG_DISPLAY')) {
231 if (defined('AJAX_SCRIPT') and AJAX_SCRIPT
) {
232 // Moodle AJAX scripts are expected to return json data, any PHP notices or errors break it badly,
233 // developers simply must learn to watch error log.
234 define('NO_DEBUG_DISPLAY', true);
236 define('NO_DEBUG_DISPLAY', false);
240 // Some scripts such as upgrade may want to prevent output buffering
241 if (!defined('NO_OUTPUT_BUFFERING')) {
242 define('NO_OUTPUT_BUFFERING', false);
245 // PHPUnit tests need custom init
246 if (!defined('PHPUNIT_TEST')) {
247 define('PHPUNIT_TEST', false);
250 // Performance tests needs to always display performance info, even in redirections.
251 if (!defined('MDL_PERF_TEST')) {
252 define('MDL_PERF_TEST', false);
254 // We force the ones we need.
255 if (!defined('MDL_PERF')) {
256 define('MDL_PERF', true);
258 if (!defined('MDL_PERFDB')) {
259 define('MDL_PERFDB', true);
261 if (!defined('MDL_PERFTOFOOT')) {
262 define('MDL_PERFTOFOOT', true);
266 // When set to true MUC (Moodle caching) will be disabled as much as possible.
267 // A special cache factory will be used to handle this situation and will use special "disabled" equivalents objects.
268 // This ensure we don't attempt to read or create the config file, don't use stores, don't provide persistence or
269 // storage of any kind.
270 if (!defined('CACHE_DISABLE_ALL')) {
271 define('CACHE_DISABLE_ALL', false);
274 // When set to true MUC (Moodle caching) will not use any of the defined or default stores.
275 // The Cache API will continue to function however this will force the use of the cachestore_dummy so all requests
276 // will be interacting with a static property and will never go to the proper cache stores.
277 // Useful if you need to avoid the stores for one reason or another.
278 if (!defined('CACHE_DISABLE_STORES')) {
279 define('CACHE_DISABLE_STORES', false);
282 // Servers should define a default timezone in php.ini, but if they don't then make sure no errors are shown.
283 date_default_timezone_set(@date_default_timezone_get
());
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 // All web service requests have WS_SERVER == true.
309 if (!defined('WS_SERVER')) {
310 define('WS_SERVER', false);
313 // Detect CLI maintenance mode - this is useful when you need to mess with database, such as during upgrades
314 if (file_exists("$CFG->dataroot/climaintenance.html")) {
316 header('Content-type: text/html; charset=utf-8');
317 header('X-UA-Compatible: IE=edge');
318 /// Headers to make it not cacheable and json
319 header('Cache-Control: no-store, no-cache, must-revalidate');
320 header('Cache-Control: post-check=0, pre-check=0', false);
321 header('Pragma: no-cache');
322 header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
323 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
324 header('Accept-Ranges: none');
325 readfile("$CFG->dataroot/climaintenance.html");
328 if (!defined('CLI_MAINTENANCE')) {
329 define('CLI_MAINTENANCE', true);
333 if (!defined('CLI_MAINTENANCE')) {
334 define('CLI_MAINTENANCE', false);
339 // sometimes people use different PHP binary for web and CLI, make 100% sure they have the supported PHP version
340 if (version_compare(phpversion(), '5.6.5') < 0) {
341 $phpversion = phpversion();
342 // do NOT localise - lang strings would not work here and we CAN NOT move it to later place
343 echo "Moodle 3.2 or later requires at least PHP 5.6.5 (currently using version $phpversion).\n";
344 echo "Some servers may have multiple PHP versions installed, are you using the correct executable?\n";
349 // Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
350 if (!defined('AJAX_SCRIPT')) {
351 define('AJAX_SCRIPT', false);
354 // Exact version of currently used yui2 and 3 library.
355 $CFG->yui2version
= '2.9.0';
356 $CFG->yui3version
= '3.17.2';
358 // Patching the upstream YUI release.
359 // For important information on patching YUI modules, please see http://docs.moodle.org/dev/YUI/Patching.
360 // If we need to patch a YUI modules between official YUI releases, the yuipatchlevel will need to be manually
361 // incremented here. The module will also need to be listed in the yuipatchedmodules.
362 // When upgrading to a subsequent version of YUI, these should be reset back to 0 and an empty array.
363 $CFG->yuipatchlevel
= 0;
364 $CFG->yuipatchedmodules
= array(
367 if (!empty($CFG->disableonclickaddoninstall
)) {
368 // This config.php flag has been merged into another one.
369 $CFG->disableupdateautodeploy
= true;
372 // Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides.
373 if (!isset($CFG->config_php_settings
)) {
374 $CFG->config_php_settings
= (array)$CFG;
375 // Forced plugin settings override values from config_plugins table.
376 unset($CFG->config_php_settings
['forced_plugin_settings']);
377 if (!isset($CFG->forced_plugin_settings
)) {
378 $CFG->forced_plugin_settings
= array();
382 if (isset($CFG->debug
)) {
383 $CFG->debug
= (int)$CFG->debug
;
387 $CFG->debugdeveloper
= (($CFG->debug
& (E_ALL | E_STRICT
)) === (E_ALL | E_STRICT
)); // DEBUG_DEVELOPER is not available yet.
389 if (!defined('MOODLE_INTERNAL')) { // Necessary because cli installer has to define it earlier.
390 /** Used by library scripts to check they are being called by Moodle. */
391 define('MOODLE_INTERNAL', true);
394 // core_component can be used in any scripts, it does not need anything else.
395 require_once($CFG->libdir
.'/classes/component.php');
397 // special support for highly optimised scripts that do not need libraries and DB connection
398 if (defined('ABORT_AFTER_CONFIG')) {
399 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
400 // hide debugging if not enabled in config.php - we do not want to disclose sensitive info
401 error_reporting($CFG->debug
);
402 if (NO_DEBUG_DISPLAY
) {
403 // Some parts of Moodle cannot display errors and debug at all.
404 ini_set('display_errors', '0');
405 ini_set('log_errors', '1');
406 } else if (empty($CFG->debugdisplay
)) {
407 ini_set('display_errors', '0');
408 ini_set('log_errors', '1');
410 ini_set('display_errors', '1');
412 require_once("$CFG->dirroot/lib/configonlylib.php");
417 // Early profiling start, based exclusively on config.php $CFG settings
418 if (!empty($CFG->earlyprofilingenabled
)) {
419 require_once($CFG->libdir
. '/xhprof/xhprof_moodle.php');
424 * Database connection. Used for all access to the database.
425 * @global moodle_database $DB
431 * Moodle's wrapper round PHP's $_SESSION.
433 * @global object $SESSION
439 * Holds the user table record for the current user. Will be the 'guest'
440 * user record for people who are not logged in.
442 * $USER is stored in the session.
444 * Items found in the user record:
445 * - $USER->email - The user's email address.
446 * - $USER->id - The unique integer identified of this user in the 'user' table.
447 * - $USER->email - The user's email address.
448 * - $USER->firstname - The user's first name.
449 * - $USER->lastname - The user's last name.
450 * - $USER->username - The user's login username.
451 * - $USER->secret - The user's ?.
452 * - $USER->lang - The user's language choice.
454 * @global object $USER
460 * Frontpage course record
465 * A central store of information about the current page we are
466 * generating in response to the user's request.
468 * @global moodle_page $PAGE
474 * The current course. An alias for $PAGE->course.
475 * @global object $COURSE
481 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
482 * it to generate HTML for output.
484 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
485 * for the magic that does that. After $OUTPUT has been initialised, any attempt
486 * to change something that affects the current theme ($PAGE->course, logged in use,
487 * httpsrequried ... will result in an exception.)
489 * Please note the $OUTPUT is replacing the old global $THEME object.
491 * @global object $OUTPUT
497 * Full script path including all params, slash arguments, scheme and host.
499 * Note: Do NOT use for getting of current page URL or detection of https,
500 * instead use $PAGE->url or is_https().
502 * @global string $FULLME
508 * Script path including query string and slash arguments without host.
515 * $FULLME without slasharguments and query string.
516 * @global string $FULLSCRIPT
522 * Relative moodle script path '/course/view.php'
523 * @global string $SCRIPT
528 // Set httpswwwroot default value (this variable will replace $CFG->wwwroot
529 // inside some URLs used in HTTPSPAGEREQUIRED pages.
530 $CFG->httpswwwroot
= $CFG->wwwroot
;
532 require_once($CFG->libdir
.'/setuplib.php'); // Functions that MUST be loaded first
534 if (NO_OUTPUT_BUFFERING
) {
535 // we have to call this always before starting session because it discards headers!
536 disable_output_buffering();
539 // Increase memory limits if possible
540 raise_memory_limit(MEMORY_STANDARD
);
542 // Time to start counting
543 init_performance_info();
545 // Put $OUTPUT in place, so errors can be displayed.
546 $OUTPUT = new bootstrap_renderer();
548 // set handler for uncaught exceptions - equivalent to print_error() call
549 if (!PHPUNIT_TEST
or PHPUNIT_UTIL
) {
550 set_exception_handler('default_exception_handler');
551 set_error_handler('default_error_handler', E_ALL | E_STRICT
);
554 // Acceptance tests needs special output to capture the errors,
555 // but not necessary for behat CLI command.
556 if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST')) {
557 require_once(__DIR__
. '/behat/lib.php');
558 set_error_handler('behat_error_handler', E_ALL | E_STRICT
);
561 // If there are any errors in the standard libraries we want to know!
562 error_reporting(E_ALL | E_STRICT
);
564 // Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
565 // http://www.google.com/webmasters/faq.html#prefetchblock
566 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
567 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
568 echo('Prefetch request forbidden.');
572 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
573 //the problem is that we need specific version of quickforms and hacked excel files :-(
574 ini_set('include_path', $CFG->libdir
.'/pear' . PATH_SEPARATOR
. ini_get('include_path'));
576 // Register our classloader, in theory somebody might want to replace it to load other hacked core classes.
577 if (defined('COMPONENT_CLASSLOADER')) {
578 spl_autoload_register(COMPONENT_CLASSLOADER
);
580 spl_autoload_register('core_component::classloader');
583 // Remember the default PHP timezone, we will need it later.
584 core_date
::store_default_php_timezone();
586 // Load up standard libraries
587 require_once($CFG->libdir
.'/filterlib.php'); // Functions for filtering test as it is output
588 require_once($CFG->libdir
.'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
589 require_once($CFG->libdir
.'/weblib.php'); // Functions relating to HTTP and content
590 require_once($CFG->libdir
.'/outputlib.php'); // Functions for generating output
591 require_once($CFG->libdir
.'/navigationlib.php'); // Class for generating Navigation structure
592 require_once($CFG->libdir
.'/dmllib.php'); // Database access
593 require_once($CFG->libdir
.'/datalib.php'); // Legacy lib with a big-mix of functions.
594 require_once($CFG->libdir
.'/accesslib.php'); // Access control functions
595 require_once($CFG->libdir
.'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
596 require_once($CFG->libdir
.'/moodlelib.php'); // Other general-purpose functions
597 require_once($CFG->libdir
.'/enrollib.php'); // Enrolment related functions
598 require_once($CFG->libdir
.'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
599 require_once($CFG->libdir
.'/blocklib.php'); // Library for controlling blocks
600 require_once($CFG->libdir
.'/eventslib.php'); // Events functions
601 require_once($CFG->libdir
.'/grouplib.php'); // Groups functions
602 require_once($CFG->libdir
.'/sessionlib.php'); // All session and cookie related stuff
603 require_once($CFG->libdir
.'/editorlib.php'); // All text editor related functions and classes
604 require_once($CFG->libdir
.'/messagelib.php'); // Messagelib functions
605 require_once($CFG->libdir
.'/modinfolib.php'); // Cached information on course-module instances
606 require_once($CFG->dirroot
.'/cache/lib.php'); // Cache API
608 // make sure PHP is not severly misconfigured
609 setup_validate_php_configuration();
611 // Connect to the database
614 if (PHPUNIT_TEST
and !PHPUNIT_UTIL
) {
615 // make sure tests do not run in parallel
616 test_lock
::acquire('phpunit');
619 if ($dbhash = $DB->get_field('config', 'value', array('name'=>'phpunittest'))) {
621 phpunit_util
::reset_database();
623 } catch (Exception
$e) {
625 // we ned to reinit if reset fails
626 $DB->set_field('config', 'value', 'na', array('name'=>'phpunittest'));
632 // Load up any configuration from the config table or MUC cache.
634 phpunit_util
::initialise_cfg();
639 if (isset($CFG->debug
)) {
640 $CFG->debug
= (int)$CFG->debug
;
641 error_reporting($CFG->debug
);
645 $CFG->debugdeveloper
= (($CFG->debug
& DEBUG_DEVELOPER
) === DEBUG_DEVELOPER
);
647 // Find out if PHP configured to display warnings,
648 // this is a security problem because some moodle scripts may
649 // disclose sensitive information.
650 if (ini_get_bool('display_errors')) {
651 define('WARN_DISPLAY_ERRORS_ENABLED', true);
653 // If we want to display Moodle errors, then try and set PHP errors to match.
654 if (!isset($CFG->debugdisplay
)) {
655 // Keep it "as is" during installation.
656 } else if (NO_DEBUG_DISPLAY
) {
657 // Some parts of Moodle cannot display errors and debug at all.
658 ini_set('display_errors', '0');
659 ini_set('log_errors', '1');
660 } else if (empty($CFG->debugdisplay
)) {
661 ini_set('display_errors', '0');
662 ini_set('log_errors', '1');
664 // This is very problematic in XHTML strict mode!
665 ini_set('display_errors', '1');
668 // Register our shutdown manager, do NOT use register_shutdown_function().
669 core_shutdown_manager
::initialize();
671 // Verify upgrade is not running unless we are in a script that needs to execute in any case
672 if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning
)) {
673 if ($CFG->upgraderunning
< time()) {
674 unset_config('upgraderunning');
676 print_error('upgraderunning');
680 // enable circular reference collector in PHP 5.3,
681 // it helps a lot when using large complex OOP structures such as in amos or gradebook
682 if (function_exists('gc_enable')) {
686 // detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
687 if (!empty($CFG->version
) and $CFG->version
< 2007101509) {
688 print_error('upgraderequires19', 'error');
692 // Calculate and set $CFG->ostype to be used everywhere. Possible values are:
693 // - WINDOWS: for any Windows flavour.
694 // - UNIX: for the rest
695 // Also, $CFG->os can continue being used if more specialization is required
696 if (stristr(PHP_OS
, 'win') && !stristr(PHP_OS
, 'darwin')) {
697 $CFG->ostype
= 'WINDOWS';
699 $CFG->ostype
= 'UNIX';
703 // Configure ampersands in URLs
704 ini_set('arg_separator.output', '&');
706 // Work around for a PHP bug see MDL-11237
707 ini_set('pcre.backtrack_limit', 20971520); // 20 MB
709 // Work around for PHP7 bug #70110. See MDL-52475 .
710 if (ini_get('pcre.jit')) {
711 ini_set('pcre.jit', 0);
714 // Set PHP default timezone to server timezone.
715 core_date
::set_default_server_timezone();
717 // Location of standard files
718 $CFG->wordlist
= $CFG->libdir
.'/wordlist.txt';
719 $CFG->moddata
= 'moddata';
721 // neutralise nasty chars in PHP_SELF
722 if (isset($_SERVER['PHP_SELF'])) {
723 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
724 if ($phppos !== false) {
725 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+
4);
730 // initialise ME's - this must be done BEFORE starting of session!
733 // define SYSCONTEXTID in config.php if you want to save some queries,
734 // after install it must match the system context record id.
735 if (!defined('SYSCONTEXTID')) {
736 context_system
::instance();
739 // Defining the site - aka frontpage course
742 } catch (moodle_exception
$e) {
744 if (empty($CFG->version
)) {
745 $SITE = new stdClass();
747 $SITE->shortname
= null;
752 // And the 'default' course - this will usually get reset later in require_login() etc.
753 $COURSE = clone($SITE);
754 // Id of the frontpage course.
755 define('SITEID', $SITE->id
);
757 // init session prevention flag - this is defined on pages that do not want session
759 // no sessions in CLI scripts possible
760 define('NO_MOODLE_COOKIES', true);
762 } else if (WS_SERVER
) {
763 // No sessions possible in web services.
764 define('NO_MOODLE_COOKIES', true);
766 } else if (!defined('NO_MOODLE_COOKIES')) {
767 if (empty($CFG->version
) or $CFG->version
< 2009011900) {
768 // no session before sessions table gets created
769 define('NO_MOODLE_COOKIES', true);
770 } else if (CLI_SCRIPT
) {
771 // CLI scripts can not have session
772 define('NO_MOODLE_COOKIES', true);
774 define('NO_MOODLE_COOKIES', false);
778 // Start session and prepare global $SESSION, $USER.
779 if (empty($CFG->sessiontimeout
)) {
780 $CFG->sessiontimeout
= 7200;
782 \core\session\manager
::start();
784 // Set default content type and encoding, developers are still required to use
785 // echo $OUTPUT->header() everywhere, anything that gets set later should override these headers.
786 // This is intended to mitigate some security problems.
788 if (!core_useragent
::supports_json_contenttype()) {
789 // Some bloody old IE.
790 @header
('Content-type: text/plain; charset=utf-8');
791 @header
('X-Content-Type-Options: nosniff');
792 } else if (!empty($_FILES)) {
793 // Some ajax code may have problems with json and file uploads.
794 @header
('Content-type: text/plain; charset=utf-8');
796 @header
('Content-type: application/json; charset=utf-8');
798 } else if (!CLI_SCRIPT
) {
799 @header
('Content-type: text/html; charset=utf-8');
802 // Initialise some variables that are supposed to be set in config.php only.
803 if (!isset($CFG->filelifetime
)) {
804 $CFG->filelifetime
= 60*60*6;
807 // Late profiling, only happening if early one wasn't started
808 if (!empty($CFG->profilingenabled
)) {
809 require_once($CFG->libdir
. '/xhprof/xhprof_moodle.php');
813 // Hack to get around max_input_vars restrictions,
814 // we need to do this after session init to have some basic DDoS protection.
815 workaround_max_input_vars();
817 // Process theme change in the URL.
818 if (!empty($CFG->allowthemechangeonurl
) and !empty($_GET['theme'])) {
819 // we have to use _GET directly because we do not want this to interfere with _POST
820 $urlthemename = optional_param('theme', '', PARAM_PLUGIN
);
822 $themeconfig = theme_config
::load($urlthemename);
823 // Makes sure the theme can be loaded without errors.
824 if ($themeconfig->name
=== $urlthemename) {
825 $SESSION->theme
= $urlthemename;
827 unset($SESSION->theme
);
830 unset($urlthemename);
831 } catch (Exception
$e) {
832 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER
, $e->getTrace());
835 unset($urlthemename);
837 // Ensure a valid theme is set.
838 if (!isset($CFG->theme
)) {
839 $CFG->theme
= 'clean';
842 // Set language/locale of printed times. If user has chosen a language that
843 // that is different from the site language, then use the locale specified
844 // in the language file. Otherwise, if the admin hasn't specified a locale
845 // then use the one from the default language. Otherwise (and this is the
846 // majority of cases), use the stored locale specified by admin.
847 // note: do not accept lang parameter from POST
848 if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR
))) {
849 if (get_string_manager()->translation_exists($lang, false)) {
850 $SESSION->lang
= $lang;
855 // PARAM_SAFEDIR used instead of PARAM_LANG because using PARAM_LANG results
856 // in an empty string being returned when a non-existant language is specified,
857 // which would make it necessary to log out to undo the forcelang setting.
858 // With PARAM_SAFEDIR, it's possible to specify ?forcelang=none to drop the forcelang effect.
859 if ($forcelang = optional_param('forcelang', '', PARAM_SAFEDIR
)) {
861 && get_string_manager()->translation_exists($forcelang, false)
862 && has_capability('moodle/site:forcelanguage', context_system
::instance())) {
863 $SESSION->forcelang
= $forcelang;
864 } else if (isset($SESSION->forcelang
)) {
865 unset($SESSION->forcelang
);
870 setup_lang_from_browser();
872 if (empty($CFG->lang
)) {
873 if (empty($SESSION->lang
)) {
876 $CFG->lang
= $SESSION->lang
;
880 // Set the default site locale, a lot of the stuff may depend on this
881 // it is definitely too late to call this first in require_login()!
884 // Create the $PAGE global - this marks the PAGE and OUTPUT fully initialised, this MUST be done at the end of setup!
885 if (!empty($CFG->moodlepageclass
)) {
886 if (!empty($CFG->moodlepageclassfile
)) {
887 require_once($CFG->moodlepageclassfile
);
889 $classname = $CFG->moodlepageclass
;
891 $classname = 'moodle_page';
893 $PAGE = new $classname();
897 if (!empty($CFG->debugvalidators
) and !empty($CFG->guestloginbutton
)) {
898 if ($CFG->theme
== 'standard') { // Temporary measure to help with XHTML validation
899 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id
)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
900 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
901 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
902 if ($user = get_complete_user_data("username", "w3cvalidator")) {
903 $user->ignoresesskey
= true;
905 $user = guest_user();
907 \core\session\manager
::set_user($user);
913 // Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
914 // LogFormat to get the current logged in username in moodle.
915 if ($USER && function_exists('apache_note')
916 && !empty($CFG->apacheloguser
) && isset($USER->username
)) {
917 $apachelog_userid = $USER->id
;
918 $apachelog_username = clean_filename($USER->username
);
919 $apachelog_name = '';
920 if (isset($USER->firstname
)) {
921 // We can assume both will be set
922 // - even if to empty.
923 $apachelog_name = clean_filename($USER->firstname
. " " .
926 if (\core\session\manager
::is_loggedinas()) {
927 $realuser = \core\session\manager
::get_realuser();
928 $apachelog_username = clean_filename($realuser->username
." as ".$apachelog_username);
929 $apachelog_name = clean_filename($realuser->firstname
." ".$realuser->lastname
." as ".$apachelog_name);
930 $apachelog_userid = clean_filename($realuser->id
." as ".$apachelog_userid);
932 switch ($CFG->apacheloguser
) {
934 $logname = $apachelog_username;
937 $logname = $apachelog_name;
941 $logname = $apachelog_userid;
944 apache_note('MOODLEUSER', $logname);
947 // Ensure the urlrewriteclass is setup correctly (to avoid crippling site).
948 if (isset($CFG->urlrewriteclass
)) {
949 if (!class_exists($CFG->urlrewriteclass
)) {
950 debugging("urlrewriteclass {$CFG->urlrewriteclass} was not found, disabling.");
951 unset($CFG->urlrewriteclass
);
952 } else if (!in_array('core\output\url_rewriter', class_implements($CFG->urlrewriteclass
))) {
953 debugging("{$CFG->urlrewriteclass} does not implement core\output\url_rewriter, disabling.", DEBUG_DEVELOPER
);
954 unset($CFG->urlrewriteclass
);
958 // Use a custom script replacement if one exists
959 if (!empty($CFG->customscripts
)) {
960 if (($customscript = custom_script_path()) !== false) {
961 require ($customscript);
966 // no ip blocking, these are CLI only
967 } else if (CLI_SCRIPT
and !defined('WEB_CRON_EMULATED_CLI')) {
969 } else if (!empty($CFG->allowbeforeblock
)) { // allowed list processed before blocked list?
970 // in this case, ip in allowed list will be performed first
971 // for example, client IP is 192.168.1.1
972 // 192.168 subnet is an entry in allowed list
973 // 192.168.1.1 is banned in blocked list
974 // This ip will be banned finally
975 if (!empty($CFG->allowedip
)) {
976 if (!remoteip_in_list($CFG->allowedip
)) {
977 die(get_string('ipblocked', 'admin'));
980 // need further check, client ip may a part of
981 // allowed subnet, but a IP address are listed
983 if (!empty($CFG->blockedip
)) {
984 if (remoteip_in_list($CFG->blockedip
)) {
985 die(get_string('ipblocked', 'admin'));
990 // in this case, IPs in blocked list will be performed first
991 // for example, client IP is 192.168.1.1
992 // 192.168 subnet is an entry in blocked list
993 // 192.168.1.1 is allowed in allowed list
994 // This ip will be allowed finally
995 if (!empty($CFG->blockedip
)) {
996 if (remoteip_in_list($CFG->blockedip
)) {
997 // if the allowed ip list is not empty
998 // IPs are not included in the allowed list will be
1000 if (!empty($CFG->allowedip
)) {
1001 if (!remoteip_in_list($CFG->allowedip
)) {
1002 die(get_string('ipblocked', 'admin'));
1005 die(get_string('ipblocked', 'admin'));
1009 // if blocked list is null
1010 // allowed list should be tested
1011 if(!empty($CFG->allowedip
)) {
1012 if (!remoteip_in_list($CFG->allowedip
)) {
1013 die(get_string('ipblocked', 'admin'));
1019 // // try to detect IE6 and prevent gzip because it is extremely buggy browser
1020 if (!empty($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false) {
1021 ini_set('zlib.output_compression', 'Off');
1022 if (function_exists('apache_setenv')) {
1023 apache_setenv('no-gzip', 1);
1027 // Switch to CLI maintenance mode if required, we need to do it here after all the settings are initialised.
1028 if (isset($CFG->maintenance_later
) and $CFG->maintenance_later
<= time()) {
1029 if (!file_exists("$CFG->dataroot/climaintenance.html")) {
1030 require_once("$CFG->libdir/adminlib.php");
1031 enable_cli_maintenance_mode();
1033 unset_config('maintenance_later');
1036 } else if (!CLI_SCRIPT
) {
1037 redirect(new moodle_url('/'));
1041 // note: we can not block non utf-8 installations here, because empty mysql database
1042 // might be converted to utf-8 in admin/index.php during installation
1046 // this is a funny trick to make Eclipse believe that $OUTPUT and other globals
1047 // contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
1049 $DB = new moodle_database();
1050 $OUTPUT = new core_renderer(null, null);
1051 $PAGE = new moodle_page();