root/releases/0.9.1/lib/setup.php

Revision 1551, 18.2 kB (checked in by misja, 10 months ago)

Misja Hoebe <misja@curverider.co.uk> Applied patch, closes #258

  • Property svn:eol-style set to native
Line 
1 <?php
2
3 // declare our globals.
4 global $db;
5 global $USER;
6 global $CFG;
7 global $SESSION;
8 global $PAGE;
9
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!');
13 }
14
15 // TODO: Can't run in safe mode
16 if (ini_get_bool('safe_mode')) {
17     die("Fatal: Your server has safe_mode set to ON, elgg can't run with safe_mode enabled.");
18 }
19
20 // set up perf.
21 init_performance_info();
22
23 /// Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
24 /// http://www.google.com/webmasters/faq.html#prefetchblock
25
26 if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
27     header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');       
28     trigger_error('Prefetch request forbidden.');
29     exit;
30 }
31
32 // Privacy policy for IE, bless its cotton socks
33
34 header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
35
36 // Set defaults for some variables
37
38 if (!isset($CFG->tagline)) {
39     $CFG->tagline = "";
40 }
41 if (!isset($CFG->debug)) {
42     $CFG->debug = 0;
43 }
44 if (!isset($CFG->publicinvite)) {
45     $CFG->publicinvite = $CFG->publicreg;
46 }
47 if (empty($CFG->emailfilter)) {
48     $CFG->emailfilter = "";
49 }
50 if (empty($CFG->maxusers)) {
51     $CFG->maxusers = 0;
52 }
53 if (empty($CFG->walledgarden)) {
54     $CFG->walledgarden = 0;
55 }
56
57 if (empty($CFG->framename)) {
58     $CFG->framename = null;
59 }
60
61 if (empty($CFG->defaultlocale)) {
62     $CFG->defaultlocale = 'en';
63 }
64
65 if (empty($CFG->disable_usertemplates)) {
66     $CFG->disable_usertemplates = false;
67 }
68
69 if (empty($CFG->disable_templatechanging)) {
70     $CFG->disable_templatechanging = false;
71 }
72
73 if (empty($CFG->disable_publiccomments)) {
74     $CFG->disable_publiccomments = false;
75 }
76
77 if (empty($CFG->disable_passwordchanging)) {
78     $CFG->disable_passwordchanging = false;
79 }
80
81 if (empty($CFG->community_create_flag)) {
82     $CFG->community_create_flag = "";
83 }
84
85 if (empty($CFG->curlpath)) {
86     $CFG->curlpath = false;
87 }
88
89 if (empty($CFG->cookiepath)) {
90     $pathcomponents = @parse_url($CFG->wwwroot);
91     if (!empty($pathcomponents['path'])) {
92         $CFG->cookiepath = $pathcomponents['path'];
93     } else {
94         $CFG->cookiepath = '/';
95     }
96     unset($pathcomponents);
97 }
98
99 if (empty($CFG->absmaxuploadsize)) {
100     // absolute maximum allowed file upload size.
101     // in most cases, apache or php will have lower limits configured, that cannot be overridden in code.
102     $CFG->absmaxuploadsize = '20M';
103 }
104
105 $CFG->libdir = $CFG->dirroot . 'lib';
106
107 // set up our database connection
108 if ($CFG->debug & E_USER_ERROR) {
109     require_once($CFG->dirroot . 'lib/adodb/adodb-errorhandler.inc.php');
110 }
111 require_once($CFG->dirroot . 'lib/adodb/adodb.inc.php'); // Database access functions
112
113 $db = &ADONewConnection($CFG->dbtype);
114 $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
115
116 error_reporting(0);  // Hide errors
117
118 if (!empty($CFG->dbpersist)) {
119     $dbcmd = 'PConnect'; // Use persistent connection (default)
120 } else {
121     $dbcmd = 'Connect'; // Use single connection
122 }
123
124 if (is_array($CFG->dbhost)) {
125     foreach ($CFG->dbhost as $ahost) {
126         if ($dbconnected = $db->$dbcmd($ahost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname)) {
127             $CFG->dbhost = $ahost;
128             break;
129         }
130     }
131 } else {
132     $dbconnected = $db->$dbcmd($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);
133 }
134
135 if (! $dbconnected) {
136     // In the name of protocol correctness, monitoring and performance
137     // profiling, set the appropriate error headers for machine consumption
138     if (isset($_SERVER['SERVER_PROTOCOL'])) {
139         // Avoid it with cron.php. Note that we assume it's HTTP/1.x
140         header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');       
141     }
142     // and then for human consumption...
143     echo '<html><body>';
144     echo '<table align="center"><tr>';
145     echo '<td style="color:#990000; text-align:center; font-size:large; border-width:1px; '.
146         '    border-color:#000000; border-style:solid; border-radius: 20px; border-collapse: collapse; '.
147         '    -moz-border-radius: 20px; padding: 15px">';
148     echo '<p>Error: Database connection failed.</p>';
149     echo '<p>It is possible that the database is overloaded or otherwise not running properly.</p>';
150     echo '<p>The site administrator should also check that the database details have been correctly specified in config.php</p>';
151     echo '</td></tr></table>';
152     echo '</body></html>';
153     die;
154 } else {
155     if ($db->databaseType == 'mysql') {
156         $db->Execute("SET NAMES 'utf8'");
157         $db->Execute("SET CHARSET 'utf8'");
158     } else if ($db->databaseType == 'postgres7') {
159         $db->Execute("SET NAMES 'utf8'");
160     }
161 }
162
163 /// Load up any configuration from the config table
164 $METATABLES = $db->Metatables();
165 if ($METATABLES) {
166     $CFG = get_config();
167 }
168
169 /// Turn on SQL logging if required
170 if (!empty($CFG->logsql)) {
171     $db->LogSQL();
172 }
173
174
175 /// Set error reporting back to normal
176 if (!isset($CFG->debug)) {
177     $CFG->debug = 7;
178 }
179
180 // if not debug log errors
181 // else if enabled show raw errors on screen
182 if ($CFG->debug < 2047) {
183     // always log errors
184     @ini_set('log_errors', '1');
185     @ini_set('error_log', $CFG->dataroot . 'errors.log');
186     // hide error of screen, handled by error handler function
187     @ini_set('display_errors', '0');
188     // handle errors
189     //TODO: work on better error handler
190     set_error_handler('elgg_error_handler');
191 } else {
192     //force display errors on screen
193     @ini_set('display_errors', '1');
194     @ini_set('display_startup_errors', '1'); // maybe not good idea...
195     error_reporting($CFG->debug);
196 }
197
198 /// File permissions on created directories in the $CFG->dataroot
199
200 if (empty($CFG->directorypermissions)) {
201     $CFG->directorypermissions = 0777;      // Must be octal (that's why it's here)
202 }
203
204 /// Files might not want all the permissions that directories have, e.g. +x or g+s,
205 /// so using a separate setting for files
206 if (empty($CFG->filepermissions)) {
207     $CFG->filepermissions = 0666;      // Must be octal
208 }
209
210 if (!is_writable($CFG->dataroot)) {
211     die("Your current dataroot directory, <strong>$CFG->dataroot</strong> is not writable by the webserver!");
212 }
213
214 /// Set up session handling
215 if(empty($CFG->respectsessionsettings)) {
216     if (empty($CFG->dbsessions)) {   /// File-based sessions
217         
218         // Some distros disable GC by setting probability to 0
219         // overriding the PHP default of 1
220         // (gc_probability is divided by gc_divisor, which defaults to 1000)
221         if (ini_get('session.gc_probability') == 0) {
222             ini_set('session.gc_probability', 1);
223         }
224         
225         if (!empty($CFG->sessiontimeout)) {
226             ini_set('session.gc_maxlifetime', $CFG->sessiontimeout);
227         }
228         
229         if (!file_exists($CFG->dataroot .'sessions')) {
230             require_once($CFG->dirroot . 'lib/uploadlib.php');
231             make_upload_directory('sessions');
232         }
233         ini_set('session.save_path', $CFG->dataroot .'sessions');
234         
235     } else {                         /// Database sessions
236         ini_set('session.save_handler', 'user');
237         
238         $ADODB_SESSION_DRIVER  = $CFG->dbtype;
239         $ADODB_SESSION_CONNECT = $CFG->dbhost;
240         $ADODB_SESSION_USER    = $CFG->dbuser;
241         $ADODB_SESSION_PWD     = $CFG->dbpass;
242         $ADODB_SESSION_DB      = $CFG->dbname;
243         $ADODB_SESSION_TBL     = $CFG->prefix.'sessions';
244         
245         require_once($CFG->libdir. '/adodb/session/adodb-session.php');
246     }
247 }
248 /// Set sessioncookie variable if it isn't already
249 if (!isset($CFG->sessioncookie)) {
250     $CFG->sessioncookie = '';
251 }
252
253 // for phpthumb
254 require_once($CFG->dirroot . 'lib/uploadlib.php');
255 make_upload_directory('cache/phpThumb');
256 // for magpie rss
257 make_upload_directory('cache/magpie');
258 define('MAGPIE_CACHE_DIR',$CFG->dataroot.'cache/magpie');
259
260 // Files
261 make_upload_directory('cache/files');
262
263 /// Configure ampersands in URLs
264
265 @ini_set('arg_separator.output', '&amp;');
266
267 /// Refuse to run with register_globals
268 if (ini_get_bool('register_globals')) {
269     die("Elgg cannot run with register_globals on");
270 }
271
272 // Now we use prepared statements everywhere,
273 // we want everything to be stripslashed
274 // rather than addslashed.
275 if (ini_get_bool('magic_quotes_gpc') ) {
276     
277     //do keys as well, cos array_map ignores them
278     function stripslashes_arraykeys($array) {
279         if (is_array($array)) {
280             $array2 = array();
281             foreach ($array as $key => $data) {
282                 if ($key != stripslashes($key)) {
283                     $array2[stripslashes($key)] = $data;
284                 } else {
285                     $array2[$key] = $data;
286                 }
287             }
288             return $array2;
289         } else {
290             return $array;
291         }
292     }
293     
294     function stripslashes_deep($value) {
295         if (is_array($value)) {
296             $value = stripslashes_arraykeys($value);
297             $value = array_map('stripslashes_deep', $value);
298         } else {
299             $value = stripslashes($value);
300         }
301         return $value;
302     }
303     
304     $_POST = stripslashes_arraykeys($_POST);
305     $_GET = stripslashes_arraykeys($_GET);
306     $_COOKIE = stripslashes_arraykeys($_COOKIE);
307     $_REQUEST = stripslashes_arraykeys($_REQUEST);
308     
309     $_POST = array_map('stripslashes_deep', $_POST);
310     $_GET = array_map('stripslashes_deep', $_GET);
311     $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
312     $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
313     if (!empty($_SERVER['REQUEST_URI'])) {
314         $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']);
315     }
316     if (!empty($_SERVER['QUERY_STRING'])) {
317         $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']);
318     }
319     if (!empty($_SERVER['HTTP_REFERER'])) {
320         $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']);
321     }
322     if (!empty($_SERVER['PATH_INFO'])) {
323         $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']);
324     }
325     if (!empty($_SERVER['PHP_SELF'])) {
326         $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']);
327     }
328     if (!empty($_SERVER['PATH_TRANSLATED'])) {
329         $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']);
330     }
331     
332 }
333
334 // wtf? $noelggcookie is never set - Sven
335 if (!isset($noelggcookie)) {
336     session_name('ElggSession'.$CFG->sessioncookie);
337     ini_set("session.cookie_path", $CFG->cookiepath);
338     @session_start();
339     if (! isset($_SESSION['SESSION'])) {
340         $_SESSION['SESSION'] = new Stdclass;
341         $_SESSION['SESSION']->session_test = random_string(10);
342         if (!empty($_COOKIE['ElggSessionTest'.$CFG->sessioncookie])) {
343             $_SESSION['SESSION']->has_timed_out = true;
344         }
345         setcookie('ElggSessionTest'.$CFG->sessioncookie, $_SESSION['SESSION']->session_test, 0, $CFG->cookiepath);
346         $_COOKIE['ElggSessionTest'.$CFG->sessioncookie] = $_SESSION['SESSION']->session_test;
347     }
348
349     //@rho Force to reload user data from db
350     $_SESSION['USER']    = new StdClass;
351     
352     $SESSION = &$_SESSION['SESSION'];   // Makes them easier to reference
353     $USER    = &$_SESSION['USER'];
354 }
355 else {
356     $SESSION = NULL;
357     $USER    = NULL;
358 }
359
360 // Load textlib
361 require_once($CFG->dirroot . 'lib/textlib.class.php');
362
363 if (defined('FULLME')) {     // Usually in command-line scripts like admin/cron.php
364     $FULLME = FULLME;
365     $ME = FULLME;
366 } else {
367     $FULLME = qualified_me();
368     $ME = strip_querystring($FULLME);
369 }
370
371 /// In VERY rare cases old PHP server bugs (it has been found on PHP 4.1.2 running
372 /// as a CGI under IIS on Windows) may require that you uncomment the following:
373 //  session_register("USER");
374 //  session_register("SESSION");
375
376 /// now do a session test to prevent random user switching
377 if ($SESSION != NULL) {
378     if (empty($_COOKIE['ElggSessionTest'.$CFG->sessioncookie])) {
379         report_session_error();
380     } else if (isset($SESSION->session_test) && $_COOKIE['ElggSessionTest'.$CFG->sessioncookie] != $SESSION->session_test) {
381         report_session_error();
382     }
383 }
384
385 if (!empty($CFG->opentogoogle)) {
386     if (empty($_SESSION['USER'])) {
387         if (!empty($_SERVER['HTTP_USER_AGENT'])) {
388             if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
389                 $USER = guest_user();
390             }
391             if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) {
392                 $USER = guest_user();
393             }
394         }
395         if (empty($_SESSION['USER']) and !empty($_SERVER['HTTP_REFERER'])) {
396             if (strpos($_SERVER['HTTP_REFERER'], 'google') !== false ) {
397                 $USER = guest_user();
398             } else if (strpos($_SERVER['HTTP_REFERER'], 'altavista') !== false ) {
399                 $USER = guest_user();
400             }
401         }
402     }
403 }
404
405 /// Populates an empty $USER if is empty
406 if (empty($USER) || !isset($USER->ident)) {
407     $USER = guest_user();
408 }
409
410 /// backwards compatibility
411 fill_legacy_user_session($USER);
412
413 //////
414 ////// Load some core libraries
415 //////
416 require_once($CFG->dirroot . "lib/templates.php");
417 require_once($CFG->dirroot . "lib/displaylib.php");
418
419 //////
420 ////// Init templating basics
421 //////
422 if (!isset($CFG->templatestore)) { $CFG->templatestore = 'db' ;}
423 if (!isset($CFG->templatesroot)) { $CFG->templatesroot = $CFG->dirroot . "mod/template/templates/";}
424 if (!isset($PAGE->menu       )) { $PAGE->menu        = array();}
425 if (!isset($PAGE->menu_sub   )) { $PAGE->menu_sub    = array();}
426 if (!isset($PAGE->menu_top   )) { $PAGE->menu_top    = array();}
427 if (!isset($PAGE->menu_bottom)) { $PAGE->menu_bottom = array();}
428
429 //////
430 ////// Define what modules we have, and load their libraries
431 //////
432
433 // TODO : set up a modules table so we can do get_records('modules')
434 //        to fetch the enabled ones (instead of all the available modules)
435 //        we can also track db version with it.
436 if ($allmods = get_list_of_plugins('mod') ) {
437     foreach ($allmods as $mod) {
438         $modfile = $CFG->dirroot . 'mod/'.$mod .'/lib.php';
439         if (file_exists($modfile)) {
440             include_once($modfile);
441         }
442     }
443 }
444 // keep the global scope clean
445 unset($allmods); unset ($mod); unset($modfile);
446
447 /// Apache log integration. In apache conf file one can use ${ELGGUSER}n in
448 /// LogFormat to get the current logged in username in Elgg.
449 /// NOTE: we are grabbing the username -- see the commented out lines
450 /// for alternative things that could be logged...
451 if ($USER && function_exists('apache_note')) {
452     $apachelog_username = clean_filename($USER->username);
453     // $apachelog_name     = clean_filename($USER->firstname. " ".$USER->lastname);
454     // $apachelog_userid   = $USER->ident;
455     /* Enable this commented out section ONLY if Elgg can do
456        user masquerading...
457     if (isset($USER->realuser)) {
458         if ($realuser = get_record('users', 'ident', $USER->realuser)) {
459             $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);           
460             // $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
461             // $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
462         }
463     }
464     */
465     apache_note('ELGGUSER', $apachelog_username);
466 }
467
468 /// Adjust ALLOWED_TAGS
469 adjust_allowed_tags();
470
471 // backwards compatibility (this is what elgg used to use)
472 define("db_server", $CFG->dbhost);
473 define("db_user",$CFG->dbuser);
474 define("db_pass",$CFG->dbpass);
475 define("db_name",$CFG->dbname);
476
477 define("sitename", $CFG->sitename);
478 define("url",$CFG->wwwroot);
479 define("path",$CFG->dirroot);
480 define("email",$CFG->sysadminemail);
481 define("locale", $CFG->defaultlocale);
482 //define("public_reg", $CFG->publicreg);
483 if (empty($CFG->default_access)) {
484     $CFG->default_access = "LOGGED_IN";
485 }
486 define("default_access",$CFG->default_access);
487
488 // figure out a noreply address if we don't have one.
489 if (empty($CFG->noreplyaddress)) {
490     $CFG->noreplyaddress = 'noreply@'.preg_replace('/([a-zA-z]*:\/\/)([a-zA-Z0-9-.]*)([:0-9]*)(\/*.*)/','$2',$CFG->wwwroot);
491 }
492
493
494 /***
495  *** init_performance_info() {
496  ***
497  *** Initializes our performance info early.
498  ***
499  *** Pairs up with get_performance_info() which is actually
500  *** in moodlelib.php. This function is here so that we can
501  *** call it before all the libs are pulled in.
502  ***
503  **/
504 function init_performance_info() {
505
506     global $PERF;
507
508     $PERF = new StdClass;
509     $PERF->dbqueries = 0;   
510     $PERF->logwrites = 0;
511     if (function_exists('microtime')) {
512         $PERF->starttime = microtime();
513     }
514     if (function_exists('memory_get_usage')) {
515         $PERF->startmemory = memory_get_usage();
516     }
517     if (function_exists('posix_times')) {
518         $PERF->startposixtimes = posix_times(); 
519     }
520 }
521
522 /**
523  * Basic error handler
524  */
525 function elgg_error_handler($errno, $errmsg, $errfile, $errline, $errcontext) {
526     global $CFG;
527
528     $date = date('Y-m-d H:i:s');
529     $fatal = "$errmsg (# $errno)";
530     $file = "Error in line $errline of file $errfile";
531     $script = "Script: {$_SERVER['PHP_SELF']}";
532
533     switch ($errno) {
534         case E_USER_NOTICE:
535         case E_NOTICE:
536             if ($CFG->debug == 2047) {
537                 $msg = sprintf("%s\nNotice: %s \n %s\n%s\n",$date,$fatal,$file,$script);
538                 error_log($msg);
539             }
540             break;
541         case E_USER_WARNING:
542         case E_WARNING:
543         case E_CORE_WARNING:
544         case E_COMPILE_WARNING:
545             //log errors if debug enabled
546             if ($CFG->debug >= 7) {
547                 $msg = "$date\nWarning: $fatal\n$file\n$script\n";
548                 $msg = sprintf("%s\nWarning: %s\n%s\%s\n",$date,$fatal,$file,$script);
549                 error_log($msg);