file popup.html was added on branch MOODLE_15_STABLE on 2005-07-07 16:14:38 +0000
[moodle.git] / lib / setup.php
blobb36f4eef529d0a5e4ce67db5f49461e8c6151ef9
1 <?php
2 /**
3 * setup.php - Sets up sessions, connects to databases and so on
5 * Normally this is only called by the main config.php file
6 * Normally this file does not need to be edited.
7 * @author Martin Dougiamas
8 * @version $Id$
9 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
10 * @package moodlecore
13 ////// DOCUMENTATION IN PHPDOC FORMAT FOR MOODLE GLOBALS AND COMMON OBJECT TYPES /////////////
14 /**
15 * This global variable is read in from the 'config' table.
17 * Some typical settings in the $CFG global:
18 * - $USER->emailstop - Does the user want email sent to them?
19 * - $USER->email - The user's email address.
20 * - $USER->id - The unique integer identified of this user in the 'user' table.
21 * - $USER->email - The user's email address.
22 * - $USER->firstname - The user's first name.
23 * - $USER->lastname - The user's last name.
24 * - $USER->username - The user's login username.
25 * - $USER->secret - The user's ?.
26 * - $USER->lang - The user's language choice.
28 * @global object(user) $USER
30 global $USER;
31 /**
32 * $USER is a global instance of a typical $user record.
34 * Items found in the user record:
35 * - $CFG->wwwroot - Path to moodle index directory in url format.
36 * - $CFG->dataroot - Path to moodle index directory on server's filesystem.
37 * - $CFG->libroot - Path to moodle's library folder on server's filesystem.
39 * @global object(cfg) $CFG
41 global $CFG;
42 /**
43 * Definition of session type
44 * @global object(session) $SESSION
46 global $SESSION;
47 /**
48 * Definition of course type
49 * @global object(course) $COURSE
51 global $COURSE;
52 /**
53 * Definition of db type
54 * @global object(db) $db
56 global $db;
57 /**
58 * $THEME is a global that defines the site theme.
60 * Items found in the theme record:
61 * - $THEME->cellheading - Cell colors.
62 * - $THEME->cellheading2 - Alternate cell colors.
64 * @global object(theme) $THEME
66 global $THEME;
68 if (!isset($CFG->wwwroot)) {
69 die;
72 /// Time to start counting
73 init_performance_info();
76 /// If there are any errors in the standard libraries we want to know!
77 error_reporting(E_ALL);
79 /// Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
80 /// http://www.google.com/webmasters/faq.html#prefetchblock
81 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
82 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
83 trigger_error('Prefetch request forbidden.');
84 exit;
87 /// Connect to the database using adodb
89 $CFG->libdir = $CFG->dirroot .'/lib';
91 require_once($CFG->libdir .'/adodb/adodb.inc.php'); // Database access functions
93 $db = &ADONewConnection($CFG->dbtype);
95 error_reporting(0); // Hide errors
97 if (!isset($CFG->dbpersist) or !empty($CFG->dbpersist)) { // Use persistent connection (default)
98 $dbconnected = $db->PConnect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);
99 } else { // Use single connection
100 $dbconnected = $db->Connect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);
102 if (! $dbconnected) {
103 // In the name of protocol correctness, monitoring and performance
104 // profiling, set the appropriate error headers for machine comsumption
105 if (isset($_SERVER['SERVER_PROTOCOL'])) {
106 // Avoid it with cron.php. Note that we assume it's HTTP/1.x
107 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
109 // and then for human consumption...
110 echo '<html><body>';
111 echo '<table align="center"><tr>';
112 echo '<td style="color:#990000; text-align:center; font-size:large; border-width:1px; '.
113 ' border-color:#000000; border-style:solid; border-radius: 20px; border-collapse: collapse; '.
114 ' -moz-border-radius: 20px; padding: 15px">';
115 echo '<p>Error: Database connection failed.</p>';
116 echo '<p>It is possible that the database is overloaded or otherwise not running properly.</p>';
117 echo '<p>The site administrator should also check that the database details have been correctly specified in config.php</p>';
118 echo '</td></tr></table>';
119 echo '</body></html>';
120 die;
123 error_reporting(E_ALL); // Show errors from now on.
125 if (!isset($CFG->prefix)) { // Just in case it isn't defined in config.php
126 $CFG->prefix = '';
130 /// Define admin directory
132 if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
133 $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
137 /// Load up standard libraries
139 require_once($CFG->libdir .'/weblib.php'); // Functions for producing HTML
140 require_once($CFG->libdir .'/datalib.php'); // Functions for accessing databases
141 require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
144 /// Increase memory limits if possible
146 raise_memory_limit('64M'); // We should never NEED this much but just in case...
149 /// Load up any configuration from the config table
150 $CFG = get_config();
152 /// Turn on SQL logging if required
153 if (!empty($CFG->logsql)) {
154 $db->LogSQL();
158 /// Set error reporting back to normal
159 if (empty($CFG->debug)) {
160 $CFG->debug = 7;
162 error_reporting($CFG->debug);
165 /// Set a default enrolment configuration (see bug 1598)
166 if (!isset($CFG->enrol)) {
167 $CFG->enrol = 'internal';
170 /// File permissions on created directories in the $CFG->dataroot
172 if (empty($CFG->directorypermissions)) {
173 $CFG->directorypermissions = 0777; // Must be octal (that's why it's here)
176 /// Setup cache dir for Smarty and others
177 if (!file_exists($CFG->dataroot .'/cache')) {
178 make_upload_directory('cache');
181 /// Set up smarty template system
182 //require_once($CFG->libdir .'/smarty/Smarty.class.php');
183 //$smarty = new Smarty;
184 //$smarty->template_dir = $CFG->dirroot .'/templates/'. $CFG->template;
185 //if (!file_exists($CFG->dataroot .'/cache/smarty')) {
186 // make_upload_directory('cache/smarty');
188 //$smarty->compile_dir = $CFG->dataroot .'/cache/smarty';
190 /// Set up session handling
191 if(empty($CFG->respectsessionsettings)) {
192 if (empty($CFG->dbsessions)) { /// File-based sessions
194 // Some distros disable GC by setting probability to 0
195 // overriding the PHP default of 1
196 // (gc_probability is divided by gc_divisor, which defaults to 1000)
197 if (ini_get('session.gc_probability') == 0) {
198 ini_set('session.gc_probability', 1);
201 if (!empty($CFG->sessiontimeout)) {
202 ini_set('session.gc_maxlifetime', $CFG->sessiontimeout);
205 if (!file_exists($CFG->dataroot .'/sessions')) {
206 make_upload_directory('sessions');
208 ini_set('session.save_path', $CFG->dataroot .'/sessions');
210 } else { /// Database sessions
211 ini_set('session.save_handler', 'user');
213 $ADODB_SESSION_DRIVER = $CFG->dbtype;
214 $ADODB_SESSION_CONNECT = $CFG->dbhost;
215 $ADODB_SESSION_USER = $CFG->dbuser;
216 $ADODB_SESSION_PWD = $CFG->dbpass;
217 $ADODB_SESSION_DB = $CFG->dbname;
218 $ADODB_SESSION_TBL = $CFG->prefix.'sessions';
220 require_once($CFG->libdir. '/adodb/session/adodb-session.php');
223 /// Set sessioncookie variable if it isn't already
224 if (!isset($CFG->sessioncookie)) {
225 $CFG->sessioncookie = '';
228 /// Configure ampersands in URLs
230 @ini_set('arg_separator.output', '&amp;');
232 /// Location of standard files
234 $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
235 $CFG->javascript = $CFG->libdir .'/javascript.php';
236 $CFG->moddata = 'moddata';
239 /// A hack to get around magic_quotes_gpc being turned off
241 if (!ini_get_bool('magic_quotes_gpc') ) {
242 function addslashes_deep($value) {
243 $value = is_array($value) ?
244 array_map('addslashes_deep', $value) :
245 addslashes($value);
246 return $value;
248 $_POST = array_map('addslashes_deep', $_POST);
249 $_GET = array_map('addslashes_deep', $_GET);
250 $_COOKIE = array_map('addslashes_deep', $_COOKIE);
254 /// The following is a hack to get around the problem of PHP installations
255 /// that have "register_globals" turned off (default since PHP 4.1.0).
256 /// Eventually I'll go through and upgrade all the code to make this unnecessary
258 if (isset($_GET)) {
259 extract($_GET, EXTR_SKIP); // Skip existing variables, ie CFG
261 if (isset($_POST)) {
262 extract($_POST, EXTR_SKIP); // Skip existing variables, ie CFG
264 if (isset($_SERVER)) {
265 extract($_SERVER);
269 /// Load up global environment variables
271 class object {};
273 unset(${'MoodleSession'.$CFG->sessioncookie});
274 unset($_GET['MoodleSession'.$CFG->sessioncookie]);
275 unset($_POST['MoodleSession'.$CFG->sessioncookie]);
277 if (!isset($nomoodlecookie)) {
278 session_name('MoodleSession'.$CFG->sessioncookie);
279 @session_start();
280 if (! isset($_SESSION['SESSION'])) {
281 $_SESSION['SESSION'] = new object;
282 $_SESSION['SESSION']->session_test = random_string(10);
283 if (empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
284 setcookie('MoodleSessionTest'.$CFG->sessioncookie, $_SESSION['SESSION']->session_test, 0, '/');
285 $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] = $_SESSION['SESSION']->session_test;
286 } else {
287 $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] = 'error!!';
290 if (! isset($_SESSION['USER'])) {
291 $_SESSION['USER'] = new object;
294 $SESSION = &$_SESSION['SESSION']; // Makes them easier to reference
295 $USER = &$_SESSION['USER'];
297 else {
298 $SESSION = NULL;
299 $USER = NULL;
302 if (defined('FULLME')) { // Usually in command-line scripts like admin/cron.php
303 $FULLME = FULLME;
304 $ME = FULLME;
305 } else {
306 $FULLME = qualified_me();
307 $ME = strip_querystring($FULLME);
310 /// In VERY rare cases old PHP server bugs (it has been found on PHP 4.1.2 running
311 /// as a CGI under IIS on Windows) may require that you uncomment the following:
312 // session_register("USER");
313 // session_register("SESSION");
317 /// Load up theme variables (colours etc)
319 if (!isset($CFG->themedir)) {
320 $CFG->themedir = $CFG->dirroot.'/theme/';
321 $CFG->themewww = $CFG->wwwroot.'/theme/';
324 if (isset($_GET['theme'])) {
325 if ($CFG->allowthemechangeonurl || confirm_sesskey()) {
326 if (!detect_munged_arguments($_GET['theme'], 0) and file_exists($CFG->themedir. $_GET['theme'])) {
327 $SESSION->theme = $_GET['theme'];
332 if (!isset($CFG->theme)) {
333 $CFG->theme = 'standardwhite';
336 theme_setup(); // Sets up theme global variables
338 /// now do a session test to prevent random user switching
339 if ($SESSION != NULL) {
340 if (empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
341 report_session_error();
342 } else if (isset($SESSION->session_test) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] != $SESSION->session_test) {
343 report_session_error();
349 /// Set language/locale of printed times. If user has chosen a language that
350 /// that is different from the site language, then use the locale specified
351 /// in the language file. Otherwise, if the admin hasn't specified a locale
352 /// then use the one from the default language. Otherwise (and this is the
353 /// majority of cases), use the stored locale specified by admin.
355 if (isset($_GET['lang'])) {
356 if (!detect_munged_arguments($lang, 0) and file_exists($CFG->dirroot .'/lang/'. $lang)) {
357 $SESSION->lang = $lang;
358 $SESSION->encoding = get_string('thischarset');
361 if (empty($CFG->lang)) {
362 $CFG->lang = "en";
365 moodle_setlocale();
367 if (!empty($CFG->opentogoogle)) {
368 if (empty($_SESSION['USER'])) {
369 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
370 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
371 $USER = guest_user();
373 if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) {
374 $USER = guest_user();
377 if (empty($_SESSION['USER']) and !empty($_SERVER['HTTP_REFERER'])) {
378 if (strpos($_SERVER['HTTP_REFERER'], 'google') !== false ) {
379 $USER = guest_user();
385 if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') { // Temporary measure to help with XHTML validation
386 if (empty($_SESSION['USER']->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
387 if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
388 (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
389 if ($USER = get_complete_user_data("username", "w3cvalidator")) {
390 $USER->ignoresesskey = true;
391 } else {
392 $USER = guest_user();
398 /// Apache log intergration. In apache conf file one can use ${MOODULEUSER}n in
399 /// LogFormat to get the current logged in username in moodle.
400 if ($USER && function_exists('apache_note') && !empty($CFG->apacheloguser)) {
401 switch ($CFG->apacheloguser) {
402 case 3:
403 $logname = clean_filename($USER->username);
404 break;
405 case 2:
406 $logname = clean_filename($USER->firstname." ".$USER->lastname);
407 break;
408 case 1:
409 default:
410 $logname = $USER->id;
411 break;
413 apache_note('MOODLEUSER', $logname);
416 /// Adjust ALLOWED_TAGS
417 adjust_allowed_tags();
419 /***
420 *** init_performance_info() {
422 *** Initializes our performance info early.
423 ***
424 *** Pairs up with get_performance_info() which is actually
425 *** in moodlelib.php. This function is here so that we can
426 *** call it before all the libs are pulled in.
429 function init_performance_info() {
431 global $PERF;
433 $PERF = new Object;
434 $PERF->dbqueries = 0;
435 $PERF->logwrites = 0;
436 if (function_exists('microtime')) {
437 $PERF->starttime = microtime();
439 if (function_exists('memory_get_usage')) {
440 $PERF->startmemory = memory_get_usage();
442 if (function_exists('posix_times')) {
443 $PERF->startposixtimes = posix_times();