Merge branch 'MDL-36056-master-enrolkeywhitespace' of git://github.com/mudrd8mz/moodle
[moodle.git] / lib / setup.php
blob29cf769bf7311d64f6c34fe60d7d289706887a0a
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * setup.php - Sets up sessions, connects to databases and so on
21 * Normally this is only called by the main config.php file
22 * Normally this file does not need to be edited.
24 * @package core
25 * @subpackage lib
26 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 /**
31 * Holds the core settings that affect how Moodle works. Some of its fields
32 * are set in config.php, and the rest are loaded from the config table.
34 * Some typical settings in the $CFG global:
35 * - $CFG->wwwroot - Path to moodle index directory in url format.
36 * - $CFG->dataroot - Path to moodle data files directory on server's filesystem.
37 * - $CFG->dirroot - Path to moodle's library folder on server's filesystem.
38 * - $CFG->libdir - Path to moodle's library folder on server's filesystem.
39 * - $CFG->tempdir - Path to moodle's temp file directory on server's filesystem.
40 * - $CFG->cachedir - Path to moodle's cache directory on server's filesystem (shared by cluster nodes).
41 * - $CFG->localcachedir - Path to moodle's local cache directory (not shared by cluster nodes).
43 * @global object $CFG
44 * @name $CFG
46 global $CFG; // this should be done much earlier in config.php before creating new $CFG instance
48 if (!isset($CFG)) {
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");
51 exit(1);
52 } else {
53 // this should never happen, maybe somebody is accessing this file directly...
54 exit(1);
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 being installed for parallel run, then we modify params for parallel run only.
88 if (behat_is_test_site() && !(defined('BEHAT_PARALLEL_UTIL') && empty($CFG->behatrunprocess))) {
89 clearstatcache();
91 // Checking the integrity of the provided $CFG->behat_* vars and the
92 // selected wwwroot to prevent conflicts with production and phpunit environments.
93 behat_check_config_vars();
95 // Check that the directory does not contains other things.
96 if (!file_exists("$CFG->behat_dataroot/behattestdir.txt")) {
97 if ($dh = opendir($CFG->behat_dataroot)) {
98 while (($file = readdir($dh)) !== false) {
99 if ($file === 'behat' or $file === '.' or $file === '..' or $file === '.DS_Store' or is_numeric($file)) {
100 continue;
102 behat_error(BEHAT_EXITCODE_CONFIG, "$CFG->behat_dataroot directory is not empty, ensure this is the " .
103 "directory where you want to install behat test dataroot");
105 closedir($dh);
106 unset($dh);
107 unset($file);
110 if (defined('BEHAT_UTIL')) {
111 // Now we create dataroot directory structure for behat tests.
112 testing_initdataroot($CFG->behat_dataroot, 'behat');
113 } else {
114 behat_error(BEHAT_EXITCODE_INSTALL);
118 if (!defined('BEHAT_UTIL') and !defined('BEHAT_TEST')) {
119 // Somebody tries to access test site directly, tell them if not enabled.
120 $behatdir = preg_replace("#[/|\\\]" . BEHAT_PARALLEL_SITE_NAME . "\d{0,}$#", '', $CFG->behat_dataroot);
121 if (!file_exists($behatdir . '/test_environment_enabled.txt')) {
122 behat_error(BEHAT_EXITCODE_CONFIG, 'Behat is configured but not enabled on this test site.');
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 behat_clean_init_config();
138 // Now we can begin switching $CFG->X for $CFG->behat_X.
139 $CFG->wwwroot = $CFG->behat_wwwroot;
140 $CFG->prefix = $CFG->behat_prefix;
141 $CFG->dataroot = $CFG->behat_dataroot;
145 // Normalise dataroot - we do not want any symbolic links, trailing / or any other weirdness there
146 if (!isset($CFG->dataroot)) {
147 if (isset($_SERVER['REMOTE_ADDR'])) {
148 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
150 echo('Fatal error: $CFG->dataroot is not specified in config.php! Exiting.'."\n");
151 exit(1);
153 $CFG->dataroot = realpath($CFG->dataroot);
154 if ($CFG->dataroot === false) {
155 if (isset($_SERVER['REMOTE_ADDR'])) {
156 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
158 echo('Fatal error: $CFG->dataroot is not configured properly, directory does not exist or is not accessible! Exiting.'."\n");
159 exit(1);
160 } else if (!is_writable($CFG->dataroot)) {
161 if (isset($_SERVER['REMOTE_ADDR'])) {
162 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
164 echo('Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.'."\n");
165 exit(1);
168 // wwwroot is mandatory
169 if (!isset($CFG->wwwroot) or $CFG->wwwroot === 'http://example.com/moodle') {
170 if (isset($_SERVER['REMOTE_ADDR'])) {
171 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
173 echo('Fatal error: $CFG->wwwroot is not configured! Exiting.'."\n");
174 exit(1);
177 // Make sure there is some database table prefix.
178 if (!isset($CFG->prefix)) {
179 $CFG->prefix = '';
182 // Define admin directory
183 if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
184 $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
187 // Set up some paths.
188 $CFG->libdir = $CFG->dirroot .'/lib';
190 // Allow overriding of tempdir but be backwards compatible
191 if (!isset($CFG->tempdir)) {
192 $CFG->tempdir = "$CFG->dataroot/temp";
195 // Allow overriding of cachedir but be backwards compatible
196 if (!isset($CFG->cachedir)) {
197 $CFG->cachedir = "$CFG->dataroot/cache";
200 // Allow overriding of localcachedir.
201 if (!isset($CFG->localcachedir)) {
202 $CFG->localcachedir = "$CFG->dataroot/localcache";
205 // Location of all languages except core English pack.
206 if (!isset($CFG->langotherroot)) {
207 $CFG->langotherroot = $CFG->dataroot.'/lang';
210 // Location of local lang pack customisations (dirs with _local suffix).
211 if (!isset($CFG->langlocalroot)) {
212 $CFG->langlocalroot = $CFG->dataroot.'/lang';
215 // The current directory in PHP version 4.3.0 and above isn't necessarily the
216 // directory of the script when run from the command line. The require_once()
217 // would fail, so we'll have to chdir()
218 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
219 // do it only once - skip the second time when continuing after prevous abort
220 if (!defined('ABORT_AFTER_CONFIG') and !defined('ABORT_AFTER_CONFIG_CANCEL')) {
221 chdir(dirname($_SERVER['argv'][0]));
225 // sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
226 ini_set('precision', 14); // needed for upgrades and gradebook
227 ini_set('serialize_precision', 17); // Make float serialization consistent on all systems.
229 // Scripts may request no debug and error messages in output
230 // please note it must be defined before including the config.php script
231 // and in some cases you also need to set custom default exception handler
232 if (!defined('NO_DEBUG_DISPLAY')) {
233 if (defined('AJAX_SCRIPT') and AJAX_SCRIPT) {
234 // Moodle AJAX scripts are expected to return json data, any PHP notices or errors break it badly,
235 // developers simply must learn to watch error log.
236 define('NO_DEBUG_DISPLAY', true);
237 } else {
238 define('NO_DEBUG_DISPLAY', false);
242 // Some scripts such as upgrade may want to prevent output buffering
243 if (!defined('NO_OUTPUT_BUFFERING')) {
244 define('NO_OUTPUT_BUFFERING', false);
247 // PHPUnit tests need custom init
248 if (!defined('PHPUNIT_TEST')) {
249 define('PHPUNIT_TEST', false);
252 // Performance tests needs to always display performance info, even in redirections.
253 if (!defined('MDL_PERF_TEST')) {
254 define('MDL_PERF_TEST', false);
255 } else {
256 // We force the ones we need.
257 if (!defined('MDL_PERF')) {
258 define('MDL_PERF', true);
260 if (!defined('MDL_PERFDB')) {
261 define('MDL_PERFDB', true);
263 if (!defined('MDL_PERFTOFOOT')) {
264 define('MDL_PERFTOFOOT', true);
268 // When set to true MUC (Moodle caching) will be disabled as much as possible.
269 // A special cache factory will be used to handle this situation and will use special "disabled" equivalents objects.
270 // This ensure we don't attempt to read or create the config file, don't use stores, don't provide persistence or
271 // storage of any kind.
272 if (!defined('CACHE_DISABLE_ALL')) {
273 define('CACHE_DISABLE_ALL', false);
276 // When set to true MUC (Moodle caching) will not use any of the defined or default stores.
277 // The Cache API will continue to function however this will force the use of the cachestore_dummy so all requests
278 // will be interacting with a static property and will never go to the proper cache stores.
279 // Useful if you need to avoid the stores for one reason or another.
280 if (!defined('CACHE_DISABLE_STORES')) {
281 define('CACHE_DISABLE_STORES', false);
284 // Servers should define a default timezone in php.ini, but if they don't then make sure no errors are shown.
285 date_default_timezone_set(@date_default_timezone_get());
287 // Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
288 // In your new CLI scripts just add "define('CLI_SCRIPT', true);" before requiring config.php.
289 // Please note that one script can not be accessed from both CLI and web interface.
290 if (!defined('CLI_SCRIPT')) {
291 define('CLI_SCRIPT', false);
293 if (defined('WEB_CRON_EMULATED_CLI')) {
294 if (!isset($_SERVER['REMOTE_ADDR'])) {
295 echo('Web cron can not be executed as CLI script any more, please use admin/cli/cron.php instead'."\n");
296 exit(1);
298 } else if (isset($_SERVER['REMOTE_ADDR'])) {
299 if (CLI_SCRIPT) {
300 echo('Command line scripts can not be executed from the web interface');
301 exit(1);
303 } else {
304 if (!CLI_SCRIPT) {
305 echo('Command line scripts must define CLI_SCRIPT before requiring config.php'."\n");
306 exit(1);
310 // All web service requests have WS_SERVER == true.
311 if (!defined('WS_SERVER')) {
312 define('WS_SERVER', false);
315 // Detect CLI maintenance mode - this is useful when you need to mess with database, such as during upgrades
316 if (file_exists("$CFG->dataroot/climaintenance.html")) {
317 if (!CLI_SCRIPT) {
318 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Moodle under maintenance');
319 header('Status: 503 Moodle under maintenance');
320 header('Retry-After: 300');
321 header('Content-type: text/html; charset=utf-8');
322 header('X-UA-Compatible: IE=edge');
323 /// Headers to make it not cacheable and json
324 header('Cache-Control: no-store, no-cache, must-revalidate');
325 header('Cache-Control: post-check=0, pre-check=0', false);
326 header('Pragma: no-cache');
327 header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
328 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
329 header('Accept-Ranges: none');
330 readfile("$CFG->dataroot/climaintenance.html");
331 die;
332 } else {
333 if (!defined('CLI_MAINTENANCE')) {
334 define('CLI_MAINTENANCE', true);
337 } else {
338 if (!defined('CLI_MAINTENANCE')) {
339 define('CLI_MAINTENANCE', false);
343 // Sometimes people use different PHP binary for web and CLI, make 100% sure they have the supported PHP version.
344 if (version_compare(PHP_VERSION, '5.6.5') < 0) {
345 $phpversion = PHP_VERSION;
346 // Do NOT localise - lang strings would not work here and we CAN NOT move it to later place.
347 echo "Moodle 3.2 or later requires at least PHP 5.6.5 (currently using version $phpversion).\n";
348 echo "Some servers may have multiple PHP versions installed, are you using the correct executable?\n";
349 exit(1);
352 // Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
353 if (!defined('AJAX_SCRIPT')) {
354 define('AJAX_SCRIPT', false);
357 // Exact version of currently used yui2 and 3 library.
358 $CFG->yui2version = '2.9.0';
359 $CFG->yui3version = '3.17.2';
361 // Patching the upstream YUI release.
362 // For important information on patching YUI modules, please see http://docs.moodle.org/dev/YUI/Patching.
363 // If we need to patch a YUI modules between official YUI releases, the yuipatchlevel will need to be manually
364 // incremented here. The module will also need to be listed in the yuipatchedmodules.
365 // When upgrading to a subsequent version of YUI, these should be reset back to 0 and an empty array.
366 $CFG->yuipatchlevel = 0;
367 $CFG->yuipatchedmodules = array(
370 if (!empty($CFG->disableonclickaddoninstall)) {
371 // This config.php flag has been merged into another one.
372 $CFG->disableupdateautodeploy = true;
375 // Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides.
376 if (!isset($CFG->config_php_settings)) {
377 $CFG->config_php_settings = (array)$CFG;
378 // Forced plugin settings override values from config_plugins table.
379 unset($CFG->config_php_settings['forced_plugin_settings']);
380 if (!isset($CFG->forced_plugin_settings)) {
381 $CFG->forced_plugin_settings = array();
385 if (isset($CFG->debug)) {
386 $CFG->debug = (int)$CFG->debug;
387 } else {
388 $CFG->debug = 0;
390 $CFG->debugdeveloper = (($CFG->debug & (E_ALL | E_STRICT)) === (E_ALL | E_STRICT)); // DEBUG_DEVELOPER is not available yet.
392 if (!defined('MOODLE_INTERNAL')) { // Necessary because cli installer has to define it earlier.
393 /** Used by library scripts to check they are being called by Moodle. */
394 define('MOODLE_INTERNAL', true);
397 // core_component can be used in any scripts, it does not need anything else.
398 require_once($CFG->libdir .'/classes/component.php');
400 // special support for highly optimised scripts that do not need libraries and DB connection
401 if (defined('ABORT_AFTER_CONFIG')) {
402 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
403 // hide debugging if not enabled in config.php - we do not want to disclose sensitive info
404 error_reporting($CFG->debug);
405 if (NO_DEBUG_DISPLAY) {
406 // Some parts of Moodle cannot display errors and debug at all.
407 ini_set('display_errors', '0');
408 ini_set('log_errors', '1');
409 } else if (empty($CFG->debugdisplay)) {
410 ini_set('display_errors', '0');
411 ini_set('log_errors', '1');
412 } else {
413 ini_set('display_errors', '1');
415 require_once("$CFG->dirroot/lib/configonlylib.php");
416 return;
420 // Early profiling start, based exclusively on config.php $CFG settings
421 if (!empty($CFG->earlyprofilingenabled)) {
422 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
423 profiling_start();
427 * Database connection. Used for all access to the database.
428 * @global moodle_database $DB
429 * @name $DB
431 global $DB;
434 * Moodle's wrapper round PHP's $_SESSION.
436 * @global object $SESSION
437 * @name $SESSION
439 global $SESSION;
442 * Holds the user table record for the current user. Will be the 'guest'
443 * user record for people who are not logged in.
445 * $USER is stored in the session.
447 * Items found in the user record:
448 * - $USER->email - The user's email address.
449 * - $USER->id - The unique integer identified of this user in the 'user' table.
450 * - $USER->email - The user's email address.
451 * - $USER->firstname - The user's first name.
452 * - $USER->lastname - The user's last name.
453 * - $USER->username - The user's login username.
454 * - $USER->secret - The user's ?.
455 * - $USER->lang - The user's language choice.
457 * @global object $USER
458 * @name $USER
460 global $USER;
463 * Frontpage course record
465 global $SITE;
468 * A central store of information about the current page we are
469 * generating in response to the user's request.
471 * @global moodle_page $PAGE
472 * @name $PAGE
474 global $PAGE;
477 * The current course. An alias for $PAGE->course.
478 * @global object $COURSE
479 * @name $COURSE
481 global $COURSE;
484 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
485 * it to generate HTML for output.
487 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
488 * for the magic that does that. After $OUTPUT has been initialised, any attempt
489 * to change something that affects the current theme ($PAGE->course, logged in use,
490 * httpsrequried ... will result in an exception.)
492 * Please note the $OUTPUT is replacing the old global $THEME object.
494 * @global object $OUTPUT
495 * @name $OUTPUT
497 global $OUTPUT;
500 * Full script path including all params, slash arguments, scheme and host.
502 * Note: Do NOT use for getting of current page URL or detection of https,
503 * instead use $PAGE->url or is_https().
505 * @global string $FULLME
506 * @name $FULLME
508 global $FULLME;
511 * Script path including query string and slash arguments without host.
512 * @global string $ME
513 * @name $ME
515 global $ME;
518 * $FULLME without slasharguments and query string.
519 * @global string $FULLSCRIPT
520 * @name $FULLSCRIPT
522 global $FULLSCRIPT;
525 * Relative moodle script path '/course/view.php'
526 * @global string $SCRIPT
527 * @name $SCRIPT
529 global $SCRIPT;
531 // Set httpswwwroot to $CFG->wwwroot for backwards compatibility
532 // The loginhttps option is deprecated, so httpswwwroot is no longer necessary. See MDL-42834.
533 $CFG->httpswwwroot = $CFG->wwwroot;
535 require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
537 if (NO_OUTPUT_BUFFERING) {
538 // we have to call this always before starting session because it discards headers!
539 disable_output_buffering();
542 // Increase memory limits if possible
543 raise_memory_limit(MEMORY_STANDARD);
545 // Time to start counting
546 init_performance_info();
548 // Put $OUTPUT in place, so errors can be displayed.
549 $OUTPUT = new bootstrap_renderer();
551 // set handler for uncaught exceptions - equivalent to print_error() call
552 if (!PHPUNIT_TEST or PHPUNIT_UTIL) {
553 set_exception_handler('default_exception_handler');
554 set_error_handler('default_error_handler', E_ALL | E_STRICT);
557 // Acceptance tests needs special output to capture the errors,
558 // but not necessary for behat CLI command and init script.
559 if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST') && !defined('BEHAT_UTIL')) {
560 require_once(__DIR__ . '/behat/lib.php');
561 set_error_handler('behat_error_handler', E_ALL | E_STRICT);
564 // If there are any errors in the standard libraries we want to know!
565 error_reporting(E_ALL | E_STRICT);
567 // Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
568 // http://www.google.com/webmasters/faq.html#prefetchblock
569 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
570 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
571 echo('Prefetch request forbidden.');
572 exit(1);
575 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
576 //the problem is that we need specific version of quickforms and hacked excel files :-(
577 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
579 // Register our classloader, in theory somebody might want to replace it to load other hacked core classes.
580 if (defined('COMPONENT_CLASSLOADER')) {
581 spl_autoload_register(COMPONENT_CLASSLOADER);
582 } else {
583 spl_autoload_register('core_component::classloader');
586 // Remember the default PHP timezone, we will need it later.
587 core_date::store_default_php_timezone();
589 // Load up standard libraries
590 require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output
591 require_once($CFG->libdir .'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
592 require_once($CFG->libdir .'/weblib.php'); // Functions relating to HTTP and content
593 require_once($CFG->libdir .'/outputlib.php'); // Functions for generating output
594 require_once($CFG->libdir .'/navigationlib.php'); // Class for generating Navigation structure
595 require_once($CFG->libdir .'/dmllib.php'); // Database access
596 require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
597 require_once($CFG->libdir .'/accesslib.php'); // Access control functions
598 require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
599 require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
600 require_once($CFG->libdir .'/enrollib.php'); // Enrolment related functions
601 require_once($CFG->libdir .'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
602 require_once($CFG->libdir .'/blocklib.php'); // Library for controlling blocks
603 require_once($CFG->libdir .'/eventslib.php'); // Events functions
604 require_once($CFG->libdir .'/grouplib.php'); // Groups functions
605 require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie related stuff
606 require_once($CFG->libdir .'/editorlib.php'); // All text editor related functions and classes
607 require_once($CFG->libdir .'/messagelib.php'); // Messagelib functions
608 require_once($CFG->libdir .'/modinfolib.php'); // Cached information on course-module instances
609 require_once($CFG->dirroot.'/cache/lib.php'); // Cache API
611 // make sure PHP is not severly misconfigured
612 setup_validate_php_configuration();
614 // Connect to the database
615 setup_DB();
617 if (PHPUNIT_TEST and !PHPUNIT_UTIL) {
618 // make sure tests do not run in parallel
619 test_lock::acquire('phpunit');
620 $dbhash = null;
621 try {
622 if ($dbhash = $DB->get_field('config', 'value', array('name'=>'phpunittest'))) {
623 // reset DB tables
624 phpunit_util::reset_database();
626 } catch (Exception $e) {
627 if ($dbhash) {
628 // we ned to reinit if reset fails
629 $DB->set_field('config', 'value', 'na', array('name'=>'phpunittest'));
632 unset($dbhash);
635 // Load up any configuration from the config table or MUC cache.
636 if (PHPUNIT_TEST) {
637 phpunit_util::initialise_cfg();
638 } else {
639 initialise_cfg();
642 if (isset($CFG->debug)) {
643 $CFG->debug = (int)$CFG->debug;
644 error_reporting($CFG->debug);
645 } else {
646 $CFG->debug = 0;
648 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
650 // Find out if PHP configured to display warnings,
651 // this is a security problem because some moodle scripts may
652 // disclose sensitive information.
653 if (ini_get_bool('display_errors')) {
654 define('WARN_DISPLAY_ERRORS_ENABLED', true);
656 // If we want to display Moodle errors, then try and set PHP errors to match.
657 if (!isset($CFG->debugdisplay)) {
658 // Keep it "as is" during installation.
659 } else if (NO_DEBUG_DISPLAY) {
660 // Some parts of Moodle cannot display errors and debug at all.
661 ini_set('display_errors', '0');
662 ini_set('log_errors', '1');
663 } else if (empty($CFG->debugdisplay)) {
664 ini_set('display_errors', '0');
665 ini_set('log_errors', '1');
666 } else {
667 // This is very problematic in XHTML strict mode!
668 ini_set('display_errors', '1');
671 // Register our shutdown manager, do NOT use register_shutdown_function().
672 core_shutdown_manager::initialize();
674 // Verify upgrade is not running unless we are in a script that needs to execute in any case
675 if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
676 if ($CFG->upgraderunning < time()) {
677 unset_config('upgraderunning');
678 } else {
679 print_error('upgraderunning');
683 // enable circular reference collector in PHP 5.3,
684 // it helps a lot when using large complex OOP structures such as in amos or gradebook
685 if (function_exists('gc_enable')) {
686 gc_enable();
689 // detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
690 if (!empty($CFG->version) and $CFG->version < 2007101509) {
691 print_error('upgraderequires19', 'error');
692 die;
695 // Calculate and set $CFG->ostype to be used everywhere. Possible values are:
696 // - WINDOWS: for any Windows flavour.
697 // - UNIX: for the rest
698 // Also, $CFG->os can continue being used if more specialization is required
699 if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
700 $CFG->ostype = 'WINDOWS';
701 } else {
702 $CFG->ostype = 'UNIX';
704 $CFG->os = PHP_OS;
706 // Configure ampersands in URLs
707 ini_set('arg_separator.output', '&amp;');
709 // Work around for a PHP bug see MDL-11237
710 ini_set('pcre.backtrack_limit', 20971520); // 20 MB
712 // Work around for PHP7 bug #70110. See MDL-52475 .
713 if (ini_get('pcre.jit')) {
714 ini_set('pcre.jit', 0);
717 // Set PHP default timezone to server timezone.
718 core_date::set_default_server_timezone();
720 // Location of standard files
721 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
722 $CFG->moddata = 'moddata';
724 // neutralise nasty chars in PHP_SELF
725 if (isset($_SERVER['PHP_SELF'])) {
726 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
727 if ($phppos !== false) {
728 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
730 unset($phppos);
733 // initialise ME's - this must be done BEFORE starting of session!
734 initialise_fullme();
736 // define SYSCONTEXTID in config.php if you want to save some queries,
737 // after install it must match the system context record id.
738 if (!defined('SYSCONTEXTID')) {
739 context_system::instance();
742 // Defining the site - aka frontpage course
743 try {
744 $SITE = get_site();
745 } catch (moodle_exception $e) {
746 $SITE = null;
747 if (empty($CFG->version)) {
748 $SITE = new stdClass();
749 $SITE->id = 1;
750 $SITE->shortname = null;
751 } else {
752 throw $e;
755 // And the 'default' course - this will usually get reset later in require_login() etc.
756 $COURSE = clone($SITE);
757 // Id of the frontpage course.
758 define('SITEID', $SITE->id);
760 // init session prevention flag - this is defined on pages that do not want session
761 if (CLI_SCRIPT) {
762 // no sessions in CLI scripts possible
763 define('NO_MOODLE_COOKIES', true);
765 } else if (WS_SERVER) {
766 // No sessions possible in web services.
767 define('NO_MOODLE_COOKIES', true);
769 } else if (!defined('NO_MOODLE_COOKIES')) {
770 if (empty($CFG->version) or $CFG->version < 2009011900) {
771 // no session before sessions table gets created
772 define('NO_MOODLE_COOKIES', true);
773 } else if (CLI_SCRIPT) {
774 // CLI scripts can not have session
775 define('NO_MOODLE_COOKIES', true);
776 } else {
777 define('NO_MOODLE_COOKIES', false);
781 // Start session and prepare global $SESSION, $USER.
782 if (empty($CFG->sessiontimeout)) {
783 $CFG->sessiontimeout = 7200;
785 \core\session\manager::start();
787 // Set default content type and encoding, developers are still required to use
788 // echo $OUTPUT->header() everywhere, anything that gets set later should override these headers.
789 // This is intended to mitigate some security problems.
790 if (AJAX_SCRIPT) {
791 if (!core_useragent::supports_json_contenttype()) {
792 // Some bloody old IE.
793 @header('Content-type: text/plain; charset=utf-8');
794 @header('X-Content-Type-Options: nosniff');
795 } else if (!empty($_FILES)) {
796 // Some ajax code may have problems with json and file uploads.
797 @header('Content-type: text/plain; charset=utf-8');
798 } else {
799 @header('Content-type: application/json; charset=utf-8');
801 } else if (!CLI_SCRIPT) {
802 @header('Content-type: text/html; charset=utf-8');
805 // Initialise some variables that are supposed to be set in config.php only.
806 if (!isset($CFG->filelifetime)) {
807 $CFG->filelifetime = 60*60*6;
810 // Late profiling, only happening if early one wasn't started
811 if (!empty($CFG->profilingenabled)) {
812 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
813 profiling_start();
816 // Hack to get around max_input_vars restrictions,
817 // we need to do this after session init to have some basic DDoS protection.
818 workaround_max_input_vars();
820 // Process theme change in the URL.
821 if (!empty($CFG->allowthemechangeonurl) and !empty($_GET['theme'])) {
822 // we have to use _GET directly because we do not want this to interfere with _POST
823 $urlthemename = optional_param('theme', '', PARAM_PLUGIN);
824 try {
825 $themeconfig = theme_config::load($urlthemename);
826 // Makes sure the theme can be loaded without errors.
827 if ($themeconfig->name === $urlthemename) {
828 $SESSION->theme = $urlthemename;
829 } else {
830 unset($SESSION->theme);
832 unset($themeconfig);
833 unset($urlthemename);
834 } catch (Exception $e) {
835 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
838 unset($urlthemename);
840 // Ensure a valid theme is set.
841 if (!isset($CFG->theme)) {
842 $CFG->theme = 'boost';
845 // Set language/locale of printed times. If user has chosen a language that
846 // that is different from the site language, then use the locale specified
847 // in the language file. Otherwise, if the admin hasn't specified a locale
848 // then use the one from the default language. Otherwise (and this is the
849 // majority of cases), use the stored locale specified by admin.
850 // note: do not accept lang parameter from POST
851 if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
852 if (get_string_manager()->translation_exists($lang, false)) {
853 $SESSION->lang = $lang;
856 unset($lang);
858 // PARAM_SAFEDIR used instead of PARAM_LANG because using PARAM_LANG results
859 // in an empty string being returned when a non-existant language is specified,
860 // which would make it necessary to log out to undo the forcelang setting.
861 // With PARAM_SAFEDIR, it's possible to specify ?forcelang=none to drop the forcelang effect.
862 if ($forcelang = optional_param('forcelang', '', PARAM_SAFEDIR)) {
863 if (isloggedin()
864 && get_string_manager()->translation_exists($forcelang, false)
865 && has_capability('moodle/site:forcelanguage', context_system::instance())) {
866 $SESSION->forcelang = $forcelang;
867 } else if (isset($SESSION->forcelang)) {
868 unset($SESSION->forcelang);
871 unset($forcelang);
873 setup_lang_from_browser();
875 if (empty($CFG->lang)) {
876 if (empty($SESSION->lang)) {
877 $CFG->lang = 'en';
878 } else {
879 $CFG->lang = $SESSION->lang;
883 // Set the default site locale, a lot of the stuff may depend on this
884 // it is definitely too late to call this first in require_login()!
885 moodle_setlocale();
887 // Create the $PAGE global - this marks the PAGE and OUTPUT fully initialised, this MUST be done at the end of setup!
888 if (!empty($CFG->moodlepageclass)) {
889 if (!empty($CFG->moodlepageclassfile)) {
890 require_once($CFG->moodlepageclassfile);
892 $classname = $CFG->moodlepageclass;
893 } else {
894 $classname = 'moodle_page';
896 $PAGE = new $classname();
897 unset($classname);
900 if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
901 if ($CFG->theme == 'standard') { // Temporary measure to help with XHTML validation
902 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
903 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
904 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
905 if ($user = get_complete_user_data("username", "w3cvalidator")) {
906 $user->ignoresesskey = true;
907 } else {
908 $user = guest_user();
910 \core\session\manager::set_user($user);
916 // Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
917 // LogFormat to get the current logged in username in moodle.
918 // Alternatvely for other web servers a header X-MOODLEUSER can be set which
919 // can be using in the logfile and stripped out if needed.
920 if ($USER && isset($USER->username)) {
921 $logmethod = '';
922 $logvalue = 0;
923 if (!empty($CFG->apacheloguser) && function_exists('apache_note')) {
924 $logmethod = 'apache';
925 $logvalue = $CFG->apacheloguser;
927 if (!empty($CFG->headerloguser)) {
928 $logmethod = 'header';
929 $logvalue = $CFG->headerloguser;
931 if (!empty($logmethod)) {
932 $loguserid = $USER->id;
933 $logusername = clean_filename($USER->username);
934 $logname = '';
935 if (isset($USER->firstname)) {
936 // We can assume both will be set
937 // - even if to empty.
938 $logname = clean_filename($USER->firstname . " " . $USER->lastname);
940 if (\core\session\manager::is_loggedinas()) {
941 $realuser = \core\session\manager::get_realuser();
942 $logusername = clean_filename($realuser->username." as ".$logusername);
943 $logname = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$logname);
944 $loguserid = clean_filename($realuser->id." as ".$loguserid);
946 switch ($logvalue) {
947 case 3:
948 $logname = $logusername;
949 break;
950 case 2:
951 $logname = $logname;
952 break;
953 case 1:
954 default:
955 $logname = $loguserid;
956 break;
958 if ($logmethod == 'apache') {
959 apache_note('MOODLEUSER', $logname);
962 if ($logmethod == 'header') {
963 header("X-MOODLEUSER: $logname");
968 // Ensure the urlrewriteclass is setup correctly (to avoid crippling site).
969 if (isset($CFG->urlrewriteclass)) {
970 if (!class_exists($CFG->urlrewriteclass)) {
971 debugging("urlrewriteclass {$CFG->urlrewriteclass} was not found, disabling.");
972 unset($CFG->urlrewriteclass);
973 } else if (!in_array('core\output\url_rewriter', class_implements($CFG->urlrewriteclass))) {
974 debugging("{$CFG->urlrewriteclass} does not implement core\output\url_rewriter, disabling.", DEBUG_DEVELOPER);
975 unset($CFG->urlrewriteclass);
979 // Use a custom script replacement if one exists
980 if (!empty($CFG->customscripts)) {
981 if (($customscript = custom_script_path()) !== false) {
982 require ($customscript);
986 if (PHPUNIT_TEST) {
987 // no ip blocking, these are CLI only
988 } else if (CLI_SCRIPT and !defined('WEB_CRON_EMULATED_CLI')) {
989 // no ip blocking
990 } else if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
991 // in this case, ip in allowed list will be performed first
992 // for example, client IP is 192.168.1.1
993 // 192.168 subnet is an entry in allowed list
994 // 192.168.1.1 is banned in blocked list
995 // This ip will be banned finally
996 if (!empty($CFG->allowedip)) {
997 if (!remoteip_in_list($CFG->allowedip)) {
998 die(get_string('ipblocked', 'admin'));
1001 // need further check, client ip may a part of
1002 // allowed subnet, but a IP address are listed
1003 // in blocked list.
1004 if (!empty($CFG->blockedip)) {
1005 if (remoteip_in_list($CFG->blockedip)) {
1006 die(get_string('ipblocked', 'admin'));
1010 } else {
1011 // in this case, IPs in blocked list will be performed first
1012 // for example, client IP is 192.168.1.1
1013 // 192.168 subnet is an entry in blocked list
1014 // 192.168.1.1 is allowed in allowed list
1015 // This ip will be allowed finally
1016 if (!empty($CFG->blockedip)) {
1017 if (remoteip_in_list($CFG->blockedip)) {
1018 // if the allowed ip list is not empty
1019 // IPs are not included in the allowed list will be
1020 // blocked too
1021 if (!empty($CFG->allowedip)) {
1022 if (!remoteip_in_list($CFG->allowedip)) {
1023 die(get_string('ipblocked', 'admin'));
1025 } else {
1026 die(get_string('ipblocked', 'admin'));
1030 // if blocked list is null
1031 // allowed list should be tested
1032 if(!empty($CFG->allowedip)) {
1033 if (!remoteip_in_list($CFG->allowedip)) {
1034 die(get_string('ipblocked', 'admin'));
1040 // // try to detect IE6 and prevent gzip because it is extremely buggy browser
1041 if (!empty($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false) {
1042 ini_set('zlib.output_compression', 'Off');
1043 if (function_exists('apache_setenv')) {
1044 apache_setenv('no-gzip', 1);
1048 // Switch to CLI maintenance mode if required, we need to do it here after all the settings are initialised.
1049 if (isset($CFG->maintenance_later) and $CFG->maintenance_later <= time()) {
1050 if (!file_exists("$CFG->dataroot/climaintenance.html")) {
1051 require_once("$CFG->libdir/adminlib.php");
1052 enable_cli_maintenance_mode();
1054 unset_config('maintenance_later');
1055 if (AJAX_SCRIPT) {
1056 die;
1057 } else if (!CLI_SCRIPT) {
1058 redirect(new moodle_url('/'));
1062 // Add behat_shutdown_function to shutdown manager, so we can capture php errors,
1063 // but not necessary for behat CLI command as it's being captured by behat process.
1064 if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST')) {
1065 core_shutdown_manager::register_function('behat_shutdown_function');
1068 // note: we can not block non utf-8 installations here, because empty mysql database
1069 // might be converted to utf-8 in admin/index.php during installation
1073 // this is a funny trick to make Eclipse believe that $OUTPUT and other globals
1074 // contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
1075 if (false) {
1076 $DB = new moodle_database();
1077 $OUTPUT = new core_renderer(null, null);
1078 $PAGE = new moodle_page();