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