Merge branch 'MDL-50642_28' of https://github.com/ecampbell/moodle into MOODLE_28_STABLE
[moodle.git] / lib / setup.php
blobfe128e817e0b64405e7fb7f159a81ff2a707a43f
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(dirname(__FILE__));
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');
83 if (behat_is_test_site()) {
84 // Checking the integrity of the provided $CFG->behat_* vars and the
85 // selected wwwroot to prevent conflicts with production and phpunit environments.
86 behat_check_config_vars();
88 // Check that the directory does not contains other things.
89 if (!file_exists("$CFG->behat_dataroot/behattestdir.txt")) {
90 if ($dh = opendir($CFG->behat_dataroot)) {
91 while (($file = readdir($dh)) !== false) {
92 if ($file === 'behat' or $file === '.' or $file === '..' or $file === '.DS_Store') {
93 continue;
95 behat_error(BEHAT_EXITCODE_CONFIG, '$CFG->behat_dataroot directory is not empty, ensure this is the directory where you want to install behat test dataroot');
97 closedir($dh);
98 unset($dh);
99 unset($file);
102 if (defined('BEHAT_UTIL')) {
103 // Now we create dataroot directory structure for behat tests.
104 testing_initdataroot($CFG->behat_dataroot, 'behat');
105 } else {
106 behat_error(BEHAT_EXITCODE_INSTALL);
110 if (!defined('BEHAT_UTIL') and !defined('BEHAT_TEST')) {
111 // Somebody tries to access test site directly, tell them if not enabled.
112 if (!file_exists($CFG->behat_dataroot . '/behat/test_environment_enabled.txt')) {
113 behat_error(BEHAT_EXITCODE_CONFIG, 'Behat is configured but not enabled on this test site.');
117 // Constant used to inform that the behat test site is being used,
118 // this includes all the processes executed by the behat CLI command like
119 // the site reset, the steps executed by the browser drivers when simulating
120 // a user session and a real session when browsing manually to $CFG->behat_wwwroot
121 // like the browser driver does automatically.
122 // Different from BEHAT_TEST as only this last one can perform CLI
123 // actions like reset the site or use data generators.
124 define('BEHAT_SITE_RUNNING', true);
126 // Clean extra config.php settings.
127 behat_clean_init_config();
129 // Now we can begin switching $CFG->X for $CFG->behat_X.
130 $CFG->wwwroot = $CFG->behat_wwwroot;
131 $CFG->prefix = $CFG->behat_prefix;
132 $CFG->dataroot = $CFG->behat_dataroot;
136 // Force timezone to be Australia/Perth for behat tests, so we don't get time zone problems.
137 if (defined('BEHAT_SITE_RUNNING') || defined('BEHAT_TEST') || defined('BEHAT_UTIL')) {
138 @date_default_timezone_set('Australia/Perth');
141 // Normalise dataroot - we do not want any symbolic links, trailing / or any other weirdness there
142 if (!isset($CFG->dataroot)) {
143 if (isset($_SERVER['REMOTE_ADDR'])) {
144 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
146 echo('Fatal error: $CFG->dataroot is not specified in config.php! Exiting.'."\n");
147 exit(1);
149 $CFG->dataroot = realpath($CFG->dataroot);
150 if ($CFG->dataroot === false) {
151 if (isset($_SERVER['REMOTE_ADDR'])) {
152 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
154 echo('Fatal error: $CFG->dataroot is not configured properly, directory does not exist or is not accessible! Exiting.'."\n");
155 exit(1);
156 } else if (!is_writable($CFG->dataroot)) {
157 if (isset($_SERVER['REMOTE_ADDR'])) {
158 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
160 echo('Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.'."\n");
161 exit(1);
164 // wwwroot is mandatory
165 if (!isset($CFG->wwwroot) or $CFG->wwwroot === 'http://example.com/moodle') {
166 if (isset($_SERVER['REMOTE_ADDR'])) {
167 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
169 echo('Fatal error: $CFG->wwwroot is not configured! Exiting.'."\n");
170 exit(1);
173 // Make sure there is some database table prefix.
174 if (!isset($CFG->prefix)) {
175 $CFG->prefix = '';
178 // Define admin directory
179 if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
180 $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
183 // Set up some paths.
184 $CFG->libdir = $CFG->dirroot .'/lib';
186 // Allow overriding of tempdir but be backwards compatible
187 if (!isset($CFG->tempdir)) {
188 $CFG->tempdir = "$CFG->dataroot/temp";
191 // Allow overriding of cachedir but be backwards compatible
192 if (!isset($CFG->cachedir)) {
193 $CFG->cachedir = "$CFG->dataroot/cache";
196 // Allow overriding of localcachedir.
197 if (!isset($CFG->localcachedir)) {
198 $CFG->localcachedir = "$CFG->dataroot/localcache";
201 // Location of all languages except core English pack.
202 if (!isset($CFG->langotherroot)) {
203 $CFG->langotherroot = $CFG->dataroot.'/lang';
206 // Location of local lang pack customisations (dirs with _local suffix).
207 if (!isset($CFG->langlocalroot)) {
208 $CFG->langlocalroot = $CFG->dataroot.'/lang';
211 // The current directory in PHP version 4.3.0 and above isn't necessarily the
212 // directory of the script when run from the command line. The require_once()
213 // would fail, so we'll have to chdir()
214 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
215 // do it only once - skip the second time when continuing after prevous abort
216 if (!defined('ABORT_AFTER_CONFIG') and !defined('ABORT_AFTER_CONFIG_CANCEL')) {
217 chdir(dirname($_SERVER['argv'][0]));
221 // sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
222 ini_set('precision', 14); // needed for upgrades and gradebook
223 ini_set('serialize_precision', 17); // Make float serialization consistent on all systems.
225 // Scripts may request no debug and error messages in output
226 // please note it must be defined before including the config.php script
227 // and in some cases you also need to set custom default exception handler
228 if (!defined('NO_DEBUG_DISPLAY')) {
229 if (defined('AJAX_SCRIPT') and AJAX_SCRIPT) {
230 // Moodle AJAX scripts are expected to return json data, any PHP notices or errors break it badly,
231 // developers simply must learn to watch error log.
232 define('NO_DEBUG_DISPLAY', true);
233 } else {
234 define('NO_DEBUG_DISPLAY', false);
238 // Some scripts such as upgrade may want to prevent output buffering
239 if (!defined('NO_OUTPUT_BUFFERING')) {
240 define('NO_OUTPUT_BUFFERING', false);
243 // PHPUnit tests need custom init
244 if (!defined('PHPUNIT_TEST')) {
245 define('PHPUNIT_TEST', false);
248 // Performance tests needs to always display performance info, even in redirections.
249 if (!defined('MDL_PERF_TEST')) {
250 define('MDL_PERF_TEST', false);
251 } else {
252 // We force the ones we need.
253 if (!defined('MDL_PERF')) {
254 define('MDL_PERF', true);
256 if (!defined('MDL_PERFDB')) {
257 define('MDL_PERFDB', true);
259 if (!defined('MDL_PERFTOFOOT')) {
260 define('MDL_PERFTOFOOT', true);
264 // When set to true MUC (Moodle caching) will be disabled as much as possible.
265 // A special cache factory will be used to handle this situation and will use special "disabled" equivalents objects.
266 // This ensure we don't attempt to read or create the config file, don't use stores, don't provide persistence or
267 // storage of any kind.
268 if (!defined('CACHE_DISABLE_ALL')) {
269 define('CACHE_DISABLE_ALL', false);
272 // When set to true MUC (Moodle caching) will not use any of the defined or default stores.
273 // The Cache API will continue to function however this will force the use of the cachestore_dummy so all requests
274 // will be interacting with a static property and will never go to the proper cache stores.
275 // Useful if you need to avoid the stores for one reason or another.
276 if (!defined('CACHE_DISABLE_STORES')) {
277 define('CACHE_DISABLE_STORES', false);
280 // Servers should define a default timezone in php.ini, but if they don't then make sure something is defined.
281 // This is a quick hack. Ideally we should ask the admin for a value. See MDL-22625 for more on this.
282 if (function_exists('date_default_timezone_set') and function_exists('date_default_timezone_get')) {
283 $olddebug = error_reporting(0);
284 date_default_timezone_set(date_default_timezone_get());
285 error_reporting($olddebug);
286 unset($olddebug);
289 // Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
290 // In your new CLI scripts just add "define('CLI_SCRIPT', true);" before requiring config.php.
291 // Please note that one script can not be accessed from both CLI and web interface.
292 if (!defined('CLI_SCRIPT')) {
293 define('CLI_SCRIPT', false);
295 if (defined('WEB_CRON_EMULATED_CLI')) {
296 if (!isset($_SERVER['REMOTE_ADDR'])) {
297 echo('Web cron can not be executed as CLI script any more, please use admin/cli/cron.php instead'."\n");
298 exit(1);
300 } else if (isset($_SERVER['REMOTE_ADDR'])) {
301 if (CLI_SCRIPT) {
302 echo('Command line scripts can not be executed from the web interface');
303 exit(1);
305 } else {
306 if (!CLI_SCRIPT) {
307 echo('Command line scripts must define CLI_SCRIPT before requiring config.php'."\n");
308 exit(1);
312 // All web service requests have WS_SERVER == true.
313 if (!defined('WS_SERVER')) {
314 define('WS_SERVER', false);
317 // Detect CLI maintenance mode - this is useful when you need to mess with database, such as during upgrades
318 if (file_exists("$CFG->dataroot/climaintenance.html")) {
319 if (!CLI_SCRIPT) {
320 header('Content-type: text/html; charset=utf-8');
321 header('X-UA-Compatible: IE=edge');
322 /// Headers to make it not cacheable and json
323 header('Cache-Control: no-store, no-cache, must-revalidate');
324 header('Cache-Control: post-check=0, pre-check=0', false);
325 header('Pragma: no-cache');
326 header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
327 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
328 header('Accept-Ranges: none');
329 readfile("$CFG->dataroot/climaintenance.html");
330 die;
331 } else {
332 if (!defined('CLI_MAINTENANCE')) {
333 define('CLI_MAINTENANCE', true);
336 } else {
337 if (!defined('CLI_MAINTENANCE')) {
338 define('CLI_MAINTENANCE', false);
342 if (CLI_SCRIPT) {
343 // sometimes people use different PHP binary for web and CLI, make 100% sure they have the supported PHP version
344 if (version_compare(phpversion(), '5.4.4') < 0) {
345 $phpversion = phpversion();
346 // do NOT localise - lang strings would not work here and we CAN NOT move it to later place
347 echo "Moodle 2.7 or later requires at least PHP 5.4.4 (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);
353 // Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
354 if (!defined('AJAX_SCRIPT')) {
355 define('AJAX_SCRIPT', false);
358 // Exact version of currently used yui2 and 3 library.
359 $CFG->yui2version = '2.9.0';
360 $CFG->yui3version = '3.17.2';
362 // Patching the upstream YUI release.
363 // For important information on patching YUI modules, please see http://docs.moodle.org/dev/YUI/Patching.
364 // If we need to patch a YUI modules between official YUI releases, the yuipatchlevel will need to be manually
365 // incremented here. The module will also need to be listed in the yuipatchedmodules.
366 // When upgrading to a subsequent version of YUI, these should be reset back to 0 and an empty array.
367 $CFG->yuipatchlevel = 0;
368 $CFG->yuipatchedmodules = array(
371 // Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides.
372 if (!isset($CFG->config_php_settings)) {
373 $CFG->config_php_settings = (array)$CFG;
374 // Forced plugin settings override values from config_plugins table.
375 unset($CFG->config_php_settings['forced_plugin_settings']);
376 if (!isset($CFG->forced_plugin_settings)) {
377 $CFG->forced_plugin_settings = array();
381 if (isset($CFG->debug)) {
382 $CFG->debug = (int)$CFG->debug;
383 } else {
384 $CFG->debug = 0;
386 $CFG->debugdeveloper = (($CFG->debug & (E_ALL | E_STRICT)) === (E_ALL | E_STRICT)); // DEBUG_DEVELOPER is not available yet.
388 if (!defined('MOODLE_INTERNAL')) { // Necessary because cli installer has to define it earlier.
389 /** Used by library scripts to check they are being called by Moodle. */
390 define('MOODLE_INTERNAL', true);
393 // core_component can be used in any scripts, it does not need anything else.
394 require_once($CFG->libdir .'/classes/component.php');
396 // special support for highly optimised scripts that do not need libraries and DB connection
397 if (defined('ABORT_AFTER_CONFIG')) {
398 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
399 // hide debugging if not enabled in config.php - we do not want to disclose sensitive info
400 error_reporting($CFG->debug);
401 if (NO_DEBUG_DISPLAY) {
402 // Some parts of Moodle cannot display errors and debug at all.
403 ini_set('display_errors', '0');
404 ini_set('log_errors', '1');
405 } else if (empty($CFG->debugdisplay)) {
406 ini_set('display_errors', '0');
407 ini_set('log_errors', '1');
408 } else {
409 ini_set('display_errors', '1');
411 require_once("$CFG->dirroot/lib/configonlylib.php");
412 return;
416 // Early profiling start, based exclusively on config.php $CFG settings
417 if (!empty($CFG->earlyprofilingenabled)) {
418 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
419 profiling_start();
423 * Database connection. Used for all access to the database.
424 * @global moodle_database $DB
425 * @name $DB
427 global $DB;
430 * Moodle's wrapper round PHP's $_SESSION.
432 * @global object $SESSION
433 * @name $SESSION
435 global $SESSION;
438 * Holds the user table record for the current user. Will be the 'guest'
439 * user record for people who are not logged in.
441 * $USER is stored in the session.
443 * Items found in the user record:
444 * - $USER->email - The user's email address.
445 * - $USER->id - The unique integer identified of this user in the 'user' table.
446 * - $USER->email - The user's email address.
447 * - $USER->firstname - The user's first name.
448 * - $USER->lastname - The user's last name.
449 * - $USER->username - The user's login username.
450 * - $USER->secret - The user's ?.
451 * - $USER->lang - The user's language choice.
453 * @global object $USER
454 * @name $USER
456 global $USER;
459 * Frontpage course record
461 global $SITE;
464 * A central store of information about the current page we are
465 * generating in response to the user's request.
467 * @global moodle_page $PAGE
468 * @name $PAGE
470 global $PAGE;
473 * The current course. An alias for $PAGE->course.
474 * @global object $COURSE
475 * @name $COURSE
477 global $COURSE;
480 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
481 * it to generate HTML for output.
483 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
484 * for the magic that does that. After $OUTPUT has been initialised, any attempt
485 * to change something that affects the current theme ($PAGE->course, logged in use,
486 * httpsrequried ... will result in an exception.)
488 * Please note the $OUTPUT is replacing the old global $THEME object.
490 * @global object $OUTPUT
491 * @name $OUTPUT
493 global $OUTPUT;
496 * Full script path including all params, slash arguments, scheme and host.
498 * Note: Do NOT use for getting of current page URL or detection of https,
499 * instead use $PAGE->url or is_https().
501 * @global string $FULLME
502 * @name $FULLME
504 global $FULLME;
507 * Script path including query string and slash arguments without host.
508 * @global string $ME
509 * @name $ME
511 global $ME;
514 * $FULLME without slasharguments and query string.
515 * @global string $FULLSCRIPT
516 * @name $FULLSCRIPT
518 global $FULLSCRIPT;
521 * Relative moodle script path '/course/view.php'
522 * @global string $SCRIPT
523 * @name $SCRIPT
525 global $SCRIPT;
527 // Set httpswwwroot default value (this variable will replace $CFG->wwwroot
528 // inside some URLs used in HTTPSPAGEREQUIRED pages.
529 $CFG->httpswwwroot = $CFG->wwwroot;
531 require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
533 if (NO_OUTPUT_BUFFERING) {
534 // we have to call this always before starting session because it discards headers!
535 disable_output_buffering();
538 // Increase memory limits if possible
539 raise_memory_limit(MEMORY_STANDARD);
541 // Time to start counting
542 init_performance_info();
544 // Put $OUTPUT in place, so errors can be displayed.
545 $OUTPUT = new bootstrap_renderer();
547 // set handler for uncaught exceptions - equivalent to print_error() call
548 if (!PHPUNIT_TEST or PHPUNIT_UTIL) {
549 set_exception_handler('default_exception_handler');
550 set_error_handler('default_error_handler', E_ALL | E_STRICT);
553 // Acceptance tests needs special output to capture the errors,
554 // but not necessary for behat CLI command.
555 if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST')) {
556 require_once(__DIR__ . '/behat/lib.php');
557 set_error_handler('behat_error_handler', E_ALL | E_STRICT);
560 // If there are any errors in the standard libraries we want to know!
561 error_reporting(E_ALL | E_STRICT);
563 // Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
564 // http://www.google.com/webmasters/faq.html#prefetchblock
565 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
566 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
567 echo('Prefetch request forbidden.');
568 exit(1);
571 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
572 //the problem is that we need specific version of quickforms and hacked excel files :-(
573 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
574 //point zend include path to moodles lib/zend so that includes and requires will search there for files before anywhere else
575 //please note zend library is supposed to be used only from web service protocol classes, it may be removed in future
576 ini_set('include_path', $CFG->libdir.'/zend' . PATH_SEPARATOR . ini_get('include_path'));
578 // Register our classloader, in theory somebody might want to replace it to load other hacked core classes.
579 if (defined('COMPONENT_CLASSLOADER')) {
580 spl_autoload_register(COMPONENT_CLASSLOADER);
581 } else {
582 spl_autoload_register('core_component::classloader');
585 // Load up standard libraries
586 require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output
587 require_once($CFG->libdir .'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
588 require_once($CFG->libdir .'/weblib.php'); // Functions relating to HTTP and content
589 require_once($CFG->libdir .'/outputlib.php'); // Functions for generating output
590 require_once($CFG->libdir .'/navigationlib.php'); // Class for generating Navigation structure
591 require_once($CFG->libdir .'/dmllib.php'); // Database access
592 require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
593 require_once($CFG->libdir .'/accesslib.php'); // Access control functions
594 require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
595 require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
596 require_once($CFG->libdir .'/enrollib.php'); // Enrolment related functions
597 require_once($CFG->libdir .'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
598 require_once($CFG->libdir .'/blocklib.php'); // Library for controlling blocks
599 require_once($CFG->libdir .'/eventslib.php'); // Events functions
600 require_once($CFG->libdir .'/grouplib.php'); // Groups functions
601 require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie related stuff
602 require_once($CFG->libdir .'/editorlib.php'); // All text editor related functions and classes
603 require_once($CFG->libdir .'/messagelib.php'); // Messagelib functions
604 require_once($CFG->libdir .'/modinfolib.php'); // Cached information on course-module instances
605 require_once($CFG->dirroot.'/cache/lib.php'); // Cache API
607 // make sure PHP is not severly misconfigured
608 setup_validate_php_configuration();
610 // Connect to the database
611 setup_DB();
613 if (PHPUNIT_TEST and !PHPUNIT_UTIL) {
614 // make sure tests do not run in parallel
615 test_lock::acquire('phpunit');
616 $dbhash = null;
617 try {
618 if ($dbhash = $DB->get_field('config', 'value', array('name'=>'phpunittest'))) {
619 // reset DB tables
620 phpunit_util::reset_database();
622 } catch (Exception $e) {
623 if ($dbhash) {
624 // we ned to reinit if reset fails
625 $DB->set_field('config', 'value', 'na', array('name'=>'phpunittest'));
628 unset($dbhash);
631 // Load up any configuration from the config table or MUC cache.
632 if (PHPUNIT_TEST) {
633 phpunit_util::initialise_cfg();
634 } else {
635 initialise_cfg();
638 if (isset($CFG->debug)) {
639 $CFG->debug = (int)$CFG->debug;
640 error_reporting($CFG->debug);
641 } else {
642 $CFG->debug = 0;
644 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
646 // Find out if PHP configured to display warnings,
647 // this is a security problem because some moodle scripts may
648 // disclose sensitive information.
649 if (ini_get_bool('display_errors')) {
650 define('WARN_DISPLAY_ERRORS_ENABLED', true);
652 // If we want to display Moodle errors, then try and set PHP errors to match.
653 if (!isset($CFG->debugdisplay)) {
654 // Keep it "as is" during installation.
655 } else if (NO_DEBUG_DISPLAY) {
656 // Some parts of Moodle cannot display errors and debug at all.
657 ini_set('display_errors', '0');
658 ini_set('log_errors', '1');
659 } else if (empty($CFG->debugdisplay)) {
660 ini_set('display_errors', '0');
661 ini_set('log_errors', '1');
662 } else {
663 // This is very problematic in XHTML strict mode!
664 ini_set('display_errors', '1');
667 // Register our shutdown manager, do NOT use register_shutdown_function().
668 core_shutdown_manager::initialize();
670 // Verify upgrade is not running unless we are in a script that needs to execute in any case
671 if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
672 if ($CFG->upgraderunning < time()) {
673 unset_config('upgraderunning');
674 } else {
675 print_error('upgraderunning');
679 // enable circular reference collector in PHP 5.3,
680 // it helps a lot when using large complex OOP structures such as in amos or gradebook
681 if (function_exists('gc_enable')) {
682 gc_enable();
685 // detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
686 if (!empty($CFG->version) and $CFG->version < 2007101509) {
687 print_error('upgraderequires19', 'error');
688 die;
691 // Calculate and set $CFG->ostype to be used everywhere. Possible values are:
692 // - WINDOWS: for any Windows flavour.
693 // - UNIX: for the rest
694 // Also, $CFG->os can continue being used if more specialization is required
695 if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
696 $CFG->ostype = 'WINDOWS';
697 } else {
698 $CFG->ostype = 'UNIX';
700 $CFG->os = PHP_OS;
702 // Configure ampersands in URLs
703 ini_set('arg_separator.output', '&amp;');
705 // Work around for a PHP bug see MDL-11237
706 ini_set('pcre.backtrack_limit', 20971520); // 20 MB
708 // Location of standard files
709 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
710 $CFG->moddata = 'moddata';
712 // neutralise nasty chars in PHP_SELF
713 if (isset($_SERVER['PHP_SELF'])) {
714 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
715 if ($phppos !== false) {
716 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
718 unset($phppos);
721 // initialise ME's - this must be done BEFORE starting of session!
722 initialise_fullme();
724 // define SYSCONTEXTID in config.php if you want to save some queries,
725 // after install it must match the system context record id.
726 if (!defined('SYSCONTEXTID')) {
727 context_system::instance();
730 // Defining the site - aka frontpage course
731 try {
732 $SITE = get_site();
733 } catch (moodle_exception $e) {
734 $SITE = null;
735 if (empty($CFG->version)) {
736 $SITE = new stdClass();
737 $SITE->id = 1;
738 $SITE->shortname = null;
739 } else {
740 throw $e;
743 // And the 'default' course - this will usually get reset later in require_login() etc.
744 $COURSE = clone($SITE);
745 // Id of the frontpage course.
746 define('SITEID', $SITE->id);
748 // init session prevention flag - this is defined on pages that do not want session
749 if (CLI_SCRIPT) {
750 // no sessions in CLI scripts possible
751 define('NO_MOODLE_COOKIES', true);
753 } else if (WS_SERVER) {
754 // No sessions possible in web services.
755 define('NO_MOODLE_COOKIES', true);
757 } else if (!defined('NO_MOODLE_COOKIES')) {
758 if (empty($CFG->version) or $CFG->version < 2009011900) {
759 // no session before sessions table gets created
760 define('NO_MOODLE_COOKIES', true);
761 } else if (CLI_SCRIPT) {
762 // CLI scripts can not have session
763 define('NO_MOODLE_COOKIES', true);
764 } else {
765 define('NO_MOODLE_COOKIES', false);
769 // Start session and prepare global $SESSION, $USER.
770 if (empty($CFG->sessiontimeout)) {
771 $CFG->sessiontimeout = 7200;
773 \core\session\manager::start();
775 // Set default content type and encoding, developers are still required to use
776 // echo $OUTPUT->header() everywhere, anything that gets set later should override these headers.
777 // This is intended to mitigate some security problems.
778 if (AJAX_SCRIPT) {
779 if (!core_useragent::supports_json_contenttype()) {
780 // Some bloody old IE.
781 @header('Content-type: text/plain; charset=utf-8');
782 @header('X-Content-Type-Options: nosniff');
783 } else if (!empty($_FILES)) {
784 // Some ajax code may have problems with json and file uploads.
785 @header('Content-type: text/plain; charset=utf-8');
786 } else {
787 @header('Content-type: application/json; charset=utf-8');
789 } else if (!CLI_SCRIPT) {
790 @header('Content-type: text/html; charset=utf-8');
793 // Initialise some variables that are supposed to be set in config.php only.
794 if (!isset($CFG->filelifetime)) {
795 $CFG->filelifetime = 60*60*6;
798 // Late profiling, only happening if early one wasn't started
799 if (!empty($CFG->profilingenabled)) {
800 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
801 profiling_start();
804 // Hack to get around max_input_vars restrictions,
805 // we need to do this after session init to have some basic DDoS protection.
806 workaround_max_input_vars();
808 // Process theme change in the URL.
809 if (!empty($CFG->allowthemechangeonurl) and !empty($_GET['theme'])) {
810 // we have to use _GET directly because we do not want this to interfere with _POST
811 $urlthemename = optional_param('theme', '', PARAM_PLUGIN);
812 try {
813 $themeconfig = theme_config::load($urlthemename);
814 // Makes sure the theme can be loaded without errors.
815 if ($themeconfig->name === $urlthemename) {
816 $SESSION->theme = $urlthemename;
817 } else {
818 unset($SESSION->theme);
820 unset($themeconfig);
821 unset($urlthemename);
822 } catch (Exception $e) {
823 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
826 unset($urlthemename);
828 // Ensure a valid theme is set.
829 if (!isset($CFG->theme)) {
830 $CFG->theme = 'clean';
833 // Set language/locale of printed times. If user has chosen a language that
834 // that is different from the site language, then use the locale specified
835 // in the language file. Otherwise, if the admin hasn't specified a locale
836 // then use the one from the default language. Otherwise (and this is the
837 // majority of cases), use the stored locale specified by admin.
838 // note: do not accept lang parameter from POST
839 if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
840 if (get_string_manager()->translation_exists($lang, false)) {
841 $SESSION->lang = $lang;
844 unset($lang);
846 // PARAM_SAFEDIR used instead of PARAM_LANG because using PARAM_LANG results
847 // in an empty string being returned when a non-existant language is specified,
848 // which would make it necessary to log out to undo the forcelang setting.
849 // With PARAM_SAFEDIR, it's possible to specify ?forcelang=none to drop the forcelang effect.
850 if ($forcelang = optional_param('forcelang', '', PARAM_SAFEDIR)) {
851 if (isloggedin()
852 && get_string_manager()->translation_exists($forcelang, false)
853 && has_capability('moodle/site:forcelanguage', context_system::instance())) {
854 $SESSION->forcelang = $forcelang;
855 } else if (isset($SESSION->forcelang)) {
856 unset($SESSION->forcelang);
859 unset($forcelang);
861 setup_lang_from_browser();
863 if (empty($CFG->lang)) {
864 if (empty($SESSION->lang)) {
865 $CFG->lang = 'en';
866 } else {
867 $CFG->lang = $SESSION->lang;
871 // Set the default site locale, a lot of the stuff may depend on this
872 // it is definitely too late to call this first in require_login()!
873 moodle_setlocale();
875 // Create the $PAGE global - this marks the PAGE and OUTPUT fully initialised, this MUST be done at the end of setup!
876 if (!empty($CFG->moodlepageclass)) {
877 if (!empty($CFG->moodlepageclassfile)) {
878 require_once($CFG->moodlepageclassfile);
880 $classname = $CFG->moodlepageclass;
881 } else {
882 $classname = 'moodle_page';
884 $PAGE = new $classname();
885 unset($classname);
888 if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
889 if ($CFG->theme == 'standard') { // Temporary measure to help with XHTML validation
890 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
891 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
892 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
893 if ($user = get_complete_user_data("username", "w3cvalidator")) {
894 $user->ignoresesskey = true;
895 } else {
896 $user = guest_user();
898 \core\session\manager::set_user($user);
904 // Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
905 // LogFormat to get the current logged in username in moodle.
906 if ($USER && function_exists('apache_note')
907 && !empty($CFG->apacheloguser) && isset($USER->username)) {
908 $apachelog_userid = $USER->id;
909 $apachelog_username = clean_filename($USER->username);
910 $apachelog_name = '';
911 if (isset($USER->firstname)) {
912 // We can assume both will be set
913 // - even if to empty.
914 $apachelog_name = clean_filename($USER->firstname . " " .
915 $USER->lastname);
917 if (\core\session\manager::is_loggedinas()) {
918 $realuser = \core\session\manager::get_realuser();
919 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
920 $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
921 $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
923 switch ($CFG->apacheloguser) {
924 case 3:
925 $logname = $apachelog_username;
926 break;
927 case 2:
928 $logname = $apachelog_name;
929 break;
930 case 1:
931 default:
932 $logname = $apachelog_userid;
933 break;
935 apache_note('MOODLEUSER', $logname);
938 // Use a custom script replacement if one exists
939 if (!empty($CFG->customscripts)) {
940 if (($customscript = custom_script_path()) !== false) {
941 require ($customscript);
945 if (PHPUNIT_TEST) {
946 // no ip blocking, these are CLI only
947 } else if (CLI_SCRIPT and !defined('WEB_CRON_EMULATED_CLI')) {
948 // no ip blocking
949 } else if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
950 // in this case, ip in allowed list will be performed first
951 // for example, client IP is 192.168.1.1
952 // 192.168 subnet is an entry in allowed list
953 // 192.168.1.1 is banned in blocked list
954 // This ip will be banned finally
955 if (!empty($CFG->allowedip)) {
956 if (!remoteip_in_list($CFG->allowedip)) {
957 die(get_string('ipblocked', 'admin'));
960 // need further check, client ip may a part of
961 // allowed subnet, but a IP address are listed
962 // in blocked list.
963 if (!empty($CFG->blockedip)) {
964 if (remoteip_in_list($CFG->blockedip)) {
965 die(get_string('ipblocked', 'admin'));
969 } else {
970 // in this case, IPs in blocked list will be performed first
971 // for example, client IP is 192.168.1.1
972 // 192.168 subnet is an entry in blocked list
973 // 192.168.1.1 is allowed in allowed list
974 // This ip will be allowed finally
975 if (!empty($CFG->blockedip)) {
976 if (remoteip_in_list($CFG->blockedip)) {
977 // if the allowed ip list is not empty
978 // IPs are not included in the allowed list will be
979 // blocked too
980 if (!empty($CFG->allowedip)) {
981 if (!remoteip_in_list($CFG->allowedip)) {
982 die(get_string('ipblocked', 'admin'));
984 } else {
985 die(get_string('ipblocked', 'admin'));
989 // if blocked list is null
990 // allowed list should be tested
991 if(!empty($CFG->allowedip)) {
992 if (!remoteip_in_list($CFG->allowedip)) {
993 die(get_string('ipblocked', 'admin'));
999 // // try to detect IE6 and prevent gzip because it is extremely buggy browser
1000 if (!empty($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false) {
1001 ini_set('zlib.output_compression', 'Off');
1002 if (function_exists('apache_setenv')) {
1003 apache_setenv('no-gzip', 1);
1007 // Switch to CLI maintenance mode if required, we need to do it here after all the settings are initialised.
1008 if (isset($CFG->maintenance_later) and $CFG->maintenance_later <= time()) {
1009 if (!file_exists("$CFG->dataroot/climaintenance.html")) {
1010 require_once("$CFG->libdir/adminlib.php");
1011 enable_cli_maintenance_mode();
1013 unset_config('maintenance_later');
1014 if (AJAX_SCRIPT) {
1015 die;
1016 } else if (!CLI_SCRIPT) {
1017 redirect(new moodle_url('/'));
1021 // note: we can not block non utf-8 installations here, because empty mysql database
1022 // might be converted to utf-8 in admin/index.php during installation
1026 // this is a funny trick to make Eclipse believe that $OUTPUT and other globals
1027 // contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
1028 if (false) {
1029 $DB = new moodle_database();
1030 $OUTPUT = new core_renderer(null, null);
1031 $PAGE = new moodle_page();