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.
25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 * Holds the core settings that affect how Moodle works. Some of its fields
31 * are set in config.php, and the rest are loaded from the config table.
33 * Some typical settings in the $CFG global:
34 * - $CFG->wwwroot - Path to moodle index directory in url format.
35 * - $CFG->dataroot - Path to moodle index directory on server's filesystem.
36 * - $CFG->libdir - Path to moodle's library folder on server's filesystem.
44 $CFG->libdir = $CFG->dirroot .'/lib';
46 // exact version of currently used yui2 and 3 library
47 $CFG->yui2version = '2.8.0r4';
48 $CFG->yui3version = '3.0.0';
50 // special support for highly optimised scripts that do not need libraries and DB connection
51 if (defined('ABORT_AFTER_CONFIG')) {
52 if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
53 // hide debugging if not enabled in config.php - we do not want to disclose sensitive info
54 if (isset($CFG->debug)) {
55 error_reporting($CFG->debug);
59 if (empty($CFG->debugdisplay)) {
60 @ini_set('display_errors', '0');
61 @ini_set('log_errors', '1');
63 @ini_set('display_errors', '1');
65 require_once("$CFG->dirroot/lib/configonlylib.php");
71 * Database connection. Used for all access to the database.
72 * @global moodle_database $DB
78 * Moodle's wrapper round PHP's $_SESSION.
80 * @global object $SESSION
86 * Holds the user table record for the current user. Will be the 'guest'
87 * user record for people who are not logged in.
89 * $USER is stored in the session.
91 * Items found in the user record:
92 * - $USER->emailstop - Does the user want email sent to them?
93 * - $USER->email - The user's email address.
94 * - $USER->id - The unique integer identified of this user in the 'user' table.
95 * - $USER->email - The user's email address.
96 * - $USER->firstname - The user's first name.
97 * - $USER->lastname - The user's last name.
98 * - $USER->username - The user's login username.
99 * - $USER->secret - The user's ?.
100 * - $USER->lang - The user's language choice.
102 * @global object $USER
108 * A central store of information about the current page we are
109 * generating in response to the user's request.
111 * @global moodle_page $PAGE
117 * The current course. An alias for $PAGE->course.
118 * @global object $COURSE
124 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
125 * it to generate HTML for output.
127 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
128 * for the magic that does that. After $OUTPUT has been initialised, any attempt
129 * to change something that affects the current theme ($PAGE->course, logged in use,
130 * httpsrequried ... will result in an exception.)
132 * Please note the $OUTPUT is replacing the old global $THEME object.
134 * @global object $OUTPUT
140 * Shared memory cache.
141 * @global object $MCACHE
147 * A global to define if the page being displayed must run under HTTPS.
149 * Its primary goal is to allow 100% HTTPS pages when $CFG->loginhttps is enabled. Default to false.
150 * Its enabled only by the $PAGE->https_required() function and used in some pages to update some URLs
152 * @global bool $HTTPSPAGEREQUIRED
153 * @name $HTTPSPAGEREQUIRED
155 global $HTTPSPAGEREQUIRED;
158 * Full script path including all params, slash arguments, scheme and host.
159 * @global string $FULLME
165 * Script path including query string and slash arguments without host.
172 * $FULLME without slasharguments and query string.
173 * @global string $FULLSCRIPT
179 * Relative moodle script path '/course/view.php'
180 * @global string $SCRIPT
185 // Scripts may request no debug and error messages in output
186 // please note it must be defined before including the config.php script
187 // and in some cases you also need to set custom default exception handler
188 if (!defined('NO_DEBUG_DISPLAY')) {
189 define('NO_DEBUG_DISPLAY', false);
192 // wwwroot is mandatory
193 if (!isset($CFG->wwwroot)) {
194 // trigger_error() is not correct here, no need to log this
195 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
196 echo('Fatal: $CFG->wwwroot is not configured! Exiting.');
200 // Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
201 if (!defined('CLI_SCRIPT')) { // CLI_SCRIPT might be defined in 'fake' CLI scripts like admin/cron.php
202 if (isset($_SERVER['REMOTE_ADDR'])) {
203 define('CLI_SCRIPT', false);
206 define('CLI_SCRIPT', true);
210 // sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
211 @ini_set('precision', 14); // needed for upgrades and gradebook
213 // The current directory in PHP version 4.3.0 and above isn't necessarily the
214 // directory of the script when run from the command line. The require_once()
215 // would fail, so we'll have to chdir()
216 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
217 chdir(dirname($_SERVER['argv'][0]));
220 // Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides
221 $CFG->config_php_settings = (array)$CFG;
223 // Set httpswwwroot default value (this variable will replace $CFG->wwwroot
224 // inside some URLs used in HTTPSPAGEREQUIRED pages.
225 $CFG->httpswwwroot = $CFG->wwwroot;
227 require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
229 // Time to start counting
230 init_performance_info();
232 // Put $OUTPUT in place, so errors can be displayed.
233 $OUTPUT = new bootstrap_renderer();
235 // set handler for uncaught exceptions - equivalent to print_error() call
236 set_exception_handler('default_exception_handler');
238 // If there are any errors in the standard libraries we want to know!
239 error_reporting(E_ALL);
241 // Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
242 // http://www.google.com/webmasters/faq.html#prefetchblock
243 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
244 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
245 echo('Prefetch request forbidden.');
249 // Define admin directory
250 if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
251 $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
254 if (!isset($CFG->prefix)) { // Just in case it isn't defined in config.php
258 // Load up standard libraries
259 require_once($CFG->libdir .'/textlib.class.php'); // Functions to handle multibyte strings
260 require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output
261 require_once($CFG->libdir .'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI
262 require_once($CFG->libdir .'/weblib.php'); // Functions relating to HTTP and content
263 require_once($CFG->libdir .'/outputlib.php'); // Functions for generating output
264 require_once($CFG->libdir .'/navigationlib.php'); // Class for generating Navigation structure
265 require_once($CFG->libdir .'/dmllib.php'); // Database access
266 require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
267 require_once($CFG->libdir .'/accesslib.php'); // Access control functions
268 require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
269 require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
270 require_once($CFG->libdir .'/pagelib.php'); // Library that defines the moodle_page class, used for $PAGE
271 require_once($CFG->libdir .'/blocklib.php'); // Library for controlling blocks
272 require_once($CFG->libdir .'/eventslib.php'); // Events functions
273 require_once($CFG->libdir .'/grouplib.php'); // Groups functions
274 require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie related stuff
275 require_once($CFG->libdir .'/editorlib.php'); // All text editor related functions and classes
276 require_once($CFG->libdir .'/messagelib.php'); // Messagelib functions
278 //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
279 //the problem is that we need specific version of quickforms and hacked excel files :-(
280 ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
281 //point zend include path to moodles lib/zend so that includes and requires will search there for files before anywhere else
282 //please note zend library is supposed to be used only from web service protocol classes, it may be removed in future
283 ini_set('include_path', $CFG->libdir.'/zend' . PATH_SEPARATOR . ini_get('include_path'));
285 // make sure PHP is not severly misconfigured
286 setup_validate_php_configuration();
288 // Increase memory limits if possible
289 raise_memory_limit('96M'); // We should never NEED this much but just in case...
291 // Connect to the database
294 // Disable errors for now - needed for installation when debug enabled in config.php
295 if (isset($CFG->debug)) {
296 $originalconfigdebug = $CFG->debug;
299 $originalconfigdebug = -1;
302 // Load up any configuration from the config table
305 } catch (dml_read_exception $e) {
306 // most probably empty db, going to install soon
309 // Verify upgrade is not running unless we are in a script that needs to execute in any case
310 if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
311 if ($CFG->upgraderunning < time()) {
312 unset_config('upgraderunning');
314 print_error('upgraderunning');
318 // Turn on SQL logging if required
319 if (!empty($CFG->logsql)) {
320 $DB->set_logging(true);
323 // Prevent warnings from roles when upgrading with debug on
324 if (isset($CFG->debug)) {
325 $originaldatabasedebug = $CFG->debug;
328 $originaldatabasedebug = -1;
332 // For now, only needed under apache (and probably unstable in other contexts)
333 if (function_exists('register_shutdown_function')) {
334 register_shutdown_function('moodle_request_shutdown');
341 * If $SITE global from {@link get_site()} is set then SITEID to $SITE->id, otherwise set to 1.
343 define('SITEID', $SITE->id);
344 // And the 'default' course - this will usually get reset later in require_login() etc.
345 $COURSE = clone($SITE);
346 } catch (dml_read_exception $e) {
348 if (empty($CFG->version)) {
349 // we are just installing
354 // And the 'default' course
355 $COURSE = new object(); // no site created yet
362 // define SYSCONTEXTID in config.php if you want to save some queries (after install or upgrade!)
363 if (!defined('SYSCONTEXTID')) {
364 get_system_context();
367 // Set error reporting back to normal
368 if ($originaldatabasedebug == -1) {
369 $CFG->debug = DEBUG_MINIMAL;
371 $CFG->debug = $originaldatabasedebug;
373 if ($originalconfigdebug !== -1) {
374 $CFG->debug = $originalconfigdebug;
376 unset($originalconfigdebug);
377 unset($originaldatabasedebug);
378 error_reporting($CFG->debug);
380 // find out if PHP cofigured to display warnings,
381 // this is a security problem because some moodle scripts may
382 // disclose sensitive information
383 if (ini_get_bool('display_errors')) {
384 define('WARN_DISPLAY_ERRORS_ENABLED', true);
386 // If we want to display Moodle errors, then try and set PHP errors to match
387 if (!isset($CFG->debugdisplay)) {
388 // keep it "as is" during installation
389 } else if (NO_DEBUG_DISPLAY) {
390 // some parts of Moodle cannot display errors and debug at all.
391 @ini_set('display_errors', '0');
392 @ini_set('log_errors', '1');
393 } else if (empty($CFG->debugdisplay)) {
394 @ini_set('display_errors', '0');
395 @ini_set('log_errors', '1');
397 // This is very problematic in XHTML strict mode!
398 @ini_set('display_errors', '1');
401 // detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
402 if (!empty($CFG->version) and $CFG->version < 2007101509) {
403 print_error('upgraderequires19', 'error');
407 // Shared-Memory cache init -- will set $MCACHE
408 // $MCACHE is a global object that offers at least add(), set() and delete()
409 // with similar semantics to the memcached PHP API http://php.net/memcache
410 // Ensure we define rcache - so we can later check for it
411 // with a really fast and unambiguous $CFG->rcache === false
412 if (!empty($CFG->cachetype)) {
413 if (empty($CFG->rcache)) {
414 $CFG->rcache = false;
419 // do not try to initialize if cache disabled
421 $CFG->cachetype = '';
424 if ($CFG->cachetype === 'memcached' && !empty($CFG->memcachedhosts)) {
425 if (!init_memcached()) {
426 debugging("Error initialising memcached");
427 $CFG->cachetype = '';
428 $CFG->rcache = false;
430 } else if ($CFG->cachetype === 'eaccelerator') {
431 if (!init_eaccelerator()) {
432 debugging("Error initialising eaccelerator cache");
433 $CFG->cachetype = '';
434 $CFG->rcache = false;
438 } else { // just make sure it is defined
439 $CFG->cachetype = '';
440 $CFG->rcache = false;
443 // File permissions on created directories in the $CFG->dataroot
444 if (empty($CFG->directorypermissions)) {
445 $CFG->directorypermissions = 0777; // Must be octal (that's why it's here)
447 if (empty($CFG->filepermissions)) {
448 $CFG->filepermissions = ($CFG->directorypermissions & 0666); // strip execute flags
450 // better also set default umask because recursive mkdir() does not apply permissions recursively otherwise
453 // Calculate and set $CFG->ostype to be used everywhere. Possible values are:
454 // - WINDOWS: for any Windows flavour.
455 // - UNIX: for the rest
456 // Also, $CFG->os can continue being used if more specialization is required
457 if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
458 $CFG->ostype = 'WINDOWS';
460 $CFG->ostype = 'UNIX';
464 // Setup cache dir for Smarty and others
465 if (!file_exists($CFG->dataroot .'/cache')) {
466 make_upload_directory('cache');
469 // Configure ampersands in URLs
470 @ini_set('arg_separator.output', '&');
472 // Work around for a PHP bug see MDL-11237
473 @ini_set('pcre.backtrack_limit', 20971520); // 20 MB
475 // Location of standard files
476 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
477 $CFG->moddata = 'moddata';
479 // Create the $PAGE global.
480 if (!empty($CFG->moodlepageclass)) {
481 $classname = $CFG->moodlepageclass;
483 $classname = 'moodle_page';
485 $PAGE = new $classname();
488 // A hack to get around magic_quotes_gpc being turned on
489 // It is strongly recommended to disable "magic_quotes_gpc"!
490 if (ini_get_bool('magic_quotes_gpc')) {
491 function stripslashes_deep($value) {
492 $value = is_array($value) ?
493 array_map('stripslashes_deep', $value) :
494 stripslashes($value);
497 $_POST = array_map('stripslashes_deep', $_POST);
498 $_GET = array_map('stripslashes_deep', $_GET);
499 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
500 $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
501 if (!empty($_SERVER['REQUEST_URI'])) {
502 $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']);
504 if (!empty($_SERVER['QUERY_STRING'])) {
505 $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']);
507 if (!empty($_SERVER['HTTP_REFERER'])) {
508 $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']);
510 if (!empty($_SERVER['PATH_INFO'])) {
511 $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']);
513 if (!empty($_SERVER['PHP_SELF'])) {
514 $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']);
516 if (!empty($_SERVER['PATH_TRANSLATED'])) {
517 $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']);
521 // neutralise nasty chars in PHP_SELF
522 if (isset($_SERVER['PHP_SELF'])) {
523 $phppos = strpos($_SERVER['PHP_SELF'], '.php');
524 if ($phppos !== false) {
525 $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
533 // start session and prepare global $SESSION, $USER
534 session_get_instance();
535 $SESSION = &$_SESSION['SESSION'];
536 $USER = &$_SESSION['USER'];
538 // Process theme change in the URL.
539 if (!empty($CFG->allowthemechangeonurl) and !empty($_GET['theme'])) {
540 // we have to use _GET directly because we do not want this to interfere with _POST
541 $urlthemename = optional_param('theme', '', PARAM_SAFEDIR);
543 $themeconfig = theme_config::load($urlthemename);
544 // Makes sure the theme can be loaded without errors.
545 if ($themeconfig->name === $urlthemename) {
546 $SESSION->theme = $urlthemename;
548 unset($SESSION->theme);
551 unset($urlthemename);
552 } catch (Exception $e) {
553 debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
556 unset($urlthemename);
558 // Ensure a valid theme is set.
559 if (!isset($CFG->theme)) {
560 $CFG->theme = 'standardwhite';
563 // Set language/locale of printed times. If user has chosen a language that
564 // that is different from the site language, then use the locale specified
565 // in the language file. Otherwise, if the admin hasn't specified a locale
566 // then use the one from the default language. Otherwise (and this is the
567 // majority of cases), use the stored locale specified by admin.
568 if (($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
569 if (file_exists($CFG->dataroot .'/lang/'. $lang) or
570 file_exists($CFG->dirroot .'/lang/'. $lang)) {
571 $SESSION->lang = $lang;
572 } else if (file_exists($CFG->dataroot.'/lang/'.$lang.'_utf8') or
573 file_exists($CFG->dirroot .'/lang/'.$lang.'_utf8')) {
574 $SESSION->lang = $lang.'_utf8';
579 setup_lang_from_browser();
581 if (empty($CFG->lang)) {
582 if (empty($SESSION->lang)) {
583 $CFG->lang = 'en_utf8';
585 $CFG->lang = $SESSION->lang;
589 // Set the default site locale, a lot of the stuff may depend on this
590 // it is definitely too late to call this first in require_login()!
593 if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
594 if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') { // Temporary measure to help with XHTML validation
595 if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
596 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
597 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
598 if ($user = get_complete_user_data("username", "w3cvalidator")) {
599 $user->ignoresesskey = true;
601 $user = guest_user();
603 session_set_user($user);
609 // Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
610 // LogFormat to get the current logged in username in moodle.
611 if ($USER && function_exists('apache_note')
612 && !empty($CFG->apacheloguser) && isset($USER->username)) {
613 $apachelog_userid = $USER->id;
614 $apachelog_username = clean_filename($USER->username);
615 $apachelog_name = '';
616 if (isset($USER->firstname)) {
617 // We can assume both will be set
618 // - even if to empty.
619 $apachelog_name = clean_filename($USER->firstname . " " .
622 if (session_is_loggedinas()) {
623 $realuser = session_get_realuser();
624 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
625 $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
626 $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
628 switch ($CFG->apacheloguser) {
630 $logname = $apachelog_username;
633 $logname = $apachelog_name;
637 $logname = $apachelog_userid;
640 apache_note('MOODLEUSER', $logname);
643 // Adjust ALLOWED_TAGS
644 adjust_allowed_tags();
646 // Use a custom script replacement if one exists
647 if (!empty($CFG->customscripts)) {
648 if (($customscript = custom_script_path()) !== false) {
649 require ($customscript);
653 // in the first case, ip in allowed list will be performed first
654 // for example, client IP is 192.168.1.1
655 // 192.168 subnet is an entry in allowed list
656 // 192.168.1.1 is banned in blocked list
657 // This ip will be banned finally
658 if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
659 if (!empty($CFG->allowedip)) {
660 if (!remoteip_in_list($CFG->allowedip)) {
661 die(get_string('ipblocked', 'admin'));
664 // need further check, client ip may a part of
665 // allowed subnet, but a IP address are listed
667 if (!empty($CFG->blockedip)) {
668 if (remoteip_in_list($CFG->blockedip)) {
669 die(get_string('ipblocked', 'admin'));
674 // in this case, IPs in blocked list will be performed first
675 // for example, client IP is 192.168.1.1
676 // 192.168 subnet is an entry in blocked list
677 // 192.168.1.1 is allowed in allowed list
678 // This ip will be allowed finally
679 if (!empty($CFG->blockedip)) {
680 if (remoteip_in_list($CFG->blockedip)) {
681 // if the allowed ip list is not empty
682 // IPs are not included in the allowed list will be
684 if (!empty($CFG->allowedip)) {
685 if (!remoteip_in_list($CFG->allowedip)) {
686 die(get_string('ipblocked', 'admin'));
689 die(get_string('ipblocked', 'admin'));
693 // if blocked list is null
694 // allowed list should be tested
695 if(!empty($CFG->allowedip)) {
696 if (!remoteip_in_list($CFG->allowedip)) {
697 die(get_string('ipblocked', 'admin'));
703 // note: we can not block non utf-8 installations here, because empty mysql database
704 // might be converted to utf-8 in admin/index.php during installation
708 // this is a funny trick to make Eclipse believe that $OUTPUT and other globals
709 // contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
711 $DB = new moodle_database();
712 $OUTPUT = new core_renderer(null, null);
713 $PAGE = new moodle_page();