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