Merge branch 'MDL-31712_M21' of git://github.com/kordan/moodle into MOODLE_21_STABLE
[moodle.git] / lib / setup.php
blob7d1f6be4f0186c58b9a38b6dca524b32b65394fd
1 <?php
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.
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/>.
18 /**
19 * setup.php - Sets up sessions, connects to databases and so on
21 * Normally this is only called by the main config.php file
22 * Normally this file does not need to be edited.
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
30 /**
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.
34 * Some typical settings in the $CFG global:
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.
40 * @global object $CFG
41 * @name $CFG
43 global $CFG; // this should be done much earlier in config.php before creating new $CFG instance
45 if (!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);
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__));
59 // Normalise dataroot - we do not want any symbolic links, trailing / or any other weirdness there
60 if (!isset($CFG->dataroot)) {
61 if (isset($_SERVER['REMOTE_ADDR'])) {
62 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
64 echo('Fatal error: $CFG->dataroot is not specified in config.php! Exiting.'."\n");
65 exit(1);
67 $CFG->dataroot = realpath($CFG->dataroot);
68 if ($CFG->dataroot === false) {
69 if (isset($_SERVER['REMOTE_ADDR'])) {
70 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
72 echo('Fatal error: $CFG->dataroot is not configured properly, directory does not exist or is not accessible! Exiting.'."\n");
73 exit(1);
74 } else if (!is_writable($CFG->dataroot)) {
75 if (isset($_SERVER['REMOTE_ADDR'])) {
76 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
78 echo('Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.'."\n");
79 exit(1);
82 // wwwroot is mandatory
83 if (!isset($CFG->wwwroot) or $CFG->wwwroot === 'http://example.com/moodle') {
84 if (isset($_SERVER['REMOTE_ADDR'])) {
85 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
87 echo('Fatal error: $CFG->wwwroot is not configured! Exiting.'."\n");
88 exit(1);
91 // Define admin directory
92 if (!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
96 // Set up some paths.
97 $CFG->libdir = $CFG->dirroot .'/lib';
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()
102 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
103 chdir(dirname($_SERVER['argv'][0]));
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
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
112 if (!defined('NO_DEBUG_DISPLAY')) {
113 define('NO_DEBUG_DISPLAY', false);
116 // Some scripts such as upgrade may want to prevent output buffering
117 if (!defined('NO_OUTPUT_BUFFERING')) {
118 define('NO_OUTPUT_BUFFERING', false);
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.
123 if (function_exists('date_default_timezone_set') and function_exists('date_default_timezone_get')) {
124 $olddebug = error_reporting(0);
125 date_default_timezone_set(date_default_timezone_get());
126 error_reporting($olddebug);
127 unset($olddebug);
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
132 if (!defined('PHPUNIT_SCRIPT')) {
133 define('PHPUNIT_SCRIPT', false);
135 if (PHPUNIT_SCRIPT) {
136 define('CLI_SCRIPT', true);
139 // Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
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.
142 if (!defined('CLI_SCRIPT')) {
143 define('CLI_SCRIPT', false);
145 if (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);
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);
155 } else {
156 if (!CLI_SCRIPT) {
157 echo('Command line scripts must define CLI_SCRIPT before requiring config.php'."\n");
158 exit(1);
162 // Detect CLI maintenance mode - this is useful when you need to mess with database, such as during upgrades
163 if (file_exists("$CFG->dataroot/climaintenance.html")) {
164 if (!CLI_SCRIPT) {
165 header('Content-type: text/html; charset=utf-8');
166 /// Headers to make it not cacheable and json
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');
173 readfile("$CFG->dataroot/climaintenance.html");
174 die;
175 } else {
176 if (!defined('CLI_MAINTENANCE')) {
177 define('CLI_MAINTENANCE', true);
180 } else {
181 if (!defined('CLI_MAINTENANCE')) {
182 define('CLI_MAINTENANCE', false);
186 if (CLI_SCRIPT) {
187 // sometimes people use different PHP binary for web and CLI, make 100% sure they have the supported PHP version
188 if (version_compare(phpversion(), '5.3.2') < 0) {
189 $phpversion = phpversion();
190 // do NOT localise - lang strings would not work here and we CAN NOT move it to later place
191 echo "Moodle 2.1 or later requires at least PHP 5.3.2 (currently using version $phpversion).\n";
192 echo "Some servers may have multiple PHP versions installed, are you using the correct executable?\n";
193 exit(1);
197 // Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
198 if (!defined('AJAX_SCRIPT')) {
199 define('AJAX_SCRIPT', false);
202 // File permissions on created directories in the $CFG->dataroot
203 if (empty($CFG->directorypermissions)) {
204 $CFG->directorypermissions = 02777; // Must be octal (that's why it's here)
206 if (empty($CFG->filepermissions)) {
207 $CFG->filepermissions = ($CFG->directorypermissions & 0666); // strip execute flags
209 // better also set default umask because recursive mkdir() does not apply permissions recursively otherwise
210 umask(0000);
212 // exact version of currently used yui2 and 3 library
213 $CFG->yui2version = '2.9.0';
214 $CFG->yui3version = '3.4.1';
217 // special support for highly optimised scripts that do not need libraries and DB connection
218 if (defined('ABORT_AFTER_CONFIG')) {
219 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
220 // hide debugging if not enabled in config.php - we do not want to disclose sensitive info
221 if (isset($CFG->debug)) {
222 error_reporting($CFG->debug);
223 } else {
224 error_reporting(0);
226 if (empty($CFG->debugdisplay)) {
227 ini_set('display_errors', '0');
228 ini_set('log_errors', '1');
229 } else {
230 ini_set('display_errors', '1');
232 require_once("$CFG->dirroot/lib/configonlylib.php");
233 return;
237 /** Used by library scripts to check they are being called by Moodle */
238 if (!defined('MOODLE_INTERNAL')) { // necessary because cli installer has to define it earlier
239 define('MOODLE_INTERNAL', true);
242 // Early profiling start, based exclusively on config.php $CFG settings
243 if (!empty($CFG->earlyprofilingenabled)) {
244 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
245 if (profiling_start()) {
246 register_shutdown_function('profiling_stop');
251 * Database connection. Used for all access to the database.
252 * @global moodle_database $DB
253 * @name $DB
255 global $DB;
258 * Moodle's wrapper round PHP's $_SESSION.
260 * @global object $SESSION
261 * @name $SESSION
263 global $SESSION;
266 * Holds the user table record for the current user. Will be the 'guest'
267 * user record for people who are not logged in.
269 * $USER is stored in the session.
271 * Items found in the user record:
272 * - $USER->email - The user's email address.
273 * - $USER->id - The unique integer identified of this user in the 'user' table.
274 * - $USER->email - The user's email address.
275 * - $USER->firstname - The user's first name.
276 * - $USER->lastname - The user's last name.
277 * - $USER->username - The user's login username.
278 * - $USER->secret - The user's ?.
279 * - $USER->lang - The user's language choice.
281 * @global object $USER
282 * @name $USER
284 global $USER;
287 * A central store of information about the current page we are
288 * generating in response to the user's request.
290 * @global moodle_page $PAGE
291 * @name $PAGE
293 global $PAGE;
296 * The current course. An alias for $PAGE->course.
297 * @global object $COURSE
298 * @name $COURSE
300 global $COURSE;
303 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
304 * it to generate HTML for output.
306 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
307 * for the magic that does that. After $OUTPUT has been initialised, any attempt
308 * to change something that affects the current theme ($PAGE->course, logged in use,
309 * httpsrequried ... will result in an exception.)
311 * Please note the $OUTPUT is replacing the old global $THEME object.
313 * @global object $OUTPUT
314 * @name $OUTPUT
316 global $OUTPUT;
319 * Shared memory cache.
320 * @global object $MCACHE
321 * @name $MCACHE
323 global $MCACHE;
326 * Full script path including all params, slash arguments, scheme and host.
327 * @global string $FULLME
328 * @name $FULLME
330 global $FULLME;
333 * Script path including query string and slash arguments without host.
334 * @global string $ME
335 * @name $ME
337 global $ME;
340 * $FULLME without slasharguments and query string.
341 * @global string $FULLSCRIPT
342 * @name $FULLSCRIPT
344 global $FULLSCRIPT;
347 * Relative moodle script path '/course/view.php'
348 * @global string $SCRIPT
349 * @name $SCRIPT
351 global $SCRIPT;
353 // Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides
354 $CFG->config_php_settings = (array)$CFG;
355 // Forced plugin settings override values from config_plugins table
356 unset($CFG->config_php_settings['forced_plugin_settings']);
357 if (!isset($CFG->forced_plugin_settings)) {
358 $CFG->forced_plugin_settings = array();
360 // Set httpswwwroot default value (this variable will replace $CFG->wwwroot
361 // inside some URLs used in HTTPSPAGEREQUIRED pages.
362 $CFG->httpswwwroot = $CFG->wwwroot;
364 require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
366 if (NO_OUTPUT_BUFFERING) {
367 // we have to call this always before starting session because it discards headers!
368 disable_output_buffering();
371 // Increase memory limits if possible
372 raise_memory_limit(MEMORY_STANDARD);
374 // Time to start counting
375 init_performance_info();
377 // Put $OUTPUT in place, so errors can be displayed.
378 $OUTPUT = new bootstrap_renderer();
380 // set handler for uncaught exceptions - equivalent to print_error() call
381 set_exception_handler('default_exception_handler');
382 set_error_handler('default_error_handler', E_ALL | E_STRICT);
384 // If there are any errors in the standard libraries we want to know!
385 error_reporting(E_ALL);
387 // Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
388 // http://www.google.com/webmasters/faq.html#prefetchblock
389 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
390 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
391 echo('Prefetch request forbidden.');
392 exit(1);
395 if (!isset($CFG->prefix)) { // Just in case it isn't defined in config.php
396 $CFG->prefix = '';
399 // location of all languages except core English pack
400 if (!isset($CFG->langotherroot)) {
401 $CFG->langotherroot = $CFG->dataroot.'/lang';
404 // location of local lang pack customisations (dirs with _local suffix)
405 if (!isset($CFG->langlocalroot)) {
406 $CFG->langlocalroot = $CFG->dataroot.'/lang';
409 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
410 //the problem is that we need specific version of quickforms and hacked excel files :-(
411 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
412 //point zend include path to moodles lib/zend so that includes and requires will search there for files before anywhere else
413 //please note zend library is supposed to be used only from web service protocol classes, it may be removed in future
414 ini_set('include_path', $CFG->libdir.'/zend' . PATH_SEPARATOR . ini_get('include_path'));
416 // Load up standard libraries
417 require_once($CFG->libdir .'/textlib.class.php'); // Functions to handle multibyte strings
418 require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output
419 require_once($CFG->libdir .'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
420 require_once($CFG->libdir .'/weblib.php'); // Functions relating to HTTP and content
421 require_once($CFG->libdir .'/outputlib.php'); // Functions for generating output
422 require_once($CFG->libdir .'/navigationlib.php'); // Class for generating Navigation structure
423 require_once($CFG->libdir .'/dmllib.php'); // Database access
424 require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
425 require_once($CFG->libdir .'/accesslib.php'); // Access control functions
426 require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
427 require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
428 require_once($CFG->libdir .'/enrollib.php'); // Enrolment related functions
429 require_once($CFG->libdir .'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
430 require_once($CFG->libdir .'/blocklib.php'); // Library for controlling blocks
431 require_once($CFG->libdir .'/eventslib.php'); // Events functions
432 require_once($CFG->libdir .'/grouplib.php'); // Groups functions
433 require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie related stuff
434 require_once($CFG->libdir .'/editorlib.php'); // All text editor related functions and classes
435 require_once($CFG->libdir .'/messagelib.php'); // Messagelib functions
436 require_once($CFG->libdir .'/modinfolib.php'); // Cached information on course-module instances
438 // make sure PHP is not severly misconfigured
439 setup_validate_php_configuration();
441 // Connect to the database
442 setup_DB();
444 // Disable errors for now - needed for installation when debug enabled in config.php
445 if (isset($CFG->debug)) {
446 $originalconfigdebug = $CFG->debug;
447 unset($CFG->debug);
448 } else {
449 $originalconfigdebug = -1;
452 // Load up any configuration from the config table
453 initialise_cfg();
455 // Verify upgrade is not running unless we are in a script that needs to execute in any case
456 if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
457 if ($CFG->upgraderunning < time()) {
458 unset_config('upgraderunning');
459 } else {
460 print_error('upgraderunning');
464 // Turn on SQL logging if required
465 if (!empty($CFG->logsql)) {
466 $DB->set_logging(true);
469 // Prevent warnings from roles when upgrading with debug on
470 if (isset($CFG->debug)) {
471 $originaldatabasedebug = $CFG->debug;
472 unset($CFG->debug);
473 } else {
474 $originaldatabasedebug = -1;
477 // enable circular reference collector in PHP 5.3,
478 // it helps a lot when using large complex OOP structures such as in amos or gradebook
479 if (function_exists('gc_enable')) {
480 gc_enable();
483 // Register default shutdown tasks - such as Apache memory release helper, perf logging, etc.
484 if (function_exists('register_shutdown_function')) {
485 register_shutdown_function('moodle_request_shutdown');
488 // Defining the site
489 try {
490 $SITE = get_site();
492 * If $SITE global from {@link get_site()} is set then SITEID to $SITE->id, otherwise set to 1.
494 define('SITEID', $SITE->id);
495 // And the 'default' course - this will usually get reset later in require_login() etc.
496 $COURSE = clone($SITE);
497 } catch (dml_exception $e) {
498 $SITE = null;
499 if (empty($CFG->version)) {
500 // we are just installing
502 * @ignore
504 define('SITEID', 1);
505 // And the 'default' course
506 $COURSE = new stdClass(); // no site created yet
507 $COURSE->id = 1;
508 } else {
509 throw $e;
513 // define SYSCONTEXTID in config.php if you want to save some queries (after install or upgrade!)
514 if (!defined('SYSCONTEXTID')) {
515 get_system_context();
518 // Set error reporting back to normal
519 if ($originaldatabasedebug == -1) {
520 $CFG->debug = DEBUG_MINIMAL;
521 } else {
522 $CFG->debug = $originaldatabasedebug;
524 if ($originalconfigdebug !== -1) {
525 $CFG->debug = $originalconfigdebug;
527 unset($originalconfigdebug);
528 unset($originaldatabasedebug);
529 error_reporting($CFG->debug);
531 // find out if PHP configured to display warnings,
532 // this is a security problem because some moodle scripts may
533 // disclose sensitive information
534 if (ini_get_bool('display_errors')) {
535 define('WARN_DISPLAY_ERRORS_ENABLED', true);
537 // If we want to display Moodle errors, then try and set PHP errors to match
538 if (!isset($CFG->debugdisplay)) {
539 // keep it "as is" during installation
540 } else if (NO_DEBUG_DISPLAY) {
541 // some parts of Moodle cannot display errors and debug at all.
542 ini_set('display_errors', '0');
543 ini_set('log_errors', '1');
544 } else if (empty($CFG->debugdisplay)) {
545 ini_set('display_errors', '0');
546 ini_set('log_errors', '1');
547 } else {
548 // This is very problematic in XHTML strict mode!
549 ini_set('display_errors', '1');
552 // detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
553 if (!empty($CFG->version) and $CFG->version < 2007101509) {
554 print_error('upgraderequires19', 'error');
555 die;
558 // Shared-Memory cache init -- will set $MCACHE
559 // $MCACHE is a global object that offers at least add(), set() and delete()
560 // with similar semantics to the memcached PHP API http://php.net/memcache
561 // Ensure we define rcache - so we can later check for it
562 // with a really fast and unambiguous $CFG->rcache === false
563 if (!empty($CFG->cachetype)) {
564 if (empty($CFG->rcache)) {
565 $CFG->rcache = false;
566 } else {
567 $CFG->rcache = true;
570 // do not try to initialize if cache disabled
571 if (!$CFG->rcache) {
572 $CFG->cachetype = '';
575 if ($CFG->cachetype === 'memcached' && !empty($CFG->memcachedhosts)) {
576 if (!init_memcached()) {
577 debugging("Error initialising memcached");
578 $CFG->cachetype = '';
579 $CFG->rcache = false;
581 } else if ($CFG->cachetype === 'eaccelerator') {
582 if (!init_eaccelerator()) {
583 debugging("Error initialising eaccelerator cache");
584 $CFG->cachetype = '';
585 $CFG->rcache = false;
589 } else { // just make sure it is defined
590 $CFG->cachetype = '';
591 $CFG->rcache = false;
594 // Calculate and set $CFG->ostype to be used everywhere. Possible values are:
595 // - WINDOWS: for any Windows flavour.
596 // - UNIX: for the rest
597 // Also, $CFG->os can continue being used if more specialization is required
598 if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
599 $CFG->ostype = 'WINDOWS';
600 } else {
601 $CFG->ostype = 'UNIX';
603 $CFG->os = PHP_OS;
605 // Configure ampersands in URLs
606 ini_set('arg_separator.output', '&amp;');
608 // Work around for a PHP bug see MDL-11237
609 ini_set('pcre.backtrack_limit', 20971520); // 20 MB
611 // Location of standard files
612 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
613 $CFG->moddata = 'moddata';
615 // Create the $PAGE global.
616 if (!empty($CFG->moodlepageclass)) {
617 $classname = $CFG->moodlepageclass;
618 } else {
619 $classname = 'moodle_page';
621 $PAGE = new $classname();
622 unset($classname);
624 // A hack to get around magic_quotes_gpc being turned on
625 // It is strongly recommended to disable "magic_quotes_gpc"!
626 if (ini_get_bool('magic_quotes_gpc')) {
627 function stripslashes_deep($value) {
628 $value = is_array($value) ?
629 array_map('stripslashes_deep', $value) :
630 stripslashes($value);
631 return $value;
633 $_POST = array_map('stripslashes_deep', $_POST);
634 $_GET = array_map('stripslashes_deep', $_GET);
635 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
636 $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
637 if (!empty($_SERVER['REQUEST_URI'])) {
638 $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']);
640 if (!empty($_SERVER['QUERY_STRING'])) {
641 $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']);
643 if (!empty($_SERVER['HTTP_REFERER'])) {
644 $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']);
646 if (!empty($_SERVER['PATH_INFO'])) {
647 $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']);
649 if (!empty($_SERVER['PHP_SELF'])) {
650 $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']);
652 if (!empty($_SERVER['PATH_TRANSLATED'])) {
653 $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']);
657 // neutralise nasty chars in PHP_SELF
658 if (isset($_SERVER['PHP_SELF'])) {
659 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
660 if ($phppos !== false) {
661 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
663 unset($phppos);
666 // initialise ME's - this must be done BEFORE starting of session!
667 initialise_fullme();
669 // init session prevention flag - this is defined on pages that do not want session
670 if (CLI_SCRIPT) {
671 // no sessions in CLI scripts possible
672 define('NO_MOODLE_COOKIES', true);
674 } else if (!defined('NO_MOODLE_COOKIES')) {
675 if (empty($CFG->version) or $CFG->version < 2009011900) {
676 // no session before sessions table gets created
677 define('NO_MOODLE_COOKIES', true);
678 } else if (CLI_SCRIPT) {
679 // CLI scripts can not have session
680 define('NO_MOODLE_COOKIES', true);
681 } else {
682 define('NO_MOODLE_COOKIES', false);
686 // start session and prepare global $SESSION, $USER
687 session_get_instance();
688 $SESSION = &$_SESSION['SESSION'];
689 $USER = &$_SESSION['USER'];
691 // Late profiling, only happening if early one wasn't started
692 if (!empty($CFG->profilingenabled)) {
693 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
694 if (profiling_start()) {
695 register_shutdown_function('profiling_stop');
699 // Process theme change in the URL.
700 if (!empty($CFG->allowthemechangeonurl) and !empty($_GET['theme'])) {
701 // we have to use _GET directly because we do not want this to interfere with _POST
702 $urlthemename = optional_param('theme', '', PARAM_SAFEDIR);
703 try {
704 $themeconfig = theme_config::load($urlthemename);
705 // Makes sure the theme can be loaded without errors.
706 if ($themeconfig->name === $urlthemename) {
707 $SESSION->theme = $urlthemename;
708 } else {
709 unset($SESSION->theme);
711 unset($themeconfig);
712 unset($urlthemename);
713 } catch (Exception $e) {
714 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
717 unset($urlthemename);
719 // Ensure a valid theme is set.
720 if (!isset($CFG->theme)) {
721 $CFG->theme = 'standardwhite';
724 // Set language/locale of printed times. If user has chosen a language that
725 // that is different from the site language, then use the locale specified
726 // in the language file. Otherwise, if the admin hasn't specified a locale
727 // then use the one from the default language. Otherwise (and this is the
728 // majority of cases), use the stored locale specified by admin.
729 // note: do not accept lang parameter from POST
730 if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
731 if (get_string_manager()->translation_exists($lang, false)) {
732 $SESSION->lang = $lang;
735 unset($lang);
737 setup_lang_from_browser();
739 if (empty($CFG->lang)) {
740 if (empty($SESSION->lang)) {
741 $CFG->lang = 'en';
742 } else {
743 $CFG->lang = $SESSION->lang;
747 // Set the default site locale, a lot of the stuff may depend on this
748 // it is definitely too late to call this first in require_login()!
749 moodle_setlocale();
751 if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
752 if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') { // Temporary measure to help with XHTML validation
753 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
754 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
755 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
756 if ($user = get_complete_user_data("username", "w3cvalidator")) {
757 $user->ignoresesskey = true;
758 } else {
759 $user = guest_user();
761 session_set_user($user);
767 // Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
768 // LogFormat to get the current logged in username in moodle.
769 if ($USER && function_exists('apache_note')
770 && !empty($CFG->apacheloguser) && isset($USER->username)) {
771 $apachelog_userid = $USER->id;
772 $apachelog_username = clean_filename($USER->username);
773 $apachelog_name = '';
774 if (isset($USER->firstname)) {
775 // We can assume both will be set
776 // - even if to empty.
777 $apachelog_name = clean_filename($USER->firstname . " " .
778 $USER->lastname);
780 if (session_is_loggedinas()) {
781 $realuser = session_get_realuser();
782 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
783 $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
784 $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
786 switch ($CFG->apacheloguser) {
787 case 3:
788 $logname = $apachelog_username;
789 break;
790 case 2:
791 $logname = $apachelog_name;
792 break;
793 case 1:
794 default:
795 $logname = $apachelog_userid;
796 break;
798 apache_note('MOODLEUSER', $logname);
801 // Adjust ALLOWED_TAGS
802 adjust_allowed_tags();
804 // Use a custom script replacement if one exists
805 if (!empty($CFG->customscripts)) {
806 if (($customscript = custom_script_path()) !== false) {
807 require ($customscript);
811 if (CLI_SCRIPT and !defined('WEB_CRON_EMULATED_CLI') and !PHPUNIT_SCRIPT) {
812 // no ip blocking
813 } else if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
814 // in this case, ip in allowed list will be performed first
815 // for example, client IP is 192.168.1.1
816 // 192.168 subnet is an entry in allowed list
817 // 192.168.1.1 is banned in blocked list
818 // This ip will be banned finally
819 if (!empty($CFG->allowedip)) {
820 if (!remoteip_in_list($CFG->allowedip)) {
821 die(get_string('ipblocked', 'admin'));
824 // need further check, client ip may a part of
825 // allowed subnet, but a IP address are listed
826 // in blocked list.
827 if (!empty($CFG->blockedip)) {
828 if (remoteip_in_list($CFG->blockedip)) {
829 die(get_string('ipblocked', 'admin'));
833 } else {
834 // in this case, IPs in blocked list will be performed first
835 // for example, client IP is 192.168.1.1
836 // 192.168 subnet is an entry in blocked list
837 // 192.168.1.1 is allowed in allowed list
838 // This ip will be allowed finally
839 if (!empty($CFG->blockedip)) {
840 if (remoteip_in_list($CFG->blockedip)) {
841 // if the allowed ip list is not empty
842 // IPs are not included in the allowed list will be
843 // blocked too
844 if (!empty($CFG->allowedip)) {
845 if (!remoteip_in_list($CFG->allowedip)) {
846 die(get_string('ipblocked', 'admin'));
848 } else {
849 die(get_string('ipblocked', 'admin'));
853 // if blocked list is null
854 // allowed list should be tested
855 if(!empty($CFG->allowedip)) {
856 if (!remoteip_in_list($CFG->allowedip)) {
857 die(get_string('ipblocked', 'admin'));
863 // note: we can not block non utf-8 installations here, because empty mysql database
864 // might be converted to utf-8 in admin/index.php during installation
868 // this is a funny trick to make Eclipse believe that $OUTPUT and other globals
869 // contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
870 if (false) {
871 $DB = new moodle_database();
872 $OUTPUT = new core_renderer(null, null);
873 $PAGE = new moodle_page();