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->backuptempdir - Path to moodle's backup temp file directory on server's filesystem.
40 * - $CFG->tempdir - Path to moodle's temp file directory on server's filesystem.
41 * - $CFG->cachedir - Path to moodle's cache directory on server's filesystem (shared by cluster nodes).
42 * - $CFG->localcachedir - Path to moodle's local cache directory (not shared by cluster nodes).
43 * - $CFG->localrequestdir - Path to moodle's local temp request directory (not shared by cluster nodes).
48 global $CFG; // this should be done much earlier in config.php before creating new $CFG instance
51 if (defined('PHPUNIT_TEST') and PHPUNIT_TEST
) {
52 echo('There is a missing "global $CFG;" at the beginning of the config.php file.'."\n");
55 // this should never happen, maybe somebody is accessing this file directly...
60 // We can detect real dirroot path reliably since PHP 4.0.2,
61 // it can not be anything else, there is no point in having this in config.php
62 $CFG->dirroot
= dirname(__DIR__
);
64 // File permissions on created directories in the $CFG->dataroot
65 if (!isset($CFG->directorypermissions
)) {
66 $CFG->directorypermissions
= 02777; // Must be octal (that's why it's here)
68 if (!isset($CFG->filepermissions
)) {
69 $CFG->filepermissions
= ($CFG->directorypermissions
& 0666); // strip execute flags
71 // Better also set default umask because developers often forget to include directory
72 // permissions in mkdir() and chmod() after creating new files.
73 if (!isset($CFG->umaskpermissions
)) {
74 $CFG->umaskpermissions
= (($CFG->directorypermissions
& 0777) ^
0777);
76 umask($CFG->umaskpermissions
);
78 if (defined('BEHAT_SITE_RUNNING')) {
79 // We already switched to behat test site previously.
81 } else if (!empty($CFG->behat_wwwroot
) or !empty($CFG->behat_dataroot
) or !empty($CFG->behat_prefix
)) {
82 // The behat is configured on this server, we need to find out if this is the behat test
83 // site based on the URL used for access.
84 require_once(__DIR__
. '/../lib/behat/lib.php');
86 // Update config variables for parallel behat runs.
87 behat_update_vars_for_process();
89 // If behat is being installed for parallel run, then we modify params for parallel run only.
90 if (behat_is_test_site() && !(defined('BEHAT_PARALLEL_UTIL') && empty($CFG->behatrunprocess
))) {
93 // Checking the integrity of the provided $CFG->behat_* vars and the
94 // selected wwwroot to prevent conflicts with production and phpunit environments.
95 behat_check_config_vars();
97 // Check that the directory does not contains other things.
98 if (!file_exists("$CFG->behat_dataroot/behattestdir.txt")) {
99 if ($dh = opendir($CFG->behat_dataroot
)) {
100 while (($file = readdir($dh)) !== false) {
101 if ($file === 'behat' or $file === '.' or $file === '..' or $file === '.DS_Store' or is_numeric($file)) {
104 behat_error(BEHAT_EXITCODE_CONFIG
, "$CFG->behat_dataroot directory is not empty, ensure this is the " .
105 "directory where you want to install behat test dataroot");
112 if (defined('BEHAT_UTIL')) {
113 // Now we create dataroot directory structure for behat tests.
114 testing_initdataroot($CFG->behat_dataroot
, 'behat');
116 behat_error(BEHAT_EXITCODE_INSTALL
);
120 if (!defined('BEHAT_UTIL') and !defined('BEHAT_TEST')) {
121 // Somebody tries to access test site directly, tell them if not enabled.
122 $behatdir = preg_replace("#[/|\\\]" . BEHAT_PARALLEL_SITE_NAME
. "\d{0,}$#", '', $CFG->behat_dataroot
);
123 if (!file_exists($behatdir . '/test_environment_enabled.txt')) {
124 behat_error(BEHAT_EXITCODE_CONFIG
, 'Behat is configured but not enabled on this test site.');
128 // Constant used to inform that the behat test site is being used,
129 // this includes all the processes executed by the behat CLI command like
130 // the site reset, the steps executed by the browser drivers when simulating
131 // a user session and a real session when browsing manually to $CFG->behat_wwwroot
132 // like the browser driver does automatically.
133 // Different from BEHAT_TEST as only this last one can perform CLI
134 // actions like reset the site or use data generators.
135 define('BEHAT_SITE_RUNNING', true);
137 // Clean extra config.php settings.
138 behat_clean_init_config();
140 // Now we can begin switching $CFG->X for $CFG->behat_X.
141 $CFG->wwwroot
= $CFG->behat_wwwroot
;
142 $CFG->prefix
= $CFG->behat_prefix
;
143 $CFG->dataroot
= $CFG->behat_dataroot
;
147 // Normalise dataroot - we do not want any symbolic links, trailing / or any other weirdness there
148 if (!isset($CFG->dataroot
)) {
149 if (isset($_SERVER['REMOTE_ADDR'])) {
150 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
152 echo('Fatal error: $CFG->dataroot is not specified in config.php! Exiting.'."\n");
155 $CFG->dataroot
= realpath($CFG->dataroot
);
156 if ($CFG->dataroot
=== false) {
157 if (isset($_SERVER['REMOTE_ADDR'])) {
158 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
160 echo('Fatal error: $CFG->dataroot is not configured properly, directory does not exist or is not accessible! Exiting.'."\n");
162 } else if (!is_writable($CFG->dataroot
)) {
163 if (isset($_SERVER['REMOTE_ADDR'])) {
164 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
166 echo('Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.'."\n");
170 // wwwroot is mandatory
171 if (!isset($CFG->wwwroot
) or $CFG->wwwroot
=== 'http://example.com/moodle') {
172 if (isset($_SERVER['REMOTE_ADDR'])) {
173 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
175 echo('Fatal error: $CFG->wwwroot is not configured! Exiting.'."\n");
179 // Make sure there is some database table prefix.
180 if (!isset($CFG->prefix
)) {
184 // Define admin directory
185 if (!isset($CFG->admin
)) { // Just in case it isn't defined in config.php
186 $CFG->admin
= 'admin'; // This is relative to the wwwroot and dirroot
189 // Set up some paths.
190 $CFG->libdir
= $CFG->dirroot
.'/lib';
192 // Allow overriding of tempdir but be backwards compatible
193 if (!isset($CFG->tempdir
)) {
194 $CFG->tempdir
= "$CFG->dataroot/temp";
197 // Allow overriding of backuptempdir but be backwards compatible
198 if (!isset($CFG->backuptempdir
)) {
199 $CFG->backuptempdir
= "$CFG->tempdir/backup";
202 // Allow overriding of cachedir but be backwards compatible
203 if (!isset($CFG->cachedir
)) {
204 $CFG->cachedir
= "$CFG->dataroot/cache";
207 // Allow overriding of localcachedir.
208 if (!isset($CFG->localcachedir
)) {
209 $CFG->localcachedir
= "$CFG->dataroot/localcache";
212 // Allow overriding of localrequestdir.
213 if (!isset($CFG->localrequestdir
)) {
214 $CFG->localrequestdir
= sys_get_temp_dir() . '/requestdir';
217 // Location of all languages except core English pack.
218 if (!isset($CFG->langotherroot
)) {
219 $CFG->langotherroot
= $CFG->dataroot
.'/lang';
222 // Location of local lang pack customisations (dirs with _local suffix).
223 if (!isset($CFG->langlocalroot
)) {
224 $CFG->langlocalroot
= $CFG->dataroot
.'/lang';
227 // The current directory in PHP version 4.3.0 and above isn't necessarily the
228 // directory of the script when run from the command line. The require_once()
229 // would fail, so we'll have to chdir()
230 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
231 // do it only once - skip the second time when continuing after prevous abort
232 if (!defined('ABORT_AFTER_CONFIG') and !defined('ABORT_AFTER_CONFIG_CANCEL')) {
233 chdir(dirname($_SERVER['argv'][0]));
237 // sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
238 ini_set('precision', 14); // needed for upgrades and gradebook
239 ini_set('serialize_precision', 17); // Make float serialization consistent on all systems.
241 // Scripts may request no debug and error messages in output
242 // please note it must be defined before including the config.php script
243 // and in some cases you also need to set custom default exception handler
244 if (!defined('NO_DEBUG_DISPLAY')) {
245 if (defined('AJAX_SCRIPT') and AJAX_SCRIPT
) {
246 // Moodle AJAX scripts are expected to return json data, any PHP notices or errors break it badly,
247 // developers simply must learn to watch error log.
248 define('NO_DEBUG_DISPLAY', true);
250 define('NO_DEBUG_DISPLAY', false);
254 // Some scripts such as upgrade may want to prevent output buffering
255 if (!defined('NO_OUTPUT_BUFFERING')) {
256 define('NO_OUTPUT_BUFFERING', false);
259 // PHPUnit tests need custom init
260 if (!defined('PHPUNIT_TEST')) {
261 define('PHPUNIT_TEST', false);
264 // Performance tests needs to always display performance info, even in redirections.
265 if (!defined('MDL_PERF_TEST')) {
266 define('MDL_PERF_TEST', false);
268 // We force the ones we need.
269 if (!defined('MDL_PERF')) {
270 define('MDL_PERF', true);
272 if (!defined('MDL_PERFDB')) {
273 define('MDL_PERFDB', true);
275 if (!defined('MDL_PERFTOFOOT')) {
276 define('MDL_PERFTOFOOT', true);
280 // When set to true MUC (Moodle caching) will be disabled as much as possible.
281 // A special cache factory will be used to handle this situation and will use special "disabled" equivalents objects.
282 // This ensure we don't attempt to read or create the config file, don't use stores, don't provide persistence or
283 // storage of any kind.
284 if (!defined('CACHE_DISABLE_ALL')) {
285 define('CACHE_DISABLE_ALL', false);
288 // When set to true MUC (Moodle caching) will not use any of the defined or default stores.
289 // The Cache API will continue to function however this will force the use of the cachestore_dummy so all requests
290 // will be interacting with a static property and will never go to the proper cache stores.
291 // Useful if you need to avoid the stores for one reason or another.
292 if (!defined('CACHE_DISABLE_STORES')) {
293 define('CACHE_DISABLE_STORES', false);
296 // Servers should define a default timezone in php.ini, but if they don't then make sure no errors are shown.
297 date_default_timezone_set(@date_default_timezone_get
());
299 // Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
300 // In your new CLI scripts just add "define('CLI_SCRIPT', true);" before requiring config.php.
301 // Please note that one script can not be accessed from both CLI and web interface.
302 if (!defined('CLI_SCRIPT')) {
303 define('CLI_SCRIPT', false);
305 if (defined('WEB_CRON_EMULATED_CLI')) {
306 if (!isset($_SERVER['REMOTE_ADDR'])) {
307 echo('Web cron can not be executed as CLI script any more, please use admin/cli/cron.php instead'."\n");
310 } else if (isset($_SERVER['REMOTE_ADDR'])) {
312 echo('Command line scripts can not be executed from the web interface');
317 echo('Command line scripts must define CLI_SCRIPT before requiring config.php'."\n");
322 // All web service requests have WS_SERVER == true.
323 if (!defined('WS_SERVER')) {
324 define('WS_SERVER', false);
327 // Detect CLI maintenance mode - this is useful when you need to mess with database, such as during upgrades
328 if (file_exists("$CFG->dataroot/climaintenance.html")) {
330 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Moodle under maintenance');
331 header('Status: 503 Moodle under maintenance');
332 header('Retry-After: 300');
333 header('Content-type: text/html; charset=utf-8');
334 header('X-UA-Compatible: IE=edge');
335 /// Headers to make it not cacheable and json
336 header('Cache-Control: no-store, no-cache, must-revalidate');
337 header('Cache-Control: post-check=0, pre-check=0', false);
338 header('Pragma: no-cache');
339 header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
340 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
341 header('Accept-Ranges: none');
342 readfile("$CFG->dataroot/climaintenance.html");
345 if (!defined('CLI_MAINTENANCE')) {
346 define('CLI_MAINTENANCE', true);
350 if (!defined('CLI_MAINTENANCE')) {
351 define('CLI_MAINTENANCE', false);
355 // Sometimes people use different PHP binary for web and CLI, make 100% sure they have the supported PHP version.
356 if (version_compare(PHP_VERSION
, '5.6.5') < 0) {
357 $phpversion = PHP_VERSION
;
358 // Do NOT localise - lang strings would not work here and we CAN NOT move it to later place.
359 echo "Moodle 3.2 or later requires at least PHP 5.6.5 (currently using version $phpversion).\n";
360 echo "Some servers may have multiple PHP versions installed, are you using the correct executable?\n";
364 // Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
365 if (!defined('AJAX_SCRIPT')) {
366 define('AJAX_SCRIPT', false);
369 // Exact version of currently used yui2 and 3 library.
370 $CFG->yui2version
= '2.9.0';
371 $CFG->yui3version
= '3.17.2';
373 // Patching the upstream YUI release.
374 // For important information on patching YUI modules, please see http://docs.moodle.org/dev/YUI/Patching.
375 // If we need to patch a YUI modules between official YUI releases, the yuipatchlevel will need to be manually
376 // incremented here. The module will also need to be listed in the yuipatchedmodules.
377 // When upgrading to a subsequent version of YUI, these should be reset back to 0 and an empty array.
378 $CFG->yuipatchlevel
= 0;
379 $CFG->yuipatchedmodules
= array(
382 if (!empty($CFG->disableonclickaddoninstall
)) {
383 // This config.php flag has been merged into another one.
384 $CFG->disableupdateautodeploy
= true;
387 // Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides.
388 if (!isset($CFG->config_php_settings
)) {
389 $CFG->config_php_settings
= (array)$CFG;
390 // Forced plugin settings override values from config_plugins table.
391 unset($CFG->config_php_settings
['forced_plugin_settings']);
392 if (!isset($CFG->forced_plugin_settings
)) {
393 $CFG->forced_plugin_settings
= array();
397 if (isset($CFG->debug
)) {
398 $CFG->debug
= (int)$CFG->debug
;
402 $CFG->debugdeveloper
= (($CFG->debug
& (E_ALL | E_STRICT
)) === (E_ALL | E_STRICT
)); // DEBUG_DEVELOPER is not available yet.
404 if (!defined('MOODLE_INTERNAL')) { // Necessary because cli installer has to define it earlier.
405 /** Used by library scripts to check they are being called by Moodle. */
406 define('MOODLE_INTERNAL', true);
409 // core_component can be used in any scripts, it does not need anything else.
410 require_once($CFG->libdir
.'/classes/component.php');
412 // special support for highly optimised scripts that do not need libraries and DB connection
413 if (defined('ABORT_AFTER_CONFIG')) {
414 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
415 // hide debugging if not enabled in config.php - we do not want to disclose sensitive info
416 error_reporting($CFG->debug
);
417 if (NO_DEBUG_DISPLAY
) {
418 // Some parts of Moodle cannot display errors and debug at all.
419 ini_set('display_errors', '0');
420 ini_set('log_errors', '1');
421 } else if (empty($CFG->debugdisplay
)) {
422 ini_set('display_errors', '0');
423 ini_set('log_errors', '1');
425 ini_set('display_errors', '1');
427 require_once("$CFG->dirroot/lib/configonlylib.php");
432 // Early profiling start, based exclusively on config.php $CFG settings
433 if (!empty($CFG->earlyprofilingenabled
)) {
434 require_once($CFG->libdir
. '/xhprof/xhprof_moodle.php');
439 * Database connection. Used for all access to the database.
440 * @global moodle_database $DB
446 * Moodle's wrapper round PHP's $_SESSION.
448 * @global object $SESSION
454 * Holds the user table record for the current user. Will be the 'guest'
455 * user record for people who are not logged in.
457 * $USER is stored in the session.
459 * Items found in the user record:
460 * - $USER->email - The user's email address.
461 * - $USER->id - The unique integer identified of this user in the 'user' table.
462 * - $USER->email - The user's email address.
463 * - $USER->firstname - The user's first name.
464 * - $USER->lastname - The user's last name.
465 * - $USER->username - The user's login username.
466 * - $USER->secret - The user's ?.
467 * - $USER->lang - The user's language choice.
469 * @global object $USER
475 * Frontpage course record
480 * A central store of information about the current page we are
481 * generating in response to the user's request.
483 * @global moodle_page $PAGE
489 * The current course. An alias for $PAGE->course.
490 * @global object $COURSE
496 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
497 * it to generate HTML for output.
499 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
500 * for the magic that does that. After $OUTPUT has been initialised, any attempt
501 * to change something that affects the current theme ($PAGE->course, logged in use,
502 * httpsrequried ... will result in an exception.)
504 * Please note the $OUTPUT is replacing the old global $THEME object.
506 * @global object $OUTPUT
512 * Full script path including all params, slash arguments, scheme and host.
514 * Note: Do NOT use for getting of current page URL or detection of https,
515 * instead use $PAGE->url or is_https().
517 * @global string $FULLME
523 * Script path including query string and slash arguments without host.
530 * $FULLME without slasharguments and query string.
531 * @global string $FULLSCRIPT
537 * Relative moodle script path '/course/view.php'
538 * @global string $SCRIPT
543 // The httpswwwroot has been deprecated, we keep it as an alias for backwards compatibility with plugins only.
544 $CFG->httpswwwroot
= $CFG->wwwroot
;
546 require_once($CFG->libdir
.'/setuplib.php'); // Functions that MUST be loaded first
548 if (NO_OUTPUT_BUFFERING
) {
549 // we have to call this always before starting session because it discards headers!
550 disable_output_buffering();
553 // Increase memory limits if possible
554 raise_memory_limit(MEMORY_STANDARD
);
556 // Time to start counting
557 init_performance_info();
559 // Put $OUTPUT in place, so errors can be displayed.
560 $OUTPUT = new bootstrap_renderer();
562 // set handler for uncaught exceptions - equivalent to print_error() call
563 if (!PHPUNIT_TEST
or PHPUNIT_UTIL
) {
564 set_exception_handler('default_exception_handler');
565 set_error_handler('default_error_handler', E_ALL | E_STRICT
);
568 // Acceptance tests needs special output to capture the errors,
569 // but not necessary for behat CLI command and init script.
570 if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST') && !defined('BEHAT_UTIL')) {
571 require_once(__DIR__
. '/behat/lib.php');
572 set_error_handler('behat_error_handler', E_ALL | E_STRICT
);
575 if (defined('WS_SERVER') && WS_SERVER
) {
576 require_once($CFG->dirroot
. '/webservice/lib.php');
577 set_exception_handler('early_ws_exception_handler');
580 // If there are any errors in the standard libraries we want to know!
581 error_reporting(E_ALL | E_STRICT
);
583 // Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
584 // http://www.google.com/webmasters/faq.html#prefetchblock
585 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
586 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
587 echo('Prefetch request forbidden.');
591 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
592 //the problem is that we need specific version of quickforms and hacked excel files :-(
593 ini_set('include_path', $CFG->libdir
.'/pear' . PATH_SEPARATOR
. ini_get('include_path'));
595 // Register our classloader, in theory somebody might want to replace it to load other hacked core classes.
596 if (defined('COMPONENT_CLASSLOADER')) {
597 spl_autoload_register(COMPONENT_CLASSLOADER
);
599 spl_autoload_register('core_component::classloader');
602 // Remember the default PHP timezone, we will need it later.
603 core_date
::store_default_php_timezone();
605 // Load up standard libraries
606 require_once($CFG->libdir
.'/filterlib.php'); // Functions for filtering test as it is output
607 require_once($CFG->libdir
.'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
608 require_once($CFG->libdir
.'/weblib.php'); // Functions relating to HTTP and content
609 require_once($CFG->libdir
.'/outputlib.php'); // Functions for generating output
610 require_once($CFG->libdir
.'/navigationlib.php'); // Class for generating Navigation structure
611 require_once($CFG->libdir
.'/dmllib.php'); // Database access
612 require_once($CFG->libdir
.'/datalib.php'); // Legacy lib with a big-mix of functions.
613 require_once($CFG->libdir
.'/accesslib.php'); // Access control functions
614 require_once($CFG->libdir
.'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
615 require_once($CFG->libdir
.'/moodlelib.php'); // Other general-purpose functions
616 require_once($CFG->libdir
.'/enrollib.php'); // Enrolment related functions
617 require_once($CFG->libdir
.'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
618 require_once($CFG->libdir
.'/blocklib.php'); // Library for controlling blocks
619 require_once($CFG->libdir
.'/grouplib.php'); // Groups functions
620 require_once($CFG->libdir
.'/sessionlib.php'); // All session and cookie related stuff
621 require_once($CFG->libdir
.'/editorlib.php'); // All text editor related functions and classes
622 require_once($CFG->libdir
.'/messagelib.php'); // Messagelib functions
623 require_once($CFG->libdir
.'/modinfolib.php'); // Cached information on course-module instances
624 require_once($CFG->dirroot
.'/cache/lib.php'); // Cache API
626 // make sure PHP is not severly misconfigured
627 setup_validate_php_configuration();
629 // Connect to the database
632 if (PHPUNIT_TEST
and !PHPUNIT_UTIL
) {
633 // Make sure tests do not run in parallel.
635 if (phpunit_util
::is_in_isolated_process()) {
636 $suffix = '.isolated';
638 test_lock
::acquire('phpunit', $suffix);
641 if ($dbhash = $DB->get_field('config', 'value', array('name'=>'phpunittest'))) {
643 phpunit_util
::reset_database();
645 } catch (Exception
$e) {
647 // we ned to reinit if reset fails
648 $DB->set_field('config', 'value', 'na', array('name'=>'phpunittest'));
654 // Load up any configuration from the config table or MUC cache.
656 phpunit_util
::initialise_cfg();
661 if (isset($CFG->debug
)) {
662 $CFG->debug
= (int)$CFG->debug
;
663 error_reporting($CFG->debug
);
667 $CFG->debugdeveloper
= (($CFG->debug
& DEBUG_DEVELOPER
) === DEBUG_DEVELOPER
);
669 // Find out if PHP configured to display warnings,
670 // this is a security problem because some moodle scripts may
671 // disclose sensitive information.
672 if (ini_get_bool('display_errors')) {
673 define('WARN_DISPLAY_ERRORS_ENABLED', true);
675 // If we want to display Moodle errors, then try and set PHP errors to match.
676 if (!isset($CFG->debugdisplay
)) {
677 // Keep it "as is" during installation.
678 } else if (NO_DEBUG_DISPLAY
) {
679 // Some parts of Moodle cannot display errors and debug at all.
680 ini_set('display_errors', '0');
681 ini_set('log_errors', '1');
682 } else if (empty($CFG->debugdisplay
)) {
683 ini_set('display_errors', '0');
684 ini_set('log_errors', '1');
686 // This is very problematic in XHTML strict mode!
687 ini_set('display_errors', '1');
690 // Register our shutdown manager, do NOT use register_shutdown_function().
691 core_shutdown_manager
::initialize();
693 // Verify upgrade is not running unless we are in a script that needs to execute in any case
694 if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning
)) {
695 if ($CFG->upgraderunning
< time()) {
696 unset_config('upgraderunning');
698 print_error('upgraderunning');
702 // enable circular reference collector in PHP 5.3,
703 // it helps a lot when using large complex OOP structures such as in amos or gradebook
704 if (function_exists('gc_enable')) {
708 // detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
709 if (!empty($CFG->version
) and $CFG->version
< 2007101509) {
710 print_error('upgraderequires19', 'error');
714 // Calculate and set $CFG->ostype to be used everywhere. Possible values are:
715 // - WINDOWS: for any Windows flavour.
716 // - UNIX: for the rest
717 // Also, $CFG->os can continue being used if more specialization is required
718 if (stristr(PHP_OS
, 'win') && !stristr(PHP_OS
, 'darwin')) {
719 $CFG->ostype
= 'WINDOWS';
721 $CFG->ostype
= 'UNIX';
725 // Configure ampersands in URLs
726 ini_set('arg_separator.output', '&');
728 // Work around for a PHP bug see MDL-11237
729 ini_set('pcre.backtrack_limit', 20971520); // 20 MB
731 // Work around for PHP7 bug #70110. See MDL-52475 .
732 if (ini_get('pcre.jit')) {
733 ini_set('pcre.jit', 0);
736 // Set PHP default timezone to server timezone.
737 core_date
::set_default_server_timezone();
739 // Location of standard files
740 $CFG->wordlist
= $CFG->libdir
.'/wordlist.txt';
741 $CFG->moddata
= 'moddata';
743 // neutralise nasty chars in PHP_SELF
744 if (isset($_SERVER['PHP_SELF'])) {
745 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
746 if ($phppos !== false) {
747 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+
4);
752 // initialise ME's - this must be done BEFORE starting of session!
755 // define SYSCONTEXTID in config.php if you want to save some queries,
756 // after install it must match the system context record id.
757 if (!defined('SYSCONTEXTID')) {
758 context_system
::instance();
761 // Defining the site - aka frontpage course
764 } catch (moodle_exception
$e) {
766 if (empty($CFG->version
)) {
767 $SITE = new stdClass();
769 $SITE->shortname
= null;
774 // And the 'default' course - this will usually get reset later in require_login() etc.
775 $COURSE = clone($SITE);
776 // Id of the frontpage course.
777 define('SITEID', $SITE->id
);
779 // init session prevention flag - this is defined on pages that do not want session
781 // no sessions in CLI scripts possible
782 define('NO_MOODLE_COOKIES', true);
784 } else if (WS_SERVER
) {
785 // No sessions possible in web services.
786 define('NO_MOODLE_COOKIES', true);
788 } else if (!defined('NO_MOODLE_COOKIES')) {
789 if (empty($CFG->version
) or $CFG->version
< 2009011900) {
790 // no session before sessions table gets created
791 define('NO_MOODLE_COOKIES', true);
792 } else if (CLI_SCRIPT
) {
793 // CLI scripts can not have session
794 define('NO_MOODLE_COOKIES', true);
796 define('NO_MOODLE_COOKIES', false);
800 // Start session and prepare global $SESSION, $USER.
801 if (empty($CFG->sessiontimeout
)) {
802 $CFG->sessiontimeout
= 8 * 60 * 60;
804 \core\session\manager
::start();
806 // Set default content type and encoding, developers are still required to use
807 // echo $OUTPUT->header() everywhere, anything that gets set later should override these headers.
808 // This is intended to mitigate some security problems.
810 if (!core_useragent
::supports_json_contenttype()) {
811 // Some bloody old IE.
812 @header
('Content-type: text/plain; charset=utf-8');
813 @header
('X-Content-Type-Options: nosniff');
814 } else if (!empty($_FILES)) {
815 // Some ajax code may have problems with json and file uploads.
816 @header
('Content-type: text/plain; charset=utf-8');
818 @header
('Content-type: application/json; charset=utf-8');
820 } else if (!CLI_SCRIPT
) {
821 @header
('Content-type: text/html; charset=utf-8');
824 // Initialise some variables that are supposed to be set in config.php only.
825 if (!isset($CFG->filelifetime
)) {
826 $CFG->filelifetime
= 60*60*6;
829 // Late profiling, only happening if early one wasn't started
830 if (!empty($CFG->profilingenabled
)) {
831 require_once($CFG->libdir
. '/xhprof/xhprof_moodle.php');
835 // Hack to get around max_input_vars restrictions,
836 // we need to do this after session init to have some basic DDoS protection.
837 workaround_max_input_vars();
839 // Process theme change in the URL.
840 if (!empty($CFG->allowthemechangeonurl
) and !empty($_GET['theme'])) {
841 // we have to use _GET directly because we do not want this to interfere with _POST
842 $urlthemename = optional_param('theme', '', PARAM_PLUGIN
);
844 $themeconfig = theme_config
::load($urlthemename);
845 // Makes sure the theme can be loaded without errors.
846 if ($themeconfig->name
=== $urlthemename) {
847 $SESSION->theme
= $urlthemename;
849 unset($SESSION->theme
);
852 unset($urlthemename);
853 } catch (Exception
$e) {
854 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER
, $e->getTrace());
857 unset($urlthemename);
859 // Ensure a valid theme is set.
860 if (!isset($CFG->theme
)) {
861 $CFG->theme
= 'boost';
864 // Set language/locale of printed times. If user has chosen a language that
865 // that is different from the site language, then use the locale specified
866 // in the language file. Otherwise, if the admin hasn't specified a locale
867 // then use the one from the default language. Otherwise (and this is the
868 // majority of cases), use the stored locale specified by admin.
869 // note: do not accept lang parameter from POST
870 if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR
))) {
871 if (get_string_manager()->translation_exists($lang, false)) {
872 $SESSION->lang
= $lang;
877 // PARAM_SAFEDIR used instead of PARAM_LANG because using PARAM_LANG results
878 // in an empty string being returned when a non-existant language is specified,
879 // which would make it necessary to log out to undo the forcelang setting.
880 // With PARAM_SAFEDIR, it's possible to specify ?forcelang=none to drop the forcelang effect.
881 if ($forcelang = optional_param('forcelang', '', PARAM_SAFEDIR
)) {
883 && get_string_manager()->translation_exists($forcelang, false)
884 && has_capability('moodle/site:forcelanguage', context_system
::instance())) {
885 $SESSION->forcelang
= $forcelang;
886 } else if (isset($SESSION->forcelang
)) {
887 unset($SESSION->forcelang
);
892 setup_lang_from_browser();
894 if (empty($CFG->lang
)) {
895 if (empty($SESSION->lang
)) {
898 $CFG->lang
= $SESSION->lang
;
902 // Set the default site locale, a lot of the stuff may depend on this
903 // it is definitely too late to call this first in require_login()!
906 // Create the $PAGE global - this marks the PAGE and OUTPUT fully initialised, this MUST be done at the end of setup!
907 if (!empty($CFG->moodlepageclass
)) {
908 if (!empty($CFG->moodlepageclassfile
)) {
909 require_once($CFG->moodlepageclassfile
);
911 $classname = $CFG->moodlepageclass
;
913 $classname = 'moodle_page';
915 $PAGE = new $classname();
919 if (!empty($CFG->debugvalidators
) and !empty($CFG->guestloginbutton
)) {
920 if ($CFG->theme
== 'standard') { // Temporary measure to help with XHTML validation
921 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id
)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
922 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
923 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
924 if ($user = get_complete_user_data("username", "w3cvalidator")) {
925 $user->ignoresesskey
= true;
927 $user = guest_user();
929 \core\session\manager
::set_user($user);
935 // Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
936 // LogFormat to get the current logged in username in moodle.
937 // Alternatvely for other web servers a header X-MOODLEUSER can be set which
938 // can be using in the logfile and stripped out if needed.
939 set_access_log_user();
942 // Ensure the urlrewriteclass is setup correctly (to avoid crippling site).
943 if (isset($CFG->urlrewriteclass
)) {
944 if (!class_exists($CFG->urlrewriteclass
)) {
945 debugging("urlrewriteclass {$CFG->urlrewriteclass} was not found, disabling.");
946 unset($CFG->urlrewriteclass
);
947 } else if (!in_array('core\output\url_rewriter', class_implements($CFG->urlrewriteclass
))) {
948 debugging("{$CFG->urlrewriteclass} does not implement core\output\url_rewriter, disabling.", DEBUG_DEVELOPER
);
949 unset($CFG->urlrewriteclass
);
953 // Use a custom script replacement if one exists
954 if (!empty($CFG->customscripts
)) {
955 if (($customscript = custom_script_path()) !== false) {
956 require ($customscript);
961 // no ip blocking, these are CLI only
962 } else if (CLI_SCRIPT
and !defined('WEB_CRON_EMULATED_CLI')) {
964 } else if (!empty($CFG->allowbeforeblock
)) { // allowed list processed before blocked list?
965 // in this case, ip in allowed list will be performed first
966 // for example, client IP is 192.168.1.1
967 // 192.168 subnet is an entry in allowed list
968 // 192.168.1.1 is banned in blocked list
969 // This ip will be banned finally
970 if (!empty($CFG->allowedip
)) {
971 if (!remoteip_in_list($CFG->allowedip
)) {
972 die(get_string('ipblocked', 'admin'));
975 // need further check, client ip may a part of
976 // allowed subnet, but a IP address are listed
978 if (!empty($CFG->blockedip
)) {
979 if (remoteip_in_list($CFG->blockedip
)) {
980 die(get_string('ipblocked', 'admin'));
985 // in this case, IPs in blocked list will be performed first
986 // for example, client IP is 192.168.1.1
987 // 192.168 subnet is an entry in blocked list
988 // 192.168.1.1 is allowed in allowed list
989 // This ip will be allowed finally
990 if (!empty($CFG->blockedip
)) {
991 if (remoteip_in_list($CFG->blockedip
)) {
992 // if the allowed ip list is not empty
993 // IPs are not included in the allowed list will be
995 if (!empty($CFG->allowedip
)) {
996 if (!remoteip_in_list($CFG->allowedip
)) {
997 die(get_string('ipblocked', 'admin'));
1000 die(get_string('ipblocked', 'admin'));
1004 // if blocked list is null
1005 // allowed list should be tested
1006 if(!empty($CFG->allowedip
)) {
1007 if (!remoteip_in_list($CFG->allowedip
)) {
1008 die(get_string('ipblocked', 'admin'));
1014 // // try to detect IE6 and prevent gzip because it is extremely buggy browser
1015 if (!empty($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false) {
1016 ini_set('zlib.output_compression', 'Off');
1017 if (function_exists('apache_setenv')) {
1018 apache_setenv('no-gzip', 1);
1022 // Switch to CLI maintenance mode if required, we need to do it here after all the settings are initialised.
1023 if (isset($CFG->maintenance_later
) and $CFG->maintenance_later
<= time()) {
1024 if (!file_exists("$CFG->dataroot/climaintenance.html")) {
1025 require_once("$CFG->libdir/adminlib.php");
1026 enable_cli_maintenance_mode();
1028 unset_config('maintenance_later');
1031 } else if (!CLI_SCRIPT
) {
1032 redirect(new moodle_url('/'));
1036 // Add behat_shutdown_function to shutdown manager, so we can capture php errors,
1037 // but not necessary for behat CLI command as it's being captured by behat process.
1038 if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST')) {
1039 core_shutdown_manager
::register_function('behat_shutdown_function');
1042 // note: we can not block non utf-8 installations here, because empty mysql database
1043 // might be converted to utf-8 in admin/index.php during installation
1047 // this is a funny trick to make Eclipse believe that $OUTPUT and other globals
1048 // contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
1050 $DB = new moodle_database();
1051 $OUTPUT = new core_renderer(null, null);
1052 $PAGE = new moodle_page();
1055 // Allow plugins to callback as soon possible after setup.php is loaded.
1056 $pluginswithfunction = get_plugins_with_function('after_config', 'lib.php');
1057 foreach ($pluginswithfunction as $plugins) {
1058 foreach ($plugins as $function) {
1061 } catch (Throwable
$e) {
1062 debugging("Exception calling '$function'", DEBUG_DEVELOPER
, $e->getTrace());