Applied patch #411
[elgg.git] / lib / setup.php
blob12cfb42cc9cfb378ebad728b1aa8665878e314a9
1 <?php
3 // declare our globals.
4 global $db;
5 global $USER;
6 global $CFG;
7 global $SESSION;
8 global $PAGE;
10 /// First try to detect some attacks on older buggy PHP versions
11 if (isset($_REQUEST['GLOBALS']) || isset($_COOKIE['GLOBALS']) || isset($_FILES['GLOBALS'])) {
12 die('Fatal: Illegal GLOBALS overwrite attempt detected!');
15 // set up perf.
16 init_performance_info();
18 /// Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
19 /// http://www.google.com/webmasters/faq.html#prefetchblock
21 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
22 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
23 trigger_error('Prefetch request forbidden.');
24 exit;
27 // Privacy policy for IE, bless its cotton socks
29 header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
31 // Set defaults for some variables
33 if (!isset($CFG->tagline)) {
34 $CFG->tagline = "";
36 if (empty($CFG->debug)) {
37 $CFG->debug = 0;
39 if (empty($CFG->publicinvite)) {
40 $CFG->publicinvite = $CFG->publicreg;
42 if (empty($CFG->emailfilter)) {
43 $CFG->emailfilter = "";
45 if (empty($CFG->maxusers)) {
46 $CFG->maxusers = 0;
48 if (empty($CFG->walledgarden)) {
49 $CFG->walledgarden = 0;
52 if (empty($CFG->framename)) {
53 $CFG->framename = null;
56 if (empty($CFG->defaultlocale)) {
57 $CFG->defaultlocale = 'en';
60 if (empty($CFG->disable_templatechanging)) {
61 $CFG->disable_usertemplates = false;
64 if (empty($CFG->disable_templatechanging)) {
65 $CFG->disable_templatechanging = false;
68 if (empty($CFG->disable_publiccomments)) {
69 $CFG->disable_publiccomments = false;
72 if (empty($CFG->disable_passwordchanging)) {
73 $CFG->disable_passwordchanging = false;
76 if (empty($CFG->community_create_flag)) {
77 $CFG->community_create_flag = "";
80 if (empty($CFG->curlpath)) {
81 $CFG->curlpath = false;
84 if (empty($CFG->cookiepath)) {
85 $pathcomponents = @parse_url($CFG->wwwroot);
86 if (!empty($pathcomponents['path'])) {
87 $CFG->cookiepath = $pathcomponents['path'];
88 } else {
89 $CFG->cookiepath = '/';
91 unset($pathcomponents);
94 if (empty($CFG->absmaxuploadsize)) {
95 // absolute maximum allowed file upload size.
96 // in most cases, apache or php will have lower limits configured, that cannot be overridden in code.
97 $CFG->absmaxuploadsize = '20M';
100 $CFG->libdir = $CFG->dirroot . 'lib';
102 // set up our database connection
103 if ($CFG->debug & E_USER_ERROR) {
104 require_once($CFG->dirroot . 'lib/adodb/adodb-errorhandler.inc.php');
106 require_once($CFG->dirroot . 'lib/adodb/adodb.inc.php'); // Database access functions
108 $db = &ADONewConnection($CFG->dbtype);
109 $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
111 error_reporting(0); // Hide errors
113 if (!empty($CFG->dbpersist)) {
114 $dbcmd = 'PConnect'; // Use persistent connection (default)
115 } else {
116 $dbcmd = 'Connect'; // Use single connection
119 if (is_array($CFG->dbhost)) {
120 foreach ($CFG->dbhost as $ahost) {
121 if ($dbconnected = $db->$dbcmd($ahost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname)) {
122 $CFG->dbhost = $ahost;
123 break;
126 } else {
127 $dbconnected = $db->$dbcmd($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);
130 if (! $dbconnected) {
131 // In the name of protocol correctness, monitoring and performance
132 // profiling, set the appropriate error headers for machine consumption
133 if (isset($_SERVER['SERVER_PROTOCOL'])) {
134 // Avoid it with cron.php. Note that we assume it's HTTP/1.x
135 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
137 // and then for human consumption...
138 echo '<html><body>';
139 echo '<table align="center"><tr>';
140 echo '<td style="color:#990000; text-align:center; font-size:large; border-width:1px; '.
141 ' border-color:#000000; border-style:solid; border-radius: 20px; border-collapse: collapse; '.
142 ' -moz-border-radius: 20px; padding: 15px">';
143 echo '<p>Error: Database connection failed.</p>';
144 echo '<p>It is possible that the database is overloaded or otherwise not running properly.</p>';
145 echo '<p>The site administrator should also check that the database details have been correctly specified in config.php</p>';
146 echo '</td></tr></table>';
147 echo '</body></html>';
148 die;
149 } else {
150 if ($db->databaseType == 'mysql') {
151 $db->Execute("SET NAMES 'utf8'");
152 $db->Execute("SET CHARSET 'utf8'");
153 } else if ($db->databaseType == 'postgres7') {
154 $db->Execute("SET NAMES 'utf8'");
158 /// Load up any configuration from the config table
159 $METATABLES = $db->Metatables();
160 if ($METATABLES) {
161 $CFG = get_config();
164 /// Turn on SQL logging if required
165 if (!empty($CFG->logsql)) {
166 $db->LogSQL();
170 /// Set error reporting back to normal
171 if (empty($CFG->debug)) {
172 $CFG->debug = 7;
174 error_reporting($CFG->debug);
176 /// File permissions on created directories in the $CFG->dataroot
178 if (empty($CFG->directorypermissions)) {
179 $CFG->directorypermissions = 0777; // Must be octal (that's why it's here)
182 /// Files might not want all the permissions that directories have, e.g. +x or g+s,
183 /// so using a separate setting for files
184 if (empty($CFG->filepermissions)) {
185 $CFG->filepermissions = 0666; // Must be octal
188 if (!is_writable($CFG->dataroot)) {
189 $messages[] = "Your current dataroot directory, $CFG->dataroot is not writable by the webserver!";
192 /// Set up session handling
193 if(empty($CFG->respectsessionsettings)) {
194 if (empty($CFG->dbsessions)) { /// File-based sessions
196 // Some distros disable GC by setting probability to 0
197 // overriding the PHP default of 1
198 // (gc_probability is divided by gc_divisor, which defaults to 1000)
199 if (ini_get('session.gc_probability') == 0) {
200 ini_set('session.gc_probability', 1);
203 if (!empty($CFG->sessiontimeout)) {
204 ini_set('session.gc_maxlifetime', $CFG->sessiontimeout);
207 if (!file_exists($CFG->dataroot .'sessions')) {
208 require_once($CFG->dirroot . 'lib/uploadlib.php');
209 make_upload_directory('sessions');
211 ini_set('session.save_path', $CFG->dataroot .'sessions');
213 } else { /// Database sessions
214 ini_set('session.save_handler', 'user');
216 $ADODB_SESSION_DRIVER = $CFG->dbtype;
217 $ADODB_SESSION_CONNECT = $CFG->dbhost;
218 $ADODB_SESSION_USER = $CFG->dbuser;
219 $ADODB_SESSION_PWD = $CFG->dbpass;
220 $ADODB_SESSION_DB = $CFG->dbname;
221 $ADODB_SESSION_TBL = $CFG->prefix.'sessions';
223 require_once($CFG->libdir. '/adodb/session/adodb-session.php');
226 /// Set sessioncookie variable if it isn't already
227 if (!isset($CFG->sessioncookie)) {
228 $CFG->sessioncookie = '';
231 // for phpthumb
232 require_once($CFG->dirroot . 'lib/uploadlib.php');
233 make_upload_directory('cache/phpThumb');
234 // for magpie rss
235 make_upload_directory('cache/magpie');
236 define('MAGPIE_CACHE_DIR',$CFG->dataroot.'cache/magpie');
238 // Files
239 make_upload_directory('cache/files');
241 /// Configure ampersands in URLs
243 @ini_set('arg_separator.output', '&amp;');
245 /// Refuse to run with register_globals
246 if (ini_get_bool('register_globals')) {
247 die("Elgg cannot run with register_globals on");
250 // Now we use prepared statements everywhere,
251 // we want everything to be stripslashed
252 // rather than addslashed.
253 if (ini_get_bool('magic_quotes_gpc') ) {
255 //do keys as well, cos array_map ignores them
256 function stripslashes_arraykeys($array) {
257 if (is_array($array)) {
258 $array2 = array();
259 foreach ($array as $key => $data) {
260 if ($key != stripslashes($key)) {
261 $array2[stripslashes($key)] = $data;
262 } else {
263 $array2[$key] = $data;
266 return $array2;
267 } else {
268 return $array;
272 function stripslashes_deep($value) {
273 if (is_array($value)) {
274 $value = stripslashes_arraykeys($value);
275 $value = array_map('stripslashes_deep', $value);
276 } else {
277 $value = stripslashes($value);
279 return $value;
282 $_POST = stripslashes_arraykeys($_POST);
283 $_GET = stripslashes_arraykeys($_GET);
284 $_COOKIE = stripslashes_arraykeys($_COOKIE);
285 $_REQUEST = stripslashes_arraykeys($_REQUEST);
287 $_POST = array_map('stripslashes_deep', $_POST);
288 $_GET = array_map('stripslashes_deep', $_GET);
289 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
290 $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
291 if (!empty($_SERVER['REQUEST_URI'])) {
292 $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']);
294 if (!empty($_SERVER['QUERY_STRING'])) {
295 $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']);
297 if (!empty($_SERVER['HTTP_REFERER'])) {
298 $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']);
300 if (!empty($_SERVER['PATH_INFO'])) {
301 $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']);
303 if (!empty($_SERVER['PHP_SELF'])) {
304 $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']);
306 if (!empty($_SERVER['PATH_TRANSLATED'])) {
307 $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']);
312 // wtf? $noelggcookie is never set - Sven
313 if (!isset($noelggcookie)) {
314 session_name('ElggSession'.$CFG->sessioncookie);
315 ini_set("session.cookie_path", $CFG->cookiepath);
316 @session_start();
317 if (! isset($_SESSION['SESSION'])) {
318 $_SESSION['SESSION'] = new Stdclass;
319 $_SESSION['SESSION']->session_test = random_string(10);
320 if (!empty($_COOKIE['ElggSessionTest'.$CFG->sessioncookie])) {
321 $_SESSION['SESSION']->has_timed_out = true;
323 setcookie('ElggSessionTest'.$CFG->sessioncookie, $_SESSION['SESSION']->session_test, 0, $CFG->cookiepath);
324 $_COOKIE['ElggSessionTest'.$CFG->sessioncookie] = $_SESSION['SESSION']->session_test;
326 if (! isset($_SESSION['USER'])) {
327 $_SESSION['USER'] = new StdClass;
330 $SESSION = &$_SESSION['SESSION']; // Makes them easier to reference
331 $USER = &$_SESSION['USER'];
333 else {
334 $SESSION = NULL;
335 $USER = NULL;
338 // Load textlib
339 require_once($CFG->dirroot . 'lib/textlib.class.php');
341 if (defined('FULLME')) { // Usually in command-line scripts like admin/cron.php
342 $FULLME = FULLME;
343 $ME = FULLME;
344 } else {
345 $FULLME = qualified_me();
346 $ME = strip_querystring($FULLME);
349 /// In VERY rare cases old PHP server bugs (it has been found on PHP 4.1.2 running
350 /// as a CGI under IIS on Windows) may require that you uncomment the following:
351 // session_register("USER");
352 // session_register("SESSION");
354 /// now do a session test to prevent random user switching
355 if ($SESSION != NULL) {
356 if (empty($_COOKIE['ElggSessionTest'.$CFG->sessioncookie])) {
357 report_session_error();
358 } else if (isset($SESSION->session_test) && $_COOKIE['ElggSessionTest'.$CFG->sessioncookie] != $SESSION->session_test) {
359 report_session_error();
363 if (!empty($CFG->opentogoogle)) {
364 if (empty($_SESSION['USER'])) {
365 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
366 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
367 $USER = guest_user();
369 if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) {
370 $USER = guest_user();
373 if (empty($_SESSION['USER']) and !empty($_SERVER['HTTP_REFERER'])) {
374 if (strpos($_SERVER['HTTP_REFERER'], 'google') !== false ) {
375 $USER = guest_user();
376 } else if (strpos($_SERVER['HTTP_REFERER'], 'altavista') !== false ) {
377 $USER = guest_user();
383 /// Populates an empty $USER if is empty
384 if (empty($USER) || !isset($USER->ident)) {
385 $USER = guest_user();
388 /// backwards compatibility
389 fill_legacy_user_session($USER);
391 //////
392 ////// Load some core libraries
393 //////
394 require_once($CFG->dirroot . "lib/templates.php");
395 require_once($CFG->dirroot . "lib/displaylib.php");
397 //////
398 ////// Init templating basics
399 //////
400 if (!isset($CFG->templatestore)) { $CFG->templatestore = 'db' ;}
401 if (!isset($CFG->templatesroot)) { $CFG->templatesroot = $CFG->dirroot . "mod/template/templates/";}
402 if (!isset($PAGE->menu )) { $PAGE->menu = array();}
403 if (!isset($PAGE->menu_sub )) { $PAGE->menu_sub = array();}
404 if (!isset($PAGE->menu_top )) { $PAGE->menu_top = array();}
405 if (!isset($PAGE->menu_bottom)) { $PAGE->menu_bottom = array();}
407 //////
408 ////// Define what modules we have, and load their libraries
409 //////
411 // TODO : set up a modules table so we can do get_records('modules')
412 // to fetch the enabled ones (instead of all the available modules)
413 // we can also track db version with it.
414 if ($allmods = get_list_of_plugins('mod') ) {
415 foreach ($allmods as $mod) {
416 $modfile = $CFG->dirroot . 'mod/'.$mod .'/lib.php';
417 if (file_exists($modfile)) {
418 include_once($modfile);
422 // keep the global scope clean
423 unset($allmods); unset ($mod); unset($modfile);
425 /// Apache log integration. In apache conf file one can use ${ELGGUSER}n in
426 /// LogFormat to get the current logged in username in Elgg.
427 /// NOTE: we are grabbing the username -- see the commented out lines
428 /// for alternative things that could be logged...
429 if ($USER && function_exists('apache_note')) {
430 $apachelog_username = clean_filename($USER->username);
431 // $apachelog_name = clean_filename($USER->firstname. " ".$USER->lastname);
432 // $apachelog_userid = $USER->ident;
433 /* Enable this commented out section ONLY if Elgg can do
434 user masquerading...
435 if (isset($USER->realuser)) {
436 if ($realuser = get_record('users', 'ident', $USER->realuser)) {
437 $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
438 // $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
439 // $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
443 apache_note('ELGGUSER', $apachelog_username);
446 /// Adjust ALLOWED_TAGS
447 adjust_allowed_tags();
449 // backwards compatibility (this is what elgg used to use)
450 define("db_server", $CFG->dbhost);
451 define("db_user",$CFG->dbuser);
452 define("db_pass",$CFG->dbpass);
453 define("db_name",$CFG->dbname);
455 define("sitename", $CFG->sitename);
456 define("url",$CFG->wwwroot);
457 define("path",$CFG->dirroot);
458 define("email",$CFG->sysadminemail);
459 define("locale", $CFG->defaultlocale);
460 //define("public_reg", $CFG->publicreg);
461 if (empty($CFG->default_access)) {
462 $CFG->default_access = "LOGGED_IN";
464 define("default_access",$CFG->default_access);
466 // figure out a noreply address if we don't have one.
467 if (empty($CFG->noreplyaddress)) {
468 $CFG->noreplyaddress = 'noreply@'.preg_replace('/([a-zA-z]*:\/\/)([a-zA-Z0-9-.]*)([:0-9]*)(\/*.*)/','$2',$CFG->wwwroot);
472 /***
473 *** init_performance_info() {
475 *** Initializes our performance info early.
476 ***
477 *** Pairs up with get_performance_info() which is actually
478 *** in moodlelib.php. This function is here so that we can
479 *** call it before all the libs are pulled in.
482 function init_performance_info() {
484 global $PERF;
486 $PERF = new StdClass;
487 $PERF->dbqueries = 0;
488 $PERF->logwrites = 0;
489 if (function_exists('microtime')) {
490 $PERF->starttime = microtime();
492 if (function_exists('memory_get_usage')) {
493 $PERF->startmemory = memory_get_usage();
495 if (function_exists('posix_times')) {
496 $PERF->startposixtimes = posix_times();