MDL-44599 undeprecate SITEID
[moodle.git] / lib / setup.php
CommitLineData
da8759cb 1<?php
b37eac91 2
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.
14//
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/>.
17
da8759cb 18/**
19 * setup.php - Sets up sessions, connects to databases and so on
20 *
75249234 21 * Normally this is only called by the main config.php file
22 * Normally this file does not need to be edited.
b37eac91 23 *
78bfb562
PS
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
da8759cb 28 */
29
da8759cb 30/**
e1d1b796 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.
33 *
34 * Some typical settings in the $CFG global:
3b5ff37f
PS
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.
3e939871 39 * - $CFG->tempdir - Path to moodle's temp file directory on server's filesystem.
85b38061
PS
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).
e1d1b796 42 *
43 * @global object $CFG
b37eac91 44 * @name $CFG
e1d1b796 45 */
b30fa335 46global $CFG; // this should be done much earlier in config.php before creating new $CFG instance
e1d1b796 47
fe79c400 48if (!isset($CFG)) {
a3d5830a 49 if (defined('PHPUNIT_TEST') and PHPUNIT_TEST) {
fe79c400
PS
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);
55 }
56}
57
3b5ff37f
PS
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__));
61
f46e869d
DM
62// File permissions on created directories in the $CFG->dataroot
63if (!isset($CFG->directorypermissions)) {
64 $CFG->directorypermissions = 02777; // Must be octal (that's why it's here)
65}
66if (!isset($CFG->filepermissions)) {
67 $CFG->filepermissions = ($CFG->directorypermissions & 0666); // strip execute flags
68}
69// Better also set default umask because developers often forget to include directory
70// permissions in mkdir() and chmod() after creating new files.
71if (!isset($CFG->umaskpermissions)) {
72 $CFG->umaskpermissions = (($CFG->directorypermissions & 0777) ^ 0777);
73}
74umask($CFG->umaskpermissions);
75
60129d5d
PS
76if (defined('BEHAT_SITE_RUNNING')) {
77 // We already switched to behat test site previously.
78
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();
87
9bb80d20
PS
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;
94 }
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');
96 }
97 closedir($dh);
98 unset($dh);
99 unset($file);
100 }
101
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);
107 }
108 }
109
60129d5d
PS
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.');
114 }
115 }
116
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);
125
126 // Clean extra config.php settings.
127 behat_clean_init_config();
128
129 // Now we can begin switching $CFG->X for $CFG->behat_X.
130 $CFG->wwwroot = $CFG->behat_wwwroot;
60129d5d
PS
131 $CFG->prefix = $CFG->behat_prefix;
132 $CFG->dataroot = $CFG->behat_dataroot;
133 }
134}
135
3b5ff37f
PS
136// Normalise dataroot - we do not want any symbolic links, trailing / or any other weirdness there
137if (!isset($CFG->dataroot)) {
56953adc
PS
138 if (isset($_SERVER['REMOTE_ADDR'])) {
139 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
140 }
fe79c400 141 echo('Fatal error: $CFG->dataroot is not specified in config.php! Exiting.'."\n");
3b5ff37f
PS
142 exit(1);
143}
144$CFG->dataroot = realpath($CFG->dataroot);
145if ($CFG->dataroot === false) {
56953adc
PS
146 if (isset($_SERVER['REMOTE_ADDR'])) {
147 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
148 }
fe79c400 149 echo('Fatal error: $CFG->dataroot is not configured properly, directory does not exist or is not accessible! Exiting.'."\n");
3b5ff37f 150 exit(1);
8b2ebe7f
PS
151} else if (!is_writable($CFG->dataroot)) {
152 if (isset($_SERVER['REMOTE_ADDR'])) {
153 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
154 }
155 echo('Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.'."\n");
156 exit(1);
3b5ff37f
PS
157}
158
159// wwwroot is mandatory
160if (!isset($CFG->wwwroot) or $CFG->wwwroot === 'http://example.com/moodle') {
56953adc
PS
161 if (isset($_SERVER['REMOTE_ADDR'])) {
162 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
163 }
fe79c400 164 echo('Fatal error: $CFG->wwwroot is not configured! Exiting.'."\n");
3b5ff37f
PS
165 exit(1);
166}
167
96f81ea3
PS
168// Make sure there is some database table prefix.
169if (!isset($CFG->prefix)) {
170 $CFG->prefix = '';
171}
172
3b5ff37f
PS
173// Define admin directory
174if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
175 $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
176}
177
60f2c866
PS
178// Set up some paths.
179$CFG->libdir = $CFG->dirroot .'/lib';
180
383d3884 181// Allow overriding of tempdir but be backwards compatible
3e939871 182if (!isset($CFG->tempdir)) {
383d3884
TL
183 $CFG->tempdir = "$CFG->dataroot/temp";
184}
185
186// Allow overriding of cachedir but be backwards compatible
187if (!isset($CFG->cachedir)) {
188 $CFG->cachedir = "$CFG->dataroot/cache";
3e939871
TL
189}
190
85b38061
PS
191// Allow overriding of localcachedir.
192if (!isset($CFG->localcachedir)) {
193 $CFG->localcachedir = "$CFG->dataroot/localcache";
194}
195
96f81ea3
PS
196// Location of all languages except core English pack.
197if (!isset($CFG->langotherroot)) {
198 $CFG->langotherroot = $CFG->dataroot.'/lang';
199}
200
201// Location of local lang pack customisations (dirs with _local suffix).
202if (!isset($CFG->langlocalroot)) {
203 $CFG->langlocalroot = $CFG->dataroot.'/lang';
204}
205
3b5ff37f
PS
206// The current directory in PHP version 4.3.0 and above isn't necessarily the
207// directory of the script when run from the command line. The require_once()
208// would fail, so we'll have to chdir()
209if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
5bd40408
PS
210 // do it only once - skip the second time when continuing after prevous abort
211 if (!defined('ABORT_AFTER_CONFIG') and !defined('ABORT_AFTER_CONFIG_CANCEL')) {
212 chdir(dirname($_SERVER['argv'][0]));
213 }
3b5ff37f
PS
214}
215
216// sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
27466303 217ini_set('precision', 14); // needed for upgrades and gradebook
404ecca3 218ini_set('serialize_precision', 17); // Make float serialization consistent on all systems.
3b5ff37f
PS
219
220// Scripts may request no debug and error messages in output
221// please note it must be defined before including the config.php script
222// and in some cases you also need to set custom default exception handler
223if (!defined('NO_DEBUG_DISPLAY')) {
cb9ee2a9
PS
224 if (defined('AJAX_SCRIPT') and AJAX_SCRIPT) {
225 // Moodle AJAX scripts are expected to return json data, any PHP notices or errors break it badly,
226 // developers simply must learn to watch error log.
227 define('NO_DEBUG_DISPLAY', true);
228 } else {
229 define('NO_DEBUG_DISPLAY', false);
230 }
3b5ff37f
PS
231}
232
cbad562e
PS
233// Some scripts such as upgrade may want to prevent output buffering
234if (!defined('NO_OUTPUT_BUFFERING')) {
235 define('NO_OUTPUT_BUFFERING', false);
236}
237
5bd40408 238// PHPUnit tests need custom init
a3d5830a
PS
239if (!defined('PHPUNIT_TEST')) {
240 define('PHPUNIT_TEST', false);
5bd40408
PS
241}
242
58a3a34e
DM
243// Performance tests needs to always display performance info, even in redirections.
244if (!defined('MDL_PERF_TEST')) {
245 define('MDL_PERF_TEST', false);
246} else {
247 // We force the ones we need.
248 if (!defined('MDL_PERF')) {
249 define('MDL_PERF', true);
250 }
251 if (!defined('MDL_PERFDB')) {
252 define('MDL_PERFDB', true);
253 }
254 if (!defined('MDL_PERFTOFOOT')) {
255 define('MDL_PERFTOFOOT', true);
256 }
257}
258
94ef67cf
SH
259// When set to true MUC (Moodle caching) will be disabled as much as possible.
260// A special cache factory will be used to handle this situation and will use special "disabled" equivalents objects.
261// This ensure we don't attempt to read or create the config file, don't use stores, don't provide persistence or
262// storage of any kind.
263if (!defined('CACHE_DISABLE_ALL')) {
264 define('CACHE_DISABLE_ALL', false);
265}
266
d6a1f63b 267// When set to true MUC (Moodle caching) will not use any of the defined or default stores.
6fec1820 268// The Cache API will continue to function however this will force the use of the cachestore_dummy so all requests
d6a1f63b
SH
269// will be interacting with a static property and will never go to the proper cache stores.
270// Useful if you need to avoid the stores for one reason or another.
c9f40e77
SH
271if (!defined('CACHE_DISABLE_STORES')) {
272 define('CACHE_DISABLE_STORES', false);
d6a1f63b
SH
273}
274
62c5e654
MD
275// Servers should define a default timezone in php.ini, but if they don't then make sure something is defined.
276// This is a quick hack. Ideally we should ask the admin for a value. See MDL-22625 for more on this.
177b5480 277if (function_exists('date_default_timezone_set') and function_exists('date_default_timezone_get')) {
27466303
PS
278 $olddebug = error_reporting(0);
279 date_default_timezone_set(date_default_timezone_get());
280 error_reporting($olddebug);
281 unset($olddebug);
62c5e654
MD
282}
283
3b5ff37f 284// Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
28bd3d9a
PS
285// In your new CLI scripts just add "define('CLI_SCRIPT', true);" before requiring config.php.
286// Please note that one script can not be accessed from both CLI and web interface.
3b5ff37f 287if (!defined('CLI_SCRIPT')) {
28bd3d9a
PS
288 define('CLI_SCRIPT', false);
289}
290if (defined('WEB_CRON_EMULATED_CLI')) {
291 if (!isset($_SERVER['REMOTE_ADDR'])) {
292 echo('Web cron can not be executed as CLI script any more, please use admin/cli/cron.php instead'."\n");
293 exit(1);
294 }
295} else if (isset($_SERVER['REMOTE_ADDR'])) {
296 if (CLI_SCRIPT) {
297 echo('Command line scripts can not be executed from the web interface');
298 exit(1);
299 }
300} else {
301 if (!CLI_SCRIPT) {
302 echo('Command line scripts must define CLI_SCRIPT before requiring config.php'."\n");
303 exit(1);
3b5ff37f
PS
304 }
305}
306
8820f4e7
PS
307// Detect CLI maintenance mode - this is useful when you need to mess with database, such as during upgrades
308if (file_exists("$CFG->dataroot/climaintenance.html")) {
309 if (!CLI_SCRIPT) {
8a7703ce 310 header('Content-type: text/html; charset=utf-8');
398862b9 311 header('X-UA-Compatible: IE=edge');
8820f4e7 312 /// Headers to make it not cacheable and json
27466303
PS
313 header('Cache-Control: no-store, no-cache, must-revalidate');
314 header('Cache-Control: post-check=0, pre-check=0', false);
315 header('Pragma: no-cache');
316 header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
317 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
318 header('Accept-Ranges: none');
8820f4e7
PS
319 readfile("$CFG->dataroot/climaintenance.html");
320 die;
321 } else {
e4c05ec7
PS
322 if (!defined('CLI_MAINTENANCE')) {
323 define('CLI_MAINTENANCE', true);
324 }
8820f4e7
PS
325 }
326} else {
e4c05ec7
PS
327 if (!defined('CLI_MAINTENANCE')) {
328 define('CLI_MAINTENANCE', false);
329 }
8820f4e7
PS
330}
331
8de5d7b9
PS
332if (CLI_SCRIPT) {
333 // sometimes people use different PHP binary for web and CLI, make 100% sure they have the supported PHP version
dbe0203b 334 if (version_compare(phpversion(), '5.4.4') < 0) {
8de5d7b9
PS
335 $phpversion = phpversion();
336 // do NOT localise - lang strings would not work here and we CAN NOT move it to later place
dbe0203b 337 echo "Moodle 2.7 or later requires at least PHP 5.4.4 (currently using version $phpversion).\n";
8de5d7b9
PS
338 echo "Some servers may have multiple PHP versions installed, are you using the correct executable?\n";
339 exit(1);
340 }
341}
342
3b5ff37f
PS
343// Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
344if (!defined('AJAX_SCRIPT')) {
345 define('AJAX_SCRIPT', false);
346}
347
8a478446 348// Exact version of currently used yui2 and 3 library.
6fc17ca9 349$CFG->yui2version = '2.9.0';
4d24e65c 350$CFG->yui3version = '3.15.0';
60f2c866 351
aea29737
AN
352// Patching the upstream YUI release.
353// For important information on patching YUI modules, please see http://docs.moodle.org/dev/YUI/Patching.
354// If we need to patch a YUI modules between official YUI releases, the yuipatchlevel will need to be manually
355// incremented here. The module will also need to be listed in the yuipatchedmodules.
356// When upgrading to a subsequent version of YUI, these should be reset back to 0 and an empty array.
357$CFG->yuipatchlevel = 0;
358$CFG->yuipatchedmodules = array(
359);
360
96f81ea3
PS
361// Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides.
362if (!isset($CFG->config_php_settings)) {
363 $CFG->config_php_settings = (array)$CFG;
364 // Forced plugin settings override values from config_plugins table.
365 unset($CFG->config_php_settings['forced_plugin_settings']);
366 if (!isset($CFG->forced_plugin_settings)) {
367 $CFG->forced_plugin_settings = array();
368 }
369}
370
371if (isset($CFG->debug)) {
372 $CFG->debug = (int)$CFG->debug;
373} else {
374 $CFG->debug = 0;
375}
ce7b06bc 376$CFG->debugdeveloper = (($CFG->debug & (E_ALL | E_STRICT)) === (E_ALL | E_STRICT)); // DEBUG_DEVELOPER is not available yet.
96f81ea3 377
9240ecbd
PS
378if (!defined('MOODLE_INTERNAL')) { // Necessary because cli installer has to define it earlier.
379 /** Used by library scripts to check they are being called by Moodle. */
380 define('MOODLE_INTERNAL', true);
381}
382
9e19a0f0
PS
383// core_component can be used in any scripts, it does not need anything else.
384require_once($CFG->libdir .'/classes/component.php');
3b5ff37f 385
60f2c866
PS
386// special support for highly optimised scripts that do not need libraries and DB connection
387if (defined('ABORT_AFTER_CONFIG')) {
388 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
0037dcc9 389 // hide debugging if not enabled in config.php - we do not want to disclose sensitive info
96f81ea3 390 error_reporting($CFG->debug);
463a9874
PS
391 if (NO_DEBUG_DISPLAY) {
392 // Some parts of Moodle cannot display errors and debug at all.
393 ini_set('display_errors', '0');
394 ini_set('log_errors', '1');
395 } else if (empty($CFG->debugdisplay)) {
27466303
PS
396 ini_set('display_errors', '0');
397 ini_set('log_errors', '1');
0037dcc9 398 } else {
27466303 399 ini_set('display_errors', '1');
0037dcc9 400 }
60f2c866
PS
401 require_once("$CFG->dirroot/lib/configonlylib.php");
402 return;
403 }
404}
405
c646dd26
EL
406// Early profiling start, based exclusively on config.php $CFG settings
407if (!empty($CFG->earlyprofilingenabled)) {
408 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
38fc0130 409 profiling_start();
c646dd26
EL
410}
411
e1d1b796 412/**
413 * Database connection. Used for all access to the database.
414 * @global moodle_database $DB
b37eac91 415 * @name $DB
e1d1b796 416 */
417global $DB;
418
419/**
420 * Moodle's wrapper round PHP's $_SESSION.
421 *
422 * @global object $SESSION
b37eac91 423 * @name $SESSION
e1d1b796 424 */
425global $SESSION;
426
427/**
428 * Holds the user table record for the current user. Will be the 'guest'
429 * user record for people who are not logged in.
430 *
431 * $USER is stored in the session.
da8759cb 432 *
735b8567 433 * Items found in the user record:
da8759cb 434 * - $USER->email - The user's email address.
435 * - $USER->id - The unique integer identified of this user in the 'user' table.
436 * - $USER->email - The user's email address.
437 * - $USER->firstname - The user's first name.
438 * - $USER->lastname - The user's last name.
439 * - $USER->username - The user's login username.
440 * - $USER->secret - The user's ?.
441 * - $USER->lang - The user's language choice.
442 *
e1d1b796 443 * @global object $USER
b37eac91 444 * @name $USER
da8759cb 445 */
674fb525 446global $USER;
e1d1b796 447
f0f8f9a7
PS
448/**
449 * Frontpage course record
450 */
451global $SITE;
452
c13a5e71 453/**
454 * A central store of information about the current page we are
455 * generating in response to the user's request.
456 *
457 * @global moodle_page $PAGE
b37eac91 458 * @name $PAGE
c13a5e71 459 */
460global $PAGE;
461
da8759cb 462/**
e1d1b796 463 * The current course. An alias for $PAGE->course.
464 * @global object $COURSE
b37eac91 465 * @name $COURSE
da8759cb 466 */
467global $COURSE;
e1d1b796 468
da8759cb 469/**
78946b9b 470 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
34a2777c 471 * it to generate HTML for output.
da8759cb 472 *
c84a2dbe 473 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
474 * for the magic that does that. After $OUTPUT has been initialised, any attempt
475 * to change something that affects the current theme ($PAGE->course, logged in use,
476 * httpsrequried ... will result in an exception.)
34a2777c 477 *
cbcc9852
PS
478 * Please note the $OUTPUT is replacing the old global $THEME object.
479 *
34a2777c 480 * @global object $OUTPUT
481 * @name $OUTPUT
482 */
483global $OUTPUT;
484
b37eac91 485/**
486 * Full script path including all params, slash arguments, scheme and host.
33dca156
PS
487 *
488 * Note: Do NOT use for getting of current page URL or detection of https,
489 * instead use $PAGE->url or strpos($CFG->httpswwwroot, 'https:') === 0
490 *
b37eac91 491 * @global string $FULLME
492 * @name $FULLME
493 */
11e7b506 494global $FULLME;
e1d1b796 495
b37eac91 496/**
497 * Script path including query string and slash arguments without host.
498 * @global string $ME
499 * @name $ME
500 */
11e7b506 501global $ME;
e1d1b796 502
b37eac91 503/**
504 * $FULLME without slasharguments and query string.
505 * @global string $FULLSCRIPT
506 * @name $FULLSCRIPT
507 */
11e7b506 508global $FULLSCRIPT;
e1d1b796 509
b37eac91 510/**
511 * Relative moodle script path '/course/view.php'
512 * @global string $SCRIPT
513 * @name $SCRIPT
514 */
11e7b506 515global $SCRIPT;
9d0dd812 516
4dffc775
PS
517// Set httpswwwroot default value (this variable will replace $CFG->wwwroot
518// inside some URLs used in HTTPSPAGEREQUIRED pages.
519$CFG->httpswwwroot = $CFG->wwwroot;
d3f9f1f8 520
4dffc775 521require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
17da2e6f 522
cbad562e 523if (NO_OUTPUT_BUFFERING) {
871ed458 524 // we have to call this always before starting session because it discards headers!
cbad562e
PS
525 disable_output_buffering();
526}
527
0f0f0768
PS
528// Increase memory limits if possible
529raise_memory_limit(MEMORY_STANDARD);
530
4dffc775
PS
531// Time to start counting
532init_performance_info();
b7009474 533
4dffc775
PS
534// Put $OUTPUT in place, so errors can be displayed.
535$OUTPUT = new bootstrap_renderer();
9d0dd812 536
4c1c9175 537// set handler for uncaught exceptions - equivalent to print_error() call
a3d5830a
PS
538if (!PHPUNIT_TEST or PHPUNIT_UTIL) {
539 set_exception_handler('default_exception_handler');
540 set_error_handler('default_error_handler', E_ALL | E_STRICT);
541}
6800d78e 542
cfcbc34a
DM
543// Acceptance tests needs special output to capture the errors,
544// but not necessary for behat CLI command.
545if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST')) {
90ed22ab
DM
546 require_once(__DIR__ . '/behat/lib.php');
547 set_error_handler('behat_error_handler', E_ALL | E_STRICT);
548}
549
4dffc775 550// If there are any errors in the standard libraries we want to know!
a3d5830a 551error_reporting(E_ALL | E_STRICT);
c84a2dbe 552
4dffc775
PS
553// Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
554// http://www.google.com/webmasters/faq.html#prefetchblock
555if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
556 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
557 echo('Prefetch request forbidden.');
558 exit(1);
559}
b8cea9b2 560
3d732d84
EL
561//point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
562//the problem is that we need specific version of quickforms and hacked excel files :-(
563ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
564//point zend include path to moodles lib/zend so that includes and requires will search there for files before anywhere else
565//please note zend library is supposed to be used only from web service protocol classes, it may be removed in future
566ini_set('include_path', $CFG->libdir.'/zend' . PATH_SEPARATOR . ini_get('include_path'));
567
9e19a0f0
PS
568// Register our classloader, in theory somebody might want to replace it to load other hacked core classes.
569if (defined('COMPONENT_CLASSLOADER')) {
570 spl_autoload_register(COMPONENT_CLASSLOADER);
571} else {
572 spl_autoload_register('core_component::classloader');
573}
574
4dffc775 575// Load up standard libraries
4dffc775
PS
576require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output
577require_once($CFG->libdir .'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
578require_once($CFG->libdir .'/weblib.php'); // Functions relating to HTTP and content
579require_once($CFG->libdir .'/outputlib.php'); // Functions for generating output
580require_once($CFG->libdir .'/navigationlib.php'); // Class for generating Navigation structure
581require_once($CFG->libdir .'/dmllib.php'); // Database access
582require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
583require_once($CFG->libdir .'/accesslib.php'); // Access control functions
584require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
585require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
df997f84 586require_once($CFG->libdir .'/enrollib.php'); // Enrolment related functions
4dffc775
PS
587require_once($CFG->libdir .'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
588require_once($CFG->libdir .'/blocklib.php'); // Library for controlling blocks
589require_once($CFG->libdir .'/eventslib.php'); // Events functions
590require_once($CFG->libdir .'/grouplib.php'); // Groups functions
591require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie related stuff
592require_once($CFG->libdir .'/editorlib.php'); // All text editor related functions and classes
7c7d3afa 593require_once($CFG->libdir .'/messagelib.php'); // Messagelib functions
0d8b6a69 594require_once($CFG->libdir .'/modinfolib.php'); // Cached information on course-module instances
d6a1f63b 595require_once($CFG->dirroot.'/cache/lib.php'); // Cache API
4dffc775 596
4dffc775
PS
597// make sure PHP is not severly misconfigured
598setup_validate_php_configuration();
599
4dffc775
PS
600// Connect to the database
601setup_DB();
602
a3d5830a 603if (PHPUNIT_TEST and !PHPUNIT_UTIL) {
61d3013c 604 // make sure tests do not run in parallel
3f7211f4 605 test_lock::acquire('phpunit');
17b60e9d
PS
606 $dbhash = null;
607 try {
608 if ($dbhash = $DB->get_field('config', 'value', array('name'=>'phpunittest'))) {
609 // reset DB tables
610 phpunit_util::reset_database();
611 }
612 } catch (Exception $e) {
613 if ($dbhash) {
614 // we ned to reinit if reset fails
615 $DB->set_field('config', 'value', 'na', array('name'=>'phpunittest'));
17b60e9d
PS
616 }
617 }
618 unset($dbhash);
a3d5830a
PS
619}
620
96f81ea3
PS
621// Load up any configuration from the config table or MUC cache.
622if (PHPUNIT_TEST) {
623 phpunit_util::initialise_cfg();
4dffc775 624} else {
96f81ea3 625 initialise_cfg();
4dffc775 626}
dae73c05 627
96f81ea3
PS
628if (isset($CFG->debug)) {
629 $CFG->debug = (int)$CFG->debug;
630 error_reporting($CFG->debug);
631} else {
632 $CFG->debug = 0;
633}
ce7b06bc 634$CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
589376d3 635
96f81ea3
PS
636// Find out if PHP configured to display warnings,
637// this is a security problem because some moodle scripts may
638// disclose sensitive information.
639if (ini_get_bool('display_errors')) {
640 define('WARN_DISPLAY_ERRORS_ENABLED', true);
641}
642// If we want to display Moodle errors, then try and set PHP errors to match.
643if (!isset($CFG->debugdisplay)) {
644 // Keep it "as is" during installation.
645} else if (NO_DEBUG_DISPLAY) {
646 // Some parts of Moodle cannot display errors and debug at all.
647 ini_set('display_errors', '0');
648 ini_set('log_errors', '1');
649} else if (empty($CFG->debugdisplay)) {
650 ini_set('display_errors', '0');
651 ini_set('log_errors', '1');
589376d3 652} else {
96f81ea3
PS
653 // This is very problematic in XHTML strict mode!
654 ini_set('display_errors', '1');
589376d3 655}
a8a71844 656
38fc0130
PS
657// Register our shutdown manager, do NOT use register_shutdown_function().
658core_shutdown_manager::initialize();
659
4dffc775
PS
660// Verify upgrade is not running unless we are in a script that needs to execute in any case
661if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
662 if ($CFG->upgraderunning < time()) {
663 unset_config('upgraderunning');
aa893d6b 664 } else {
4dffc775 665 print_error('upgraderunning');
aa893d6b 666 }
4dffc775 667}
aa893d6b 668
4dffc775
PS
669// Turn on SQL logging if required
670if (!empty($CFG->logsql)) {
671 $DB->set_logging(true);
672}
f9903ed0 673
c7b0e5e1
PS
674// enable circular reference collector in PHP 5.3,
675// it helps a lot when using large complex OOP structures such as in amos or gradebook
676if (function_exists('gc_enable')) {
677 gc_enable();
678}
1e3e716f 679
4dffc775
PS
680// detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
681if (!empty($CFG->version) and $CFG->version < 2007101509) {
682 print_error('upgraderequires19', 'error');
683 die;
684}
475e9de8 685
4dffc775
PS
686// Calculate and set $CFG->ostype to be used everywhere. Possible values are:
687// - WINDOWS: for any Windows flavour.
688// - UNIX: for the rest
689// Also, $CFG->os can continue being used if more specialization is required
690if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
691 $CFG->ostype = 'WINDOWS';
692} else {
693 $CFG->ostype = 'UNIX';
694}
695$CFG->os = PHP_OS;
820743c5 696
4dffc775 697// Configure ampersands in URLs
27466303 698ini_set('arg_separator.output', '&amp;');
de7e4ac9 699
4dffc775 700// Work around for a PHP bug see MDL-11237
27466303 701ini_set('pcre.backtrack_limit', 20971520); // 20 MB
e7aa5a88 702
4dffc775 703// Location of standard files
4c1c9175
PS
704$CFG->wordlist = $CFG->libdir .'/wordlist.txt';
705$CFG->moddata = 'moddata';
f9903ed0 706
4dffc775
PS
707// neutralise nasty chars in PHP_SELF
708if (isset($_SERVER['PHP_SELF'])) {
709 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
710 if ($phppos !== false) {
711 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
18b9d664 712 }
4dffc775
PS
713 unset($phppos);
714}
715
d2114969
PS
716// initialise ME's - this must be done BEFORE starting of session!
717initialise_fullme();
718
f0f8f9a7
PS
719// define SYSCONTEXTID in config.php if you want to save some queries,
720// after install it must match the system context record id.
721if (!defined('SYSCONTEXTID')) {
0601e0ee 722 context_system::instance();
f0f8f9a7
PS
723}
724
725// Defining the site - aka frontpage course
726try {
727 $SITE = get_site();
d79d5ac2 728} catch (moodle_exception $e) {
f0f8f9a7
PS
729 $SITE = null;
730 if (empty($CFG->version)) {
731 $SITE = new stdClass();
732 $SITE->id = 1;
ca5d6066 733 $SITE->shortname = null;
f0f8f9a7
PS
734 } else {
735 throw $e;
736 }
737}
738// And the 'default' course - this will usually get reset later in require_login() etc.
739$COURSE = clone($SITE);
5940a2bb 740// Id of the frontpage course.
f0f8f9a7
PS
741define('SITEID', $SITE->id);
742
df92ba9a 743// init session prevention flag - this is defined on pages that do not want session
28bd3d9a
PS
744if (CLI_SCRIPT) {
745 // no sessions in CLI scripts possible
746 define('NO_MOODLE_COOKIES', true);
747
748} else if (!defined('NO_MOODLE_COOKIES')) {
df92ba9a
PS
749 if (empty($CFG->version) or $CFG->version < 2009011900) {
750 // no session before sessions table gets created
751 define('NO_MOODLE_COOKIES', true);
752 } else if (CLI_SCRIPT) {
753 // CLI scripts can not have session
754 define('NO_MOODLE_COOKIES', true);
755 } else {
756 define('NO_MOODLE_COOKIES', false);
757 }
758}
759
d79d5ac2
PS
760// Start session and prepare global $SESSION, $USER.
761if (empty($CFG->sessiontimeout)) {
762 $CFG->sessiontimeout = 7200;
763}
764\core\session\manager::start();
de230fd3
PS
765if (!PHPUNIT_TEST and !defined('BEHAT_TEST')) {
766 $SESSION =& $_SESSION['SESSION'];
767 $USER =& $_SESSION['USER'];
768}
18b9d664 769
0c431257
PS
770// Initialise some variables that are supposed to be set in config.php only.
771if (!isset($CFG->filelifetime)) {
772 $CFG->filelifetime = 60*60*6;
773}
774
c646dd26 775// Late profiling, only happening if early one wasn't started
6af80cae
EL
776if (!empty($CFG->profilingenabled)) {
777 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
38fc0130 778 profiling_start();
6af80cae
EL
779}
780
a3777547
PS
781// Hack to get around max_input_vars restrictions,
782// we need to do this after session init to have some basic DDoS protection.
783workaround_max_input_vars();
784
4dffc775 785// Process theme change in the URL.
998999e7
PS
786if (!empty($CFG->allowthemechangeonurl) and !empty($_GET['theme'])) {
787 // we have to use _GET directly because we do not want this to interfere with _POST
aff24313 788 $urlthemename = optional_param('theme', '', PARAM_PLUGIN);
4dffc775 789 try {
998999e7
PS
790 $themeconfig = theme_config::load($urlthemename);
791 // Makes sure the theme can be loaded without errors.
792 if ($themeconfig->name === $urlthemename) {
793 $SESSION->theme = $urlthemename;
794 } else {
795 unset($SESSION->theme);
796 }
797 unset($themeconfig);
798 unset($urlthemename);
4dffc775
PS
799 } catch (Exception $e) {
800 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
18b9d664 801 }
4dffc775
PS
802}
803unset($urlthemename);
18b9d664 804
4dffc775
PS
805// Ensure a valid theme is set.
806if (!isset($CFG->theme)) {
1302f765 807 $CFG->theme = 'standard';
4dffc775
PS
808}
809
810// Set language/locale of printed times. If user has chosen a language that
811// that is different from the site language, then use the locale specified
812// in the language file. Otherwise, if the admin hasn't specified a locale
813// then use the one from the default language. Otherwise (and this is the
814// majority of cases), use the stored locale specified by admin.
4000129f
PS
815// note: do not accept lang parameter from POST
816if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
ecd7978c 817 if (get_string_manager()->translation_exists($lang, false)) {
4dffc775 818 $SESSION->lang = $lang;
3e9b5d5a 819 }
4dffc775
PS
820}
821unset($lang);
ab036ed9 822
c484af5a
BK
823// PARAM_SAFEDIR used instead of PARAM_LANG because using PARAM_LANG results
824// in an empty string being returned when a non-existant language is specified,
825// which would make it necessary to log out to undo the forcelang setting.
826// With PARAM_SAFEDIR, it's possible to specify ?forcelang=none to drop the forcelang effect.
827if ($forcelang = optional_param('forcelang', '', PARAM_SAFEDIR)) {
828 if (isloggedin()
829 && get_string_manager()->translation_exists($forcelang, false)
830 && has_capability('moodle/site:forcelanguage', context_system::instance())) {
831 $SESSION->forcelang = $forcelang;
832 } else if (isset($SESSION->forcelang)) {
833 unset($SESSION->forcelang);
834 }
835}
836unset($forcelang);
837
4dffc775 838setup_lang_from_browser();
ab036ed9 839
4dffc775
PS
840if (empty($CFG->lang)) {
841 if (empty($SESSION->lang)) {
3a915b06 842 $CFG->lang = 'en';
4dffc775
PS
843 } else {
844 $CFG->lang = $SESSION->lang;
16ba7351 845 }
4dffc775 846}
6800d78e 847
00dadbe1
PS
848// Set the default site locale, a lot of the stuff may depend on this
849// it is definitely too late to call this first in require_login()!
850moodle_setlocale();
4dffc775 851
f0f8f9a7
PS
852// Create the $PAGE global - this marks the PAGE and OUTPUT fully initialised, this MUST be done at the end of setup!
853if (!empty($CFG->moodlepageclass)) {
3edc37cb
PS
854 if (!empty($CFG->moodlepageclassfile)) {
855 require_once($CFG->moodlepageclassfile);
856 }
f0f8f9a7
PS
857 $classname = $CFG->moodlepageclass;
858} else {
859 $classname = 'moodle_page';
860}
861$PAGE = new $classname();
862unset($classname);
863
864
4dffc775 865if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
1302f765 866 if ($CFG->theme == 'standard') { // Temporary measure to help with XHTML validation
4dffc775
PS
867 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
868 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
869 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
870 if ($user = get_complete_user_data("username", "w3cvalidator")) {
871 $user->ignoresesskey = true;
872 } else {
873 $user = guest_user();
9610a66e 874 }
d79d5ac2 875 \core\session\manager::set_user($user);
9610a66e 876 }
877 }
878 }
4dffc775 879}
9610a66e 880
4c1c9175 881// Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
4dffc775
PS
882// LogFormat to get the current logged in username in moodle.
883if ($USER && function_exists('apache_note')
884 && !empty($CFG->apacheloguser) && isset($USER->username)) {
885 $apachelog_userid = $USER->id;
886 $apachelog_username = clean_filename($USER->username);
887 $apachelog_name = '';
888 if (isset($USER->firstname)) {
889 // We can assume both will be set
890 // - even if to empty.
891 $apachelog_name = clean_filename($USER->firstname . " " .
892 $USER->lastname);
893 }
d79d5ac2
PS
894 if (\core\session\manager::is_loggedinas()) {
895 $realuser = \core\session\manager::get_realuser();
4dffc775
PS
896 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
897 $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
898 $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
899 }
900 switch ($CFG->apacheloguser) {
901 case 3:
902 $logname = $apachelog_username;
903 break;
904 case 2:
905 $logname = $apachelog_name;
906 break;
907 case 1:
908 default:
909 $logname = $apachelog_userid;
910 break;
911 }
912 apache_note('MOODLEUSER', $logname);
913}
a559eee6 914
4dffc775
PS
915// Use a custom script replacement if one exists
916if (!empty($CFG->customscripts)) {
917 if (($customscript = custom_script_path()) !== false) {
918 require ($customscript);
18259d4f 919 }
4dffc775 920}
18259d4f 921
a3d5830a
PS
922if (PHPUNIT_TEST) {
923 // no ip blocking, these are CLI only
924} else if (CLI_SCRIPT and !defined('WEB_CRON_EMULATED_CLI')) {
ade30ad3
RT
925 // no ip blocking
926} else if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
927 // in this case, ip in allowed list will be performed first
928 // for example, client IP is 192.168.1.1
929 // 192.168 subnet is an entry in allowed list
930 // 192.168.1.1 is banned in blocked list
931 // This ip will be banned finally
4dffc775
PS
932 if (!empty($CFG->allowedip)) {
933 if (!remoteip_in_list($CFG->allowedip)) {
934 die(get_string('ipblocked', 'admin'));
ab99c8f0 935 }
4dffc775
PS
936 }
937 // need further check, client ip may a part of
938 // allowed subnet, but a IP address are listed
939 // in blocked list.
940 if (!empty($CFG->blockedip)) {
941 if (remoteip_in_list($CFG->blockedip)) {
942 die(get_string('ipblocked', 'admin'));
5035228f 943 }
4dffc775 944 }
d255c6e9 945
4dffc775
PS
946} else {
947 // in this case, IPs in blocked list will be performed first
948 // for example, client IP is 192.168.1.1
949 // 192.168 subnet is an entry in blocked list
950 // 192.168.1.1 is allowed in allowed list
951 // This ip will be allowed finally
952 if (!empty($CFG->blockedip)) {
953 if (remoteip_in_list($CFG->blockedip)) {
954 // if the allowed ip list is not empty
955 // IPs are not included in the allowed list will be
956 // blocked too
957 if (!empty($CFG->allowedip)) {
958 if (!remoteip_in_list($CFG->allowedip)) {
d255c6e9 959 die(get_string('ipblocked', 'admin'));
960 }
4dffc775 961 } else {
d255c6e9 962 die(get_string('ipblocked', 'admin'));
963 }
5035228f 964 }
4dffc775
PS
965 }
966 // if blocked list is null
967 // allowed list should be tested
968 if(!empty($CFG->allowedip)) {
969 if (!remoteip_in_list($CFG->allowedip)) {
970 die(get_string('ipblocked', 'admin'));
971 }
ab99c8f0 972 }
973
4dffc775 974}
092bfaf1 975
99302c5e
PS
976// // try to detect IE6 and prevent gzip because it is extremely buggy browser
977if (!empty($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false) {
b19d75a2 978 ini_set('zlib.output_compression', 'Off');
99302c5e 979 if (function_exists('apache_setenv')) {
b19d75a2 980 apache_setenv('no-gzip', 1);
99302c5e
PS
981 }
982}
983
48e114a5
PS
984// Switch to CLI maintenance mode if required, we need to do it here after all the settings are initialised.
985if (isset($CFG->maintenance_later) and $CFG->maintenance_later <= time()) {
986 if (!file_exists("$CFG->dataroot/climaintenance.html")) {
987 require_once("$CFG->libdir/adminlib.php");
988 enable_cli_maintenance_mode();
989 }
990 unset_config('maintenance_later');
991 if (AJAX_SCRIPT) {
992 die;
993 } else if (!CLI_SCRIPT) {
994 redirect(new moodle_url('/'));
995 }
996}
99302c5e 997
4dffc775
PS
998// note: we can not block non utf-8 installations here, because empty mysql database
999// might be converted to utf-8 in admin/index.php during installation
d5fac1cf
PS
1000
1001
1002
1003// this is a funny trick to make Eclipse believe that $OUTPUT and other globals
1004// contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
1005if (false) {
1006 $DB = new moodle_database();
1007 $OUTPUT = new core_renderer(null, null);
1008 $PAGE = new moodle_page();
1009}