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