Merge branch 'MDL-54830-master' of https://github.com/snake/moodle
[moodle.git] / lib / setup.php
blob8ee0219486fa792165459884c8c002cac06b431c
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->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).
44 * @global object $CFG
45 * @name $CFG
47 global $CFG; // this should be done much earlier in config.php before creating new $CFG instance
49 if (!isset($CFG)) {
50 if (defined('PHPUNIT_TEST') and PHPUNIT_TEST) {
51 echo('There is a missing "global $CFG;" at the beginning of the config.php file.'."\n");
52 exit(1);
53 } else {
54 // this should never happen, maybe somebody is accessing this file directly...
55 exit(1);
59 // We can detect real dirroot path reliably since PHP 4.0.2,
60 // it can not be anything else, there is no point in having this in config.php
61 $CFG->dirroot = dirname(__DIR__);
63 // File permissions on created directories in the $CFG->dataroot
64 if (!isset($CFG->directorypermissions)) {
65 $CFG->directorypermissions = 02777; // Must be octal (that's why it's here)
67 if (!isset($CFG->filepermissions)) {
68 $CFG->filepermissions = ($CFG->directorypermissions & 0666); // strip execute flags
70 // Better also set default umask because developers often forget to include directory
71 // permissions in mkdir() and chmod() after creating new files.
72 if (!isset($CFG->umaskpermissions)) {
73 $CFG->umaskpermissions = (($CFG->directorypermissions & 0777) ^ 0777);
75 umask($CFG->umaskpermissions);
77 if (defined('BEHAT_SITE_RUNNING')) {
78 // We already switched to behat test site previously.
80 } else if (!empty($CFG->behat_wwwroot) or !empty($CFG->behat_dataroot) or !empty($CFG->behat_prefix)) {
81 // The behat is configured on this server, we need to find out if this is the behat test
82 // site based on the URL used for access.
83 require_once(__DIR__ . '/../lib/behat/lib.php');
85 // Update config variables for parallel behat runs.
86 behat_update_vars_for_process();
88 // If behat is being installed for parallel run, then we modify params for parallel run only.
89 if (behat_is_test_site() && !(defined('BEHAT_PARALLEL_UTIL') && empty($CFG->behatrunprocess))) {
90 clearstatcache();
92 // Checking the integrity of the provided $CFG->behat_* vars and the
93 // selected wwwroot to prevent conflicts with production and phpunit environments.
94 behat_check_config_vars();
96 // Check that the directory does not contains other things.
97 if (!file_exists("$CFG->behat_dataroot/behattestdir.txt")) {
98 if ($dh = opendir($CFG->behat_dataroot)) {
99 while (($file = readdir($dh)) !== false) {
100 if ($file === 'behat' or $file === '.' or $file === '..' or $file === '.DS_Store' or is_numeric($file)) {
101 continue;
103 behat_error(BEHAT_EXITCODE_CONFIG, "$CFG->behat_dataroot directory is not empty, ensure this is the " .
104 "directory where you want to install behat test dataroot");
106 closedir($dh);
107 unset($dh);
108 unset($file);
111 if (defined('BEHAT_UTIL')) {
112 // Now we create dataroot directory structure for behat tests.
113 testing_initdataroot($CFG->behat_dataroot, 'behat');
114 } else {
115 behat_error(BEHAT_EXITCODE_INSTALL);
119 if (!defined('BEHAT_UTIL') and !defined('BEHAT_TEST')) {
120 // Somebody tries to access test site directly, tell them if not enabled.
121 $behatdir = preg_replace("#[/|\\\]" . BEHAT_PARALLEL_SITE_NAME . "\d{0,}$#", '', $CFG->behat_dataroot);
122 if (!file_exists($behatdir . '/test_environment_enabled.txt')) {
123 behat_error(BEHAT_EXITCODE_CONFIG, 'Behat is configured but not enabled on this test site.');
127 // Constant used to inform that the behat test site is being used,
128 // this includes all the processes executed by the behat CLI command like
129 // the site reset, the steps executed by the browser drivers when simulating
130 // a user session and a real session when browsing manually to $CFG->behat_wwwroot
131 // like the browser driver does automatically.
132 // Different from BEHAT_TEST as only this last one can perform CLI
133 // actions like reset the site or use data generators.
134 define('BEHAT_SITE_RUNNING', true);
136 // Clean extra config.php settings.
137 behat_clean_init_config();
139 // Now we can begin switching $CFG->X for $CFG->behat_X.
140 $CFG->wwwroot = $CFG->behat_wwwroot;
141 $CFG->prefix = $CFG->behat_prefix;
142 $CFG->dataroot = $CFG->behat_dataroot;
146 // Normalise dataroot - we do not want any symbolic links, trailing / or any other weirdness there
147 if (!isset($CFG->dataroot)) {
148 if (isset($_SERVER['REMOTE_ADDR'])) {
149 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
151 echo('Fatal error: $CFG->dataroot is not specified in config.php! Exiting.'."\n");
152 exit(1);
154 $CFG->dataroot = realpath($CFG->dataroot);
155 if ($CFG->dataroot === false) {
156 if (isset($_SERVER['REMOTE_ADDR'])) {
157 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
159 echo('Fatal error: $CFG->dataroot is not configured properly, directory does not exist or is not accessible! Exiting.'."\n");
160 exit(1);
161 } else if (!is_writable($CFG->dataroot)) {
162 if (isset($_SERVER['REMOTE_ADDR'])) {
163 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
165 echo('Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.'."\n");
166 exit(1);
169 // wwwroot is mandatory
170 if (!isset($CFG->wwwroot) or $CFG->wwwroot === 'http://example.com/moodle') {
171 if (isset($_SERVER['REMOTE_ADDR'])) {
172 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
174 echo('Fatal error: $CFG->wwwroot is not configured! Exiting.'."\n");
175 exit(1);
178 // Make sure there is some database table prefix.
179 if (!isset($CFG->prefix)) {
180 $CFG->prefix = '';
183 // Define admin directory
184 if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
185 $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
188 // Set up some paths.
189 $CFG->libdir = $CFG->dirroot .'/lib';
191 // Allow overriding of tempdir but be backwards compatible
192 if (!isset($CFG->tempdir)) {
193 $CFG->tempdir = "$CFG->dataroot/temp";
196 // Allow overriding of backuptempdir but be backwards compatible
197 if (!isset($CFG->backuptempdir)) {
198 $CFG->backuptempdir = "$CFG->tempdir/backup";
201 // Allow overriding of cachedir but be backwards compatible
202 if (!isset($CFG->cachedir)) {
203 $CFG->cachedir = "$CFG->dataroot/cache";
206 // Allow overriding of localcachedir.
207 if (!isset($CFG->localcachedir)) {
208 $CFG->localcachedir = "$CFG->dataroot/localcache";
211 // Location of all languages except core English pack.
212 if (!isset($CFG->langotherroot)) {
213 $CFG->langotherroot = $CFG->dataroot.'/lang';
216 // Location of local lang pack customisations (dirs with _local suffix).
217 if (!isset($CFG->langlocalroot)) {
218 $CFG->langlocalroot = $CFG->dataroot.'/lang';
221 // The current directory in PHP version 4.3.0 and above isn't necessarily the
222 // directory of the script when run from the command line. The require_once()
223 // would fail, so we'll have to chdir()
224 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
225 // do it only once - skip the second time when continuing after prevous abort
226 if (!defined('ABORT_AFTER_CONFIG') and !defined('ABORT_AFTER_CONFIG_CANCEL')) {
227 chdir(dirname($_SERVER['argv'][0]));
231 // sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
232 ini_set('precision', 14); // needed for upgrades and gradebook
233 ini_set('serialize_precision', 17); // Make float serialization consistent on all systems.
235 // Scripts may request no debug and error messages in output
236 // please note it must be defined before including the config.php script
237 // and in some cases you also need to set custom default exception handler
238 if (!defined('NO_DEBUG_DISPLAY')) {
239 if (defined('AJAX_SCRIPT') and AJAX_SCRIPT) {
240 // Moodle AJAX scripts are expected to return json data, any PHP notices or errors break it badly,
241 // developers simply must learn to watch error log.
242 define('NO_DEBUG_DISPLAY', true);
243 } else {
244 define('NO_DEBUG_DISPLAY', false);
248 // Some scripts such as upgrade may want to prevent output buffering
249 if (!defined('NO_OUTPUT_BUFFERING')) {
250 define('NO_OUTPUT_BUFFERING', false);
253 // PHPUnit tests need custom init
254 if (!defined('PHPUNIT_TEST')) {
255 define('PHPUNIT_TEST', false);
258 // Performance tests needs to always display performance info, even in redirections.
259 if (!defined('MDL_PERF_TEST')) {
260 define('MDL_PERF_TEST', false);
261 } else {
262 // We force the ones we need.
263 if (!defined('MDL_PERF')) {
264 define('MDL_PERF', true);
266 if (!defined('MDL_PERFDB')) {
267 define('MDL_PERFDB', true);
269 if (!defined('MDL_PERFTOFOOT')) {
270 define('MDL_PERFTOFOOT', true);
274 // When set to true MUC (Moodle caching) will be disabled as much as possible.
275 // A special cache factory will be used to handle this situation and will use special "disabled" equivalents objects.
276 // This ensure we don't attempt to read or create the config file, don't use stores, don't provide persistence or
277 // storage of any kind.
278 if (!defined('CACHE_DISABLE_ALL')) {
279 define('CACHE_DISABLE_ALL', false);
282 // When set to true MUC (Moodle caching) will not use any of the defined or default stores.
283 // The Cache API will continue to function however this will force the use of the cachestore_dummy so all requests
284 // will be interacting with a static property and will never go to the proper cache stores.
285 // Useful if you need to avoid the stores for one reason or another.
286 if (!defined('CACHE_DISABLE_STORES')) {
287 define('CACHE_DISABLE_STORES', false);
290 // Servers should define a default timezone in php.ini, but if they don't then make sure no errors are shown.
291 date_default_timezone_set(@date_default_timezone_get());
293 // Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
294 // In your new CLI scripts just add "define('CLI_SCRIPT', true);" before requiring config.php.
295 // Please note that one script can not be accessed from both CLI and web interface.
296 if (!defined('CLI_SCRIPT')) {
297 define('CLI_SCRIPT', false);
299 if (defined('WEB_CRON_EMULATED_CLI')) {
300 if (!isset($_SERVER['REMOTE_ADDR'])) {
301 echo('Web cron can not be executed as CLI script any more, please use admin/cli/cron.php instead'."\n");
302 exit(1);
304 } else if (isset($_SERVER['REMOTE_ADDR'])) {
305 if (CLI_SCRIPT) {
306 echo('Command line scripts can not be executed from the web interface');
307 exit(1);
309 } else {
310 if (!CLI_SCRIPT) {
311 echo('Command line scripts must define CLI_SCRIPT before requiring config.php'."\n");
312 exit(1);
316 // All web service requests have WS_SERVER == true.
317 if (!defined('WS_SERVER')) {
318 define('WS_SERVER', false);
321 // Detect CLI maintenance mode - this is useful when you need to mess with database, such as during upgrades
322 if (file_exists("$CFG->dataroot/climaintenance.html")) {
323 if (!CLI_SCRIPT) {
324 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Moodle under maintenance');
325 header('Status: 503 Moodle under maintenance');
326 header('Retry-After: 300');
327 header('Content-type: text/html; charset=utf-8');
328 header('X-UA-Compatible: IE=edge');
329 /// Headers to make it not cacheable and json
330 header('Cache-Control: no-store, no-cache, must-revalidate');
331 header('Cache-Control: post-check=0, pre-check=0', false);
332 header('Pragma: no-cache');
333 header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
334 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
335 header('Accept-Ranges: none');
336 readfile("$CFG->dataroot/climaintenance.html");
337 die;
338 } else {
339 if (!defined('CLI_MAINTENANCE')) {
340 define('CLI_MAINTENANCE', true);
343 } else {
344 if (!defined('CLI_MAINTENANCE')) {
345 define('CLI_MAINTENANCE', false);
349 // Sometimes people use different PHP binary for web and CLI, make 100% sure they have the supported PHP version.
350 if (version_compare(PHP_VERSION, '5.6.5') < 0) {
351 $phpversion = PHP_VERSION;
352 // Do NOT localise - lang strings would not work here and we CAN NOT move it to later place.
353 echo "Moodle 3.2 or later requires at least PHP 5.6.5 (currently using version $phpversion).\n";
354 echo "Some servers may have multiple PHP versions installed, are you using the correct executable?\n";
355 exit(1);
358 // Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
359 if (!defined('AJAX_SCRIPT')) {
360 define('AJAX_SCRIPT', false);
363 // Exact version of currently used yui2 and 3 library.
364 $CFG->yui2version = '2.9.0';
365 $CFG->yui3version = '3.17.2';
367 // Patching the upstream YUI release.
368 // For important information on patching YUI modules, please see http://docs.moodle.org/dev/YUI/Patching.
369 // If we need to patch a YUI modules between official YUI releases, the yuipatchlevel will need to be manually
370 // incremented here. The module will also need to be listed in the yuipatchedmodules.
371 // When upgrading to a subsequent version of YUI, these should be reset back to 0 and an empty array.
372 $CFG->yuipatchlevel = 0;
373 $CFG->yuipatchedmodules = array(
376 if (!empty($CFG->disableonclickaddoninstall)) {
377 // This config.php flag has been merged into another one.
378 $CFG->disableupdateautodeploy = true;
381 // Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides.
382 if (!isset($CFG->config_php_settings)) {
383 $CFG->config_php_settings = (array)$CFG;
384 // Forced plugin settings override values from config_plugins table.
385 unset($CFG->config_php_settings['forced_plugin_settings']);
386 if (!isset($CFG->forced_plugin_settings)) {
387 $CFG->forced_plugin_settings = array();
391 if (isset($CFG->debug)) {
392 $CFG->debug = (int)$CFG->debug;
393 } else {
394 $CFG->debug = 0;
396 $CFG->debugdeveloper = (($CFG->debug & (E_ALL | E_STRICT)) === (E_ALL | E_STRICT)); // DEBUG_DEVELOPER is not available yet.
398 if (!defined('MOODLE_INTERNAL')) { // Necessary because cli installer has to define it earlier.
399 /** Used by library scripts to check they are being called by Moodle. */
400 define('MOODLE_INTERNAL', true);
403 // core_component can be used in any scripts, it does not need anything else.
404 require_once($CFG->libdir .'/classes/component.php');
406 // special support for highly optimised scripts that do not need libraries and DB connection
407 if (defined('ABORT_AFTER_CONFIG')) {
408 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
409 // hide debugging if not enabled in config.php - we do not want to disclose sensitive info
410 error_reporting($CFG->debug);
411 if (NO_DEBUG_DISPLAY) {
412 // Some parts of Moodle cannot display errors and debug at all.
413 ini_set('display_errors', '0');
414 ini_set('log_errors', '1');
415 } else if (empty($CFG->debugdisplay)) {
416 ini_set('display_errors', '0');
417 ini_set('log_errors', '1');
418 } else {
419 ini_set('display_errors', '1');
421 require_once("$CFG->dirroot/lib/configonlylib.php");
422 return;
426 // Early profiling start, based exclusively on config.php $CFG settings
427 if (!empty($CFG->earlyprofilingenabled)) {
428 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
429 profiling_start();
433 * Database connection. Used for all access to the database.
434 * @global moodle_database $DB
435 * @name $DB
437 global $DB;
440 * Moodle's wrapper round PHP's $_SESSION.
442 * @global object $SESSION
443 * @name $SESSION
445 global $SESSION;
448 * Holds the user table record for the current user. Will be the 'guest'
449 * user record for people who are not logged in.
451 * $USER is stored in the session.
453 * Items found in the user record:
454 * - $USER->email - The user's email address.
455 * - $USER->id - The unique integer identified of this user in the 'user' table.
456 * - $USER->email - The user's email address.
457 * - $USER->firstname - The user's first name.
458 * - $USER->lastname - The user's last name.
459 * - $USER->username - The user's login username.
460 * - $USER->secret - The user's ?.
461 * - $USER->lang - The user's language choice.
463 * @global object $USER
464 * @name $USER
466 global $USER;
469 * Frontpage course record
471 global $SITE;
474 * A central store of information about the current page we are
475 * generating in response to the user's request.
477 * @global moodle_page $PAGE
478 * @name $PAGE
480 global $PAGE;
483 * The current course. An alias for $PAGE->course.
484 * @global object $COURSE
485 * @name $COURSE
487 global $COURSE;
490 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
491 * it to generate HTML for output.
493 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
494 * for the magic that does that. After $OUTPUT has been initialised, any attempt
495 * to change something that affects the current theme ($PAGE->course, logged in use,
496 * httpsrequried ... will result in an exception.)
498 * Please note the $OUTPUT is replacing the old global $THEME object.
500 * @global object $OUTPUT
501 * @name $OUTPUT
503 global $OUTPUT;
506 * Full script path including all params, slash arguments, scheme and host.
508 * Note: Do NOT use for getting of current page URL or detection of https,
509 * instead use $PAGE->url or is_https().
511 * @global string $FULLME
512 * @name $FULLME
514 global $FULLME;
517 * Script path including query string and slash arguments without host.
518 * @global string $ME
519 * @name $ME
521 global $ME;
524 * $FULLME without slasharguments and query string.
525 * @global string $FULLSCRIPT
526 * @name $FULLSCRIPT
528 global $FULLSCRIPT;
531 * Relative moodle script path '/course/view.php'
532 * @global string $SCRIPT
533 * @name $SCRIPT
535 global $SCRIPT;
537 // Set httpswwwroot to $CFG->wwwroot for backwards compatibility
538 // The loginhttps option is deprecated, so httpswwwroot is no longer necessary. See MDL-42834.
539 $CFG->httpswwwroot = $CFG->wwwroot;
541 require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
543 if (NO_OUTPUT_BUFFERING) {
544 // we have to call this always before starting session because it discards headers!
545 disable_output_buffering();
548 // Increase memory limits if possible
549 raise_memory_limit(MEMORY_STANDARD);
551 // Time to start counting
552 init_performance_info();
554 // Put $OUTPUT in place, so errors can be displayed.
555 $OUTPUT = new bootstrap_renderer();
557 // set handler for uncaught exceptions - equivalent to print_error() call
558 if (!PHPUNIT_TEST or PHPUNIT_UTIL) {
559 set_exception_handler('default_exception_handler');
560 set_error_handler('default_error_handler', E_ALL | E_STRICT);
563 // Acceptance tests needs special output to capture the errors,
564 // but not necessary for behat CLI command and init script.
565 if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST') && !defined('BEHAT_UTIL')) {
566 require_once(__DIR__ . '/behat/lib.php');
567 set_error_handler('behat_error_handler', E_ALL | E_STRICT);
570 // If there are any errors in the standard libraries we want to know!
571 error_reporting(E_ALL | E_STRICT);
573 // Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
574 // http://www.google.com/webmasters/faq.html#prefetchblock
575 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
576 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
577 echo('Prefetch request forbidden.');
578 exit(1);
581 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
582 //the problem is that we need specific version of quickforms and hacked excel files :-(
583 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
585 // Register our classloader, in theory somebody might want to replace it to load other hacked core classes.
586 if (defined('COMPONENT_CLASSLOADER')) {
587 spl_autoload_register(COMPONENT_CLASSLOADER);
588 } else {
589 spl_autoload_register('core_component::classloader');
592 // Remember the default PHP timezone, we will need it later.
593 core_date::store_default_php_timezone();
595 // Load up standard libraries
596 require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output
597 require_once($CFG->libdir .'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
598 require_once($CFG->libdir .'/weblib.php'); // Functions relating to HTTP and content
599 require_once($CFG->libdir .'/outputlib.php'); // Functions for generating output
600 require_once($CFG->libdir .'/navigationlib.php'); // Class for generating Navigation structure
601 require_once($CFG->libdir .'/dmllib.php'); // Database access
602 require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
603 require_once($CFG->libdir .'/accesslib.php'); // Access control functions
604 require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
605 require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
606 require_once($CFG->libdir .'/enrollib.php'); // Enrolment related functions
607 require_once($CFG->libdir .'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
608 require_once($CFG->libdir .'/blocklib.php'); // Library for controlling blocks
609 require_once($CFG->libdir .'/eventslib.php'); // Events functions
610 require_once($CFG->libdir .'/grouplib.php'); // Groups functions
611 require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie related stuff
612 require_once($CFG->libdir .'/editorlib.php'); // All text editor related functions and classes
613 require_once($CFG->libdir .'/messagelib.php'); // Messagelib functions
614 require_once($CFG->libdir .'/modinfolib.php'); // Cached information on course-module instances
615 require_once($CFG->dirroot.'/cache/lib.php'); // Cache API
617 // make sure PHP is not severly misconfigured
618 setup_validate_php_configuration();
620 // Connect to the database
621 setup_DB();
623 if (PHPUNIT_TEST and !PHPUNIT_UTIL) {
624 // make sure tests do not run in parallel
625 test_lock::acquire('phpunit');
626 $dbhash = null;
627 try {
628 if ($dbhash = $DB->get_field('config', 'value', array('name'=>'phpunittest'))) {
629 // reset DB tables
630 phpunit_util::reset_database();
632 } catch (Exception $e) {
633 if ($dbhash) {
634 // we ned to reinit if reset fails
635 $DB->set_field('config', 'value', 'na', array('name'=>'phpunittest'));
638 unset($dbhash);
641 // Load up any configuration from the config table or MUC cache.
642 if (PHPUNIT_TEST) {
643 phpunit_util::initialise_cfg();
644 } else {
645 initialise_cfg();
648 if (isset($CFG->debug)) {
649 $CFG->debug = (int)$CFG->debug;
650 error_reporting($CFG->debug);
651 } else {
652 $CFG->debug = 0;
654 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
656 // Find out if PHP configured to display warnings,
657 // this is a security problem because some moodle scripts may
658 // disclose sensitive information.
659 if (ini_get_bool('display_errors')) {
660 define('WARN_DISPLAY_ERRORS_ENABLED', true);
662 // If we want to display Moodle errors, then try and set PHP errors to match.
663 if (!isset($CFG->debugdisplay)) {
664 // Keep it "as is" during installation.
665 } else if (NO_DEBUG_DISPLAY) {
666 // Some parts of Moodle cannot display errors and debug at all.
667 ini_set('display_errors', '0');
668 ini_set('log_errors', '1');
669 } else if (empty($CFG->debugdisplay)) {
670 ini_set('display_errors', '0');
671 ini_set('log_errors', '1');
672 } else {
673 // This is very problematic in XHTML strict mode!
674 ini_set('display_errors', '1');
677 // Register our shutdown manager, do NOT use register_shutdown_function().
678 core_shutdown_manager::initialize();
680 // Verify upgrade is not running unless we are in a script that needs to execute in any case
681 if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
682 if ($CFG->upgraderunning < time()) {
683 unset_config('upgraderunning');
684 } else {
685 print_error('upgraderunning');
689 // enable circular reference collector in PHP 5.3,
690 // it helps a lot when using large complex OOP structures such as in amos or gradebook
691 if (function_exists('gc_enable')) {
692 gc_enable();
695 // detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
696 if (!empty($CFG->version) and $CFG->version < 2007101509) {
697 print_error('upgraderequires19', 'error');
698 die;
701 // Calculate and set $CFG->ostype to be used everywhere. Possible values are:
702 // - WINDOWS: for any Windows flavour.
703 // - UNIX: for the rest
704 // Also, $CFG->os can continue being used if more specialization is required
705 if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
706 $CFG->ostype = 'WINDOWS';
707 } else {
708 $CFG->ostype = 'UNIX';
710 $CFG->os = PHP_OS;
712 // Configure ampersands in URLs
713 ini_set('arg_separator.output', '&amp;');
715 // Work around for a PHP bug see MDL-11237
716 ini_set('pcre.backtrack_limit', 20971520); // 20 MB
718 // Work around for PHP7 bug #70110. See MDL-52475 .
719 if (ini_get('pcre.jit')) {
720 ini_set('pcre.jit', 0);
723 // Set PHP default timezone to server timezone.
724 core_date::set_default_server_timezone();
726 // Location of standard files
727 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
728 $CFG->moddata = 'moddata';
730 // neutralise nasty chars in PHP_SELF
731 if (isset($_SERVER['PHP_SELF'])) {
732 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
733 if ($phppos !== false) {
734 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
736 unset($phppos);
739 // initialise ME's - this must be done BEFORE starting of session!
740 initialise_fullme();
742 // define SYSCONTEXTID in config.php if you want to save some queries,
743 // after install it must match the system context record id.
744 if (!defined('SYSCONTEXTID')) {
745 context_system::instance();
748 // Defining the site - aka frontpage course
749 try {
750 $SITE = get_site();
751 } catch (moodle_exception $e) {
752 $SITE = null;
753 if (empty($CFG->version)) {
754 $SITE = new stdClass();
755 $SITE->id = 1;
756 $SITE->shortname = null;
757 } else {
758 throw $e;
761 // And the 'default' course - this will usually get reset later in require_login() etc.
762 $COURSE = clone($SITE);
763 // Id of the frontpage course.
764 define('SITEID', $SITE->id);
766 // init session prevention flag - this is defined on pages that do not want session
767 if (CLI_SCRIPT) {
768 // no sessions in CLI scripts possible
769 define('NO_MOODLE_COOKIES', true);
771 } else if (WS_SERVER) {
772 // No sessions possible in web services.
773 define('NO_MOODLE_COOKIES', true);
775 } else if (!defined('NO_MOODLE_COOKIES')) {
776 if (empty($CFG->version) or $CFG->version < 2009011900) {
777 // no session before sessions table gets created
778 define('NO_MOODLE_COOKIES', true);
779 } else if (CLI_SCRIPT) {
780 // CLI scripts can not have session
781 define('NO_MOODLE_COOKIES', true);
782 } else {
783 define('NO_MOODLE_COOKIES', false);
787 // Start session and prepare global $SESSION, $USER.
788 if (empty($CFG->sessiontimeout)) {
789 $CFG->sessiontimeout = 7200;
791 \core\session\manager::start();
793 // Set default content type and encoding, developers are still required to use
794 // echo $OUTPUT->header() everywhere, anything that gets set later should override these headers.
795 // This is intended to mitigate some security problems.
796 if (AJAX_SCRIPT) {
797 if (!core_useragent::supports_json_contenttype()) {
798 // Some bloody old IE.
799 @header('Content-type: text/plain; charset=utf-8');
800 @header('X-Content-Type-Options: nosniff');
801 } else if (!empty($_FILES)) {
802 // Some ajax code may have problems with json and file uploads.
803 @header('Content-type: text/plain; charset=utf-8');
804 } else {
805 @header('Content-type: application/json; charset=utf-8');
807 } else if (!CLI_SCRIPT) {
808 @header('Content-type: text/html; charset=utf-8');
811 // Initialise some variables that are supposed to be set in config.php only.
812 if (!isset($CFG->filelifetime)) {
813 $CFG->filelifetime = 60*60*6;
816 // Late profiling, only happening if early one wasn't started
817 if (!empty($CFG->profilingenabled)) {
818 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
819 profiling_start();
822 // Hack to get around max_input_vars restrictions,
823 // we need to do this after session init to have some basic DDoS protection.
824 workaround_max_input_vars();
826 // Process theme change in the URL.
827 if (!empty($CFG->allowthemechangeonurl) and !empty($_GET['theme'])) {
828 // we have to use _GET directly because we do not want this to interfere with _POST
829 $urlthemename = optional_param('theme', '', PARAM_PLUGIN);
830 try {
831 $themeconfig = theme_config::load($urlthemename);
832 // Makes sure the theme can be loaded without errors.
833 if ($themeconfig->name === $urlthemename) {
834 $SESSION->theme = $urlthemename;
835 } else {
836 unset($SESSION->theme);
838 unset($themeconfig);
839 unset($urlthemename);
840 } catch (Exception $e) {
841 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
844 unset($urlthemename);
846 // Ensure a valid theme is set.
847 if (!isset($CFG->theme)) {
848 $CFG->theme = 'boost';
851 // Set language/locale of printed times. If user has chosen a language that
852 // that is different from the site language, then use the locale specified
853 // in the language file. Otherwise, if the admin hasn't specified a locale
854 // then use the one from the default language. Otherwise (and this is the
855 // majority of cases), use the stored locale specified by admin.
856 // note: do not accept lang parameter from POST
857 if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
858 if (get_string_manager()->translation_exists($lang, false)) {
859 $SESSION->lang = $lang;
862 unset($lang);
864 // PARAM_SAFEDIR used instead of PARAM_LANG because using PARAM_LANG results
865 // in an empty string being returned when a non-existant language is specified,
866 // which would make it necessary to log out to undo the forcelang setting.
867 // With PARAM_SAFEDIR, it's possible to specify ?forcelang=none to drop the forcelang effect.
868 if ($forcelang = optional_param('forcelang', '', PARAM_SAFEDIR)) {
869 if (isloggedin()
870 && get_string_manager()->translation_exists($forcelang, false)
871 && has_capability('moodle/site:forcelanguage', context_system::instance())) {
872 $SESSION->forcelang = $forcelang;
873 } else if (isset($SESSION->forcelang)) {
874 unset($SESSION->forcelang);
877 unset($forcelang);
879 setup_lang_from_browser();
881 if (empty($CFG->lang)) {
882 if (empty($SESSION->lang)) {
883 $CFG->lang = 'en';
884 } else {
885 $CFG->lang = $SESSION->lang;
889 // Set the default site locale, a lot of the stuff may depend on this
890 // it is definitely too late to call this first in require_login()!
891 moodle_setlocale();
893 // Create the $PAGE global - this marks the PAGE and OUTPUT fully initialised, this MUST be done at the end of setup!
894 if (!empty($CFG->moodlepageclass)) {
895 if (!empty($CFG->moodlepageclassfile)) {
896 require_once($CFG->moodlepageclassfile);
898 $classname = $CFG->moodlepageclass;
899 } else {
900 $classname = 'moodle_page';
902 $PAGE = new $classname();
903 unset($classname);
906 if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
907 if ($CFG->theme == 'standard') { // Temporary measure to help with XHTML validation
908 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
909 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
910 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
911 if ($user = get_complete_user_data("username", "w3cvalidator")) {
912 $user->ignoresesskey = true;
913 } else {
914 $user = guest_user();
916 \core\session\manager::set_user($user);
922 // Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
923 // LogFormat to get the current logged in username in moodle.
924 // Alternatvely for other web servers a header X-MOODLEUSER can be set which
925 // can be using in the logfile and stripped out if needed.
926 if ($USER && isset($USER->username)) {
927 $logmethod = '';
928 $logvalue = 0;
929 if (!empty($CFG->apacheloguser) && function_exists('apache_note')) {
930 $logmethod = 'apache';
931 $logvalue = $CFG->apacheloguser;
933 if (!empty($CFG->headerloguser)) {
934 $logmethod = 'header';
935 $logvalue = $CFG->headerloguser;
937 if (!empty($logmethod)) {
938 $loguserid = $USER->id;
939 $logusername = clean_filename($USER->username);
940 $logname = '';
941 if (isset($USER->firstname)) {
942 // We can assume both will be set
943 // - even if to empty.
944 $logname = clean_filename($USER->firstname . " " . $USER->lastname);
946 if (\core\session\manager::is_loggedinas()) {
947 $realuser = \core\session\manager::get_realuser();
948 $logusername = clean_filename($realuser->username." as ".$logusername);
949 $logname = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$logname);
950 $loguserid = clean_filename($realuser->id." as ".$loguserid);
952 switch ($logvalue) {
953 case 3:
954 $logname = $logusername;
955 break;
956 case 2:
957 $logname = $logname;
958 break;
959 case 1:
960 default:
961 $logname = $loguserid;
962 break;
964 if ($logmethod == 'apache') {
965 apache_note('MOODLEUSER', $logname);
968 if ($logmethod == 'header') {
969 header("X-MOODLEUSER: $logname");
974 // Ensure the urlrewriteclass is setup correctly (to avoid crippling site).
975 if (isset($CFG->urlrewriteclass)) {
976 if (!class_exists($CFG->urlrewriteclass)) {
977 debugging("urlrewriteclass {$CFG->urlrewriteclass} was not found, disabling.");
978 unset($CFG->urlrewriteclass);
979 } else if (!in_array('core\output\url_rewriter', class_implements($CFG->urlrewriteclass))) {
980 debugging("{$CFG->urlrewriteclass} does not implement core\output\url_rewriter, disabling.", DEBUG_DEVELOPER);
981 unset($CFG->urlrewriteclass);
985 // Use a custom script replacement if one exists
986 if (!empty($CFG->customscripts)) {
987 if (($customscript = custom_script_path()) !== false) {
988 require ($customscript);
992 if (PHPUNIT_TEST) {
993 // no ip blocking, these are CLI only
994 } else if (CLI_SCRIPT and !defined('WEB_CRON_EMULATED_CLI')) {
995 // no ip blocking
996 } else if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
997 // in this case, ip in allowed list will be performed first
998 // for example, client IP is 192.168.1.1
999 // 192.168 subnet is an entry in allowed list
1000 // 192.168.1.1 is banned in blocked list
1001 // This ip will be banned finally
1002 if (!empty($CFG->allowedip)) {
1003 if (!remoteip_in_list($CFG->allowedip)) {
1004 die(get_string('ipblocked', 'admin'));
1007 // need further check, client ip may a part of
1008 // allowed subnet, but a IP address are listed
1009 // in blocked list.
1010 if (!empty($CFG->blockedip)) {
1011 if (remoteip_in_list($CFG->blockedip)) {
1012 die(get_string('ipblocked', 'admin'));
1016 } else {
1017 // in this case, IPs in blocked list will be performed first
1018 // for example, client IP is 192.168.1.1
1019 // 192.168 subnet is an entry in blocked list
1020 // 192.168.1.1 is allowed in allowed list
1021 // This ip will be allowed finally
1022 if (!empty($CFG->blockedip)) {
1023 if (remoteip_in_list($CFG->blockedip)) {
1024 // if the allowed ip list is not empty
1025 // IPs are not included in the allowed list will be
1026 // blocked too
1027 if (!empty($CFG->allowedip)) {
1028 if (!remoteip_in_list($CFG->allowedip)) {
1029 die(get_string('ipblocked', 'admin'));
1031 } else {
1032 die(get_string('ipblocked', 'admin'));
1036 // if blocked list is null
1037 // allowed list should be tested
1038 if(!empty($CFG->allowedip)) {
1039 if (!remoteip_in_list($CFG->allowedip)) {
1040 die(get_string('ipblocked', 'admin'));
1046 // // try to detect IE6 and prevent gzip because it is extremely buggy browser
1047 if (!empty($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false) {
1048 ini_set('zlib.output_compression', 'Off');
1049 if (function_exists('apache_setenv')) {
1050 apache_setenv('no-gzip', 1);
1054 // Switch to CLI maintenance mode if required, we need to do it here after all the settings are initialised.
1055 if (isset($CFG->maintenance_later) and $CFG->maintenance_later <= time()) {
1056 if (!file_exists("$CFG->dataroot/climaintenance.html")) {
1057 require_once("$CFG->libdir/adminlib.php");
1058 enable_cli_maintenance_mode();
1060 unset_config('maintenance_later');
1061 if (AJAX_SCRIPT) {
1062 die;
1063 } else if (!CLI_SCRIPT) {
1064 redirect(new moodle_url('/'));
1068 // Add behat_shutdown_function to shutdown manager, so we can capture php errors,
1069 // but not necessary for behat CLI command as it's being captured by behat process.
1070 if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST')) {
1071 core_shutdown_manager::register_function('behat_shutdown_function');
1074 // note: we can not block non utf-8 installations here, because empty mysql database
1075 // might be converted to utf-8 in admin/index.php during installation
1079 // this is a funny trick to make Eclipse believe that $OUTPUT and other globals
1080 // contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
1081 if (false) {
1082 $DB = new moodle_database();
1083 $OUTPUT = new core_renderer(null, null);
1084 $PAGE = new moodle_page();