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