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