3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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.
26 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
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.
43 global $CFG; // this should be done much earlier in config.php before creating new $CFG instance
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");
50 // this should never happen, maybe somebody is accessing this file directly...
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");
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");
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");
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");
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
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);
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");
150 } else if (isset($_SERVER['REMOTE_ADDR'])) {
152 echo('Command line scripts can not be executed from the web interface');
157 echo('Command line scripts must define CLI_SCRIPT before requiring config.php'."\n");
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")) {
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");
176 if (!defined('CLI_MAINTENANCE')) {
177 define('CLI_MAINTENANCE', true);
181 if (!defined('CLI_MAINTENANCE')) {
182 define('CLI_MAINTENANCE', false);
186 // Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
187 if (!defined('AJAX_SCRIPT')) {
188 define('AJAX_SCRIPT', false);
191 // File permissions on created directories in the $CFG->dataroot
192 if (empty($CFG->directorypermissions)) {
193 $CFG->directorypermissions = 02777; // Must be octal (that's why it's here)
195 if (empty($CFG->filepermissions)) {
196 $CFG->filepermissions = ($CFG->directorypermissions & 0666); // strip execute flags
198 // better also set default umask because recursive mkdir() does not apply permissions recursively otherwise
201 // exact version of currently used yui2 and 3 library
202 $CFG->yui2version = '2.8.2';
203 $CFG->yui3version = '3.2.0';
206 // special support for highly optimised scripts that do not need libraries and DB connection
207 if (defined('ABORT_AFTER_CONFIG')) {
208 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
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);
215 if (empty($CFG->debugdisplay)) {
216 ini_set('display_errors', '0');
217 ini_set('log_errors', '1');
219 ini_set('display_errors', '1');
221 require_once("$CFG->dirroot/lib/configonlylib.php");
226 /** Used by library scripts to check they are being called by Moodle */
227 if (!defined('MOODLE_INTERNAL')) { // necessary because cli installer has to define it earlier
228 define('MOODLE_INTERNAL', true);
231 // Early profiling start, based exclusively on config.php $CFG settings
232 if (!empty($CFG->earlyprofilingenabled)) {
233 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
234 if (profiling_start()) {
235 register_shutdown_function('profiling_stop');
240 * Database connection. Used for all access to the database.
241 * @global moodle_database $DB
247 * Moodle's wrapper round PHP's $_SESSION.
249 * @global object $SESSION
255 * Holds the user table record for the current user. Will be the 'guest'
256 * user record for people who are not logged in.
258 * $USER is stored in the session.
260 * Items found in the user record:
261 * - $USER->email - The user's email address.
262 * - $USER->id - The unique integer identified of this user in the 'user' table.
263 * - $USER->email - The user's email address.
264 * - $USER->firstname - The user's first name.
265 * - $USER->lastname - The user's last name.
266 * - $USER->username - The user's login username.
267 * - $USER->secret - The user's ?.
268 * - $USER->lang - The user's language choice.
270 * @global object $USER
276 * A central store of information about the current page we are
277 * generating in response to the user's request.
279 * @global moodle_page $PAGE
285 * The current course. An alias for $PAGE->course.
286 * @global object $COURSE
292 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
293 * it to generate HTML for output.
295 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
296 * for the magic that does that. After $OUTPUT has been initialised, any attempt
297 * to change something that affects the current theme ($PAGE->course, logged in use,
298 * httpsrequried ... will result in an exception.)
300 * Please note the $OUTPUT is replacing the old global $THEME object.
302 * @global object $OUTPUT
308 * Shared memory cache.
309 * @global object $MCACHE
315 * Full script path including all params, slash arguments, scheme and host.
316 * @global string $FULLME
322 * Script path including query string and slash arguments without host.
329 * $FULLME without slasharguments and query string.
330 * @global string $FULLSCRIPT
336 * Relative moodle script path '/course/view.php'
337 * @global string $SCRIPT
342 // Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides
343 $CFG->config_php_settings = (array)$CFG;
344 // Forced plugin settings override values from config_plugins table
345 unset($CFG->config_php_settings['forced_plugin_settings']);
346 if (!isset($CFG->forced_plugin_settings)) {
347 $CFG->forced_plugin_settings = array();
349 // Set httpswwwroot default value (this variable will replace $CFG->wwwroot
350 // inside some URLs used in HTTPSPAGEREQUIRED pages.
351 $CFG->httpswwwroot = $CFG->wwwroot;
353 require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
355 if (NO_OUTPUT_BUFFERING) {
356 // we have to call this always before starting session because it discards headers!
357 disable_output_buffering();
360 // Increase memory limits if possible
361 raise_memory_limit(MEMORY_STANDARD);
363 // Time to start counting
364 init_performance_info();
366 // Put $OUTPUT in place, so errors can be displayed.
367 $OUTPUT = new bootstrap_renderer();
369 // set handler for uncaught exceptions - equivalent to print_error() call
370 set_exception_handler('default_exception_handler');
371 set_error_handler('default_error_handler', E_ALL | E_STRICT);
373 // If there are any errors in the standard libraries we want to know!
374 error_reporting(E_ALL);
376 // Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
377 // http://www.google.com/webmasters/faq.html#prefetchblock
378 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
379 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
380 echo('Prefetch request forbidden.');
384 if (!isset($CFG->prefix)) { // Just in case it isn't defined in config.php
388 // location of all languages except core English pack
389 if (!isset($CFG->langotherroot)) {
390 $CFG->langotherroot = $CFG->dataroot.'/lang';
393 // location of local lang pack customisations (dirs with _local suffix)
394 if (!isset($CFG->langlocalroot)) {
395 $CFG->langlocalroot = $CFG->dataroot.'/lang';
398 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
399 //the problem is that we need specific version of quickforms and hacked excel files :-(
400 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
401 //point zend include path to moodles lib/zend so that includes and requires will search there for files before anywhere else
402 //please note zend library is supposed to be used only from web service protocol classes, it may be removed in future
403 ini_set('include_path', $CFG->libdir.'/zend' . PATH_SEPARATOR . ini_get('include_path'));
405 // Load up standard libraries
406 require_once($CFG->libdir .'/textlib.class.php'); // Functions to handle multibyte strings
407 require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output
408 require_once($CFG->libdir .'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
409 require_once($CFG->libdir .'/weblib.php'); // Functions relating to HTTP and content
410 require_once($CFG->libdir .'/outputlib.php'); // Functions for generating output
411 require_once($CFG->libdir .'/navigationlib.php'); // Class for generating Navigation structure
412 require_once($CFG->libdir .'/dmllib.php'); // Database access
413 require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
414 require_once($CFG->libdir .'/accesslib.php'); // Access control functions
415 require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
416 require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
417 require_once($CFG->libdir .'/enrollib.php'); // Enrolment related functions
418 require_once($CFG->libdir .'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
419 require_once($CFG->libdir .'/blocklib.php'); // Library for controlling blocks
420 require_once($CFG->libdir .'/eventslib.php'); // Events functions
421 require_once($CFG->libdir .'/grouplib.php'); // Groups functions
422 require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie related stuff
423 require_once($CFG->libdir .'/editorlib.php'); // All text editor related functions and classes
424 require_once($CFG->libdir .'/messagelib.php'); // Messagelib functions
425 require_once($CFG->libdir .'/modinfolib.php'); // Cached information on course-module instances
427 // make sure PHP is not severly misconfigured
428 setup_validate_php_configuration();
430 // Connect to the database
433 // Disable errors for now - needed for installation when debug enabled in config.php
434 if (isset($CFG->debug)) {
435 $originalconfigdebug = $CFG->debug;
438 $originalconfigdebug = -1;
441 // Load up any configuration from the config table
444 // Verify upgrade is not running unless we are in a script that needs to execute in any case
445 if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
446 if ($CFG->upgraderunning < time()) {
447 unset_config('upgraderunning');
449 print_error('upgraderunning');
453 // Turn on SQL logging if required
454 if (!empty($CFG->logsql)) {
455 $DB->set_logging(true);
458 // Prevent warnings from roles when upgrading with debug on
459 if (isset($CFG->debug)) {
460 $originaldatabasedebug = $CFG->debug;
463 $originaldatabasedebug = -1;
466 // enable circular reference collector in PHP 5.3,
467 // it helps a lot when using large complex OOP structures such as in amos or gradebook
468 if (function_exists('gc_enable')) {
472 // Register default shutdown tasks - such as Apache memory release helper, perf logging, etc.
473 if (function_exists('register_shutdown_function')) {
474 register_shutdown_function('moodle_request_shutdown');
481 * If $SITE global from {@link get_site()} is set then SITEID to $SITE->id, otherwise set to 1.
483 define('SITEID', $SITE->id);
484 // And the 'default' course - this will usually get reset later in require_login() etc.
485 $COURSE = clone($SITE);
486 } catch (dml_exception $e) {
488 if (empty($CFG->version)) {
489 // we are just installing
494 // And the 'default' course
495 $COURSE = new stdClass(); // no site created yet
502 // define SYSCONTEXTID in config.php if you want to save some queries (after install or upgrade!)
503 if (!defined('SYSCONTEXTID')) {
504 get_system_context();
507 // Set error reporting back to normal
508 if ($originaldatabasedebug == -1) {
509 $CFG->debug = DEBUG_MINIMAL;
511 $CFG->debug = $originaldatabasedebug;
513 if ($originalconfigdebug !== -1) {
514 $CFG->debug = $originalconfigdebug;
516 unset($originalconfigdebug);
517 unset($originaldatabasedebug);
518 error_reporting($CFG->debug);
520 // find out if PHP configured to display warnings,
521 // this is a security problem because some moodle scripts may
522 // disclose sensitive information
523 if (ini_get_bool('display_errors')) {
524 define('WARN_DISPLAY_ERRORS_ENABLED', true);
526 // If we want to display Moodle errors, then try and set PHP errors to match
527 if (!isset($CFG->debugdisplay)) {
528 // keep it "as is" during installation
529 } else if (NO_DEBUG_DISPLAY) {
530 // some parts of Moodle cannot display errors and debug at all.
531 ini_set('display_errors', '0');
532 ini_set('log_errors', '1');
533 } else if (empty($CFG->debugdisplay)) {
534 ini_set('display_errors', '0');
535 ini_set('log_errors', '1');
537 // This is very problematic in XHTML strict mode!
538 ini_set('display_errors', '1');
541 // detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
542 if (!empty($CFG->version) and $CFG->version < 2007101509) {
543 print_error('upgraderequires19', 'error');
547 // Shared-Memory cache init -- will set $MCACHE
548 // $MCACHE is a global object that offers at least add(), set() and delete()
549 // with similar semantics to the memcached PHP API http://php.net/memcache
550 // Ensure we define rcache - so we can later check for it
551 // with a really fast and unambiguous $CFG->rcache === false
552 if (!empty($CFG->cachetype)) {
553 if (empty($CFG->rcache)) {
554 $CFG->rcache = false;
559 // do not try to initialize if cache disabled
561 $CFG->cachetype = '';
564 if ($CFG->cachetype === 'memcached' && !empty($CFG->memcachedhosts)) {
565 if (!init_memcached()) {
566 debugging("Error initialising memcached");
567 $CFG->cachetype = '';
568 $CFG->rcache = false;
570 } else if ($CFG->cachetype === 'eaccelerator') {
571 if (!init_eaccelerator()) {
572 debugging("Error initialising eaccelerator cache");
573 $CFG->cachetype = '';
574 $CFG->rcache = false;
578 } else { // just make sure it is defined
579 $CFG->cachetype = '';
580 $CFG->rcache = false;
583 // Calculate and set $CFG->ostype to be used everywhere. Possible values are:
584 // - WINDOWS: for any Windows flavour.
585 // - UNIX: for the rest
586 // Also, $CFG->os can continue being used if more specialization is required
587 if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
588 $CFG->ostype = 'WINDOWS';
590 $CFG->ostype = 'UNIX';
594 // Configure ampersands in URLs
595 ini_set('arg_separator.output', '&');
597 // Work around for a PHP bug see MDL-11237
598 ini_set('pcre.backtrack_limit', 20971520); // 20 MB
600 // Location of standard files
601 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
602 $CFG->moddata = 'moddata';
604 // Create the $PAGE global.
605 if (!empty($CFG->moodlepageclass)) {
606 $classname = $CFG->moodlepageclass;
608 $classname = 'moodle_page';
610 $PAGE = new $classname();
613 // A hack to get around magic_quotes_gpc being turned on
614 // It is strongly recommended to disable "magic_quotes_gpc"!
615 if (ini_get_bool('magic_quotes_gpc')) {
616 function stripslashes_deep($value) {
617 $value = is_array($value) ?
618 array_map('stripslashes_deep', $value) :
619 stripslashes($value);
622 $_POST = array_map('stripslashes_deep', $_POST);
623 $_GET = array_map('stripslashes_deep', $_GET);
624 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
625 $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
626 if (!empty($_SERVER['REQUEST_URI'])) {
627 $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']);
629 if (!empty($_SERVER['QUERY_STRING'])) {
630 $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']);
632 if (!empty($_SERVER['HTTP_REFERER'])) {
633 $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']);
635 if (!empty($_SERVER['PATH_INFO'])) {
636 $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']);
638 if (!empty($_SERVER['PHP_SELF'])) {
639 $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']);
641 if (!empty($_SERVER['PATH_TRANSLATED'])) {
642 $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']);
646 // neutralise nasty chars in PHP_SELF
647 if (isset($_SERVER['PHP_SELF'])) {
648 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
649 if ($phppos !== false) {
650 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
655 // init session prevention flag - this is defined on pages that do not want session
657 // no sessions in CLI scripts possible
658 define('NO_MOODLE_COOKIES', true);
660 } else if (!defined('NO_MOODLE_COOKIES')) {
661 if (empty($CFG->version) or $CFG->version < 2009011900) {
662 // no session before sessions table gets created
663 define('NO_MOODLE_COOKIES', true);
664 } else if (CLI_SCRIPT) {
665 // CLI scripts can not have session
666 define('NO_MOODLE_COOKIES', true);
668 define('NO_MOODLE_COOKIES', false);
672 // start session and prepare global $SESSION, $USER
673 session_get_instance();
674 $SESSION = &$_SESSION['SESSION'];
675 $USER = &$_SESSION['USER'];
678 // This must presently come AFTER $USER has been set up.
681 // Late profiling, only happening if early one wasn't started
682 if (!empty($CFG->profilingenabled)) {
683 require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
684 if (profiling_start()) {
685 register_shutdown_function('profiling_stop');
689 // Process theme change in the URL.
690 if (!empty($CFG->allowthemechangeonurl) and !empty($_GET['theme'])) {
691 // we have to use _GET directly because we do not want this to interfere with _POST
692 $urlthemename = optional_param('theme', '', PARAM_SAFEDIR);
694 $themeconfig = theme_config::load($urlthemename);
695 // Makes sure the theme can be loaded without errors.
696 if ($themeconfig->name === $urlthemename) {
697 $SESSION->theme = $urlthemename;
699 unset($SESSION->theme);
702 unset($urlthemename);
703 } catch (Exception $e) {
704 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
707 unset($urlthemename);
709 // Ensure a valid theme is set.
710 if (!isset($CFG->theme)) {
711 $CFG->theme = 'standardwhite';
714 // Set language/locale of printed times. If user has chosen a language that
715 // that is different from the site language, then use the locale specified
716 // in the language file. Otherwise, if the admin hasn't specified a locale
717 // then use the one from the default language. Otherwise (and this is the
718 // majority of cases), use the stored locale specified by admin.
719 // note: do not accept lang parameter from POST
720 if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
721 if (get_string_manager()->translation_exists($lang, false)) {
722 $SESSION->lang = $lang;
727 setup_lang_from_browser();
729 if (empty($CFG->lang)) {
730 if (empty($SESSION->lang)) {
733 $CFG->lang = $SESSION->lang;
737 // Set the default site locale, a lot of the stuff may depend on this
738 // it is definitely too late to call this first in require_login()!
741 if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
742 if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') { // Temporary measure to help with XHTML validation
743 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
744 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
745 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
746 if ($user = get_complete_user_data("username", "w3cvalidator")) {
747 $user->ignoresesskey = true;
749 $user = guest_user();
751 session_set_user($user);
757 // Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
758 // LogFormat to get the current logged in username in moodle.
759 if ($USER && function_exists('apache_note')
760 && !empty($CFG->apacheloguser) && isset($USER->username)) {
761 $apachelog_userid = $USER->id;
762 $apachelog_username = clean_filename($USER->username);
763 $apachelog_name = '';
764 if (isset($USER->firstname)) {
765 // We can assume both will be set
766 // - even if to empty.
767 $apachelog_name = clean_filename($USER->firstname . " " .
770 if (session_is_loggedinas()) {
771 $realuser = session_get_realuser();
772 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
773 $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
774 $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
776 switch ($CFG->apacheloguser) {
778 $logname = $apachelog_username;
781 $logname = $apachelog_name;
785 $logname = $apachelog_userid;
788 apache_note('MOODLEUSER', $logname);
791 // Adjust ALLOWED_TAGS
792 adjust_allowed_tags();
794 // Use a custom script replacement if one exists
795 if (!empty($CFG->customscripts)) {
796 if (($customscript = custom_script_path()) !== false) {
797 require ($customscript);
801 // in the first case, ip in allowed list will be performed first
802 // for example, client IP is 192.168.1.1
803 // 192.168 subnet is an entry in allowed list
804 // 192.168.1.1 is banned in blocked list
805 // This ip will be banned finally
806 if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
807 if (!empty($CFG->allowedip)) {
808 if (!remoteip_in_list($CFG->allowedip)) {
809 die(get_string('ipblocked', 'admin'));
812 // need further check, client ip may a part of
813 // allowed subnet, but a IP address are listed
815 if (!empty($CFG->blockedip)) {
816 if (remoteip_in_list($CFG->blockedip)) {
817 die(get_string('ipblocked', 'admin'));
822 // in this case, IPs in blocked list will be performed first
823 // for example, client IP is 192.168.1.1
824 // 192.168 subnet is an entry in blocked list
825 // 192.168.1.1 is allowed in allowed list
826 // This ip will be allowed finally
827 if (!empty($CFG->blockedip)) {
828 if (remoteip_in_list($CFG->blockedip)) {
829 // if the allowed ip list is not empty
830 // IPs are not included in the allowed list will be
832 if (!empty($CFG->allowedip)) {
833 if (!remoteip_in_list($CFG->allowedip)) {
834 die(get_string('ipblocked', 'admin'));
837 die(get_string('ipblocked', 'admin'));
841 // if blocked list is null
842 // allowed list should be tested
843 if(!empty($CFG->allowedip)) {
844 if (!remoteip_in_list($CFG->allowedip)) {
845 die(get_string('ipblocked', 'admin'));
851 // note: we can not block non utf-8 installations here, because empty mysql database
852 // might be converted to utf-8 in admin/index.php during installation
856 // this is a funny trick to make Eclipse believe that $OUTPUT and other globals
857 // contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
859 $DB = new moodle_database();
860 $OUTPUT = new core_renderer(null, null);
861 $PAGE = new moodle_page();