root/releases/0.9/lib/setup.php

Revision 1463, 18.0 kB (checked in by misja, 1 year ago)

Misja Hoebe <misja@curverider.co.uk> Merge r1456, r1457, r1458, r1459, r1460, r1461, r1462 into 0.9 branch

  • 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 (empty($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_templatechanging)) {
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 // always log errors
181 @ini_set('log_errors', '1');
182 @ini_set('error_log', $CFG->dataroot . 'errors.log');
183 // hide error of screen, handled by error handler function
184 @ini_set('display_errors', '0');
185 // handle errors
186 set_error_handler('elgg_error_handler');
187
188 /// File permissions on created directories in the $CFG->dataroot
189
190 if (empty($CFG->directorypermissions)) {
191     $CFG->directorypermissions = 0777;      // Must be octal (that's why it's here)
192 }
193
194 /// Files might not want all the permissions that directories have, e.g. +x or g+s,
195 /// so using a separate setting for files
196 if (empty($CFG->filepermissions)) {
197     $CFG->filepermissions = 0666;      // Must be octal
198 }
199
200 if (!is_writable($CFG->dataroot)) {
201     die("Your current dataroot directory, <strong>$CFG->dataroot</strong> is not writable by the webserver!");
202 }
203
204 /// Set up session handling
205 if(empty($CFG->respectsessionsettings)) {
206     if (empty($CFG->dbsessions)) {   /// File-based sessions
207         
208         // Some distros disable GC by setting probability to 0
209         // overriding the PHP default of 1
210         // (gc_probability is divided by gc_divisor, which defaults to 1000)
211         if (ini_get('session.gc_probability') == 0) {
212             ini_set('session.gc_probability', 1);
213         }
214         
215         if (!empty($CFG->sessiontimeout)) {
216             ini_set('session.gc_maxlifetime', $CFG->sessiontimeout);
217         }
218         
219         if (!file_exists($CFG->dataroot .'sessions')) {
220             require_once($CFG->dirroot . 'lib/uploadlib.php');
221             make_upload_directory('sessions');
222         }
223         ini_set('session.save_path', $CFG->dataroot .'sessions');
224         
225     } else {                         /// Database sessions
226         ini_set('session.save_handler', 'user');
227         
228         $ADODB_SESSION_DRIVER  = $CFG->dbtype;
229         $ADODB_SESSION_CONNECT = $CFG->dbhost;
230         $ADODB_SESSION_USER    = $CFG->dbuser;
231         $ADODB_SESSION_PWD     = $CFG->dbpass;
232         $ADODB_SESSION_DB      = $CFG->dbname;
233         $ADODB_SESSION_TBL     = $CFG->prefix.'sessions';
234         
235         require_once($CFG->libdir. '/adodb/session/adodb-session.php');
236     }
237 }
238 /// Set sessioncookie variable if it isn't already
239 if (!isset($CFG->sessioncookie)) {
240     $CFG->sessioncookie = '';
241 }
242
243 // for phpthumb
244 require_once($CFG->dirroot . 'lib/uploadlib.php');
245 make_upload_directory('cache/phpThumb');
246 // for magpie rss
247 make_upload_directory('cache/magpie');
248 define('MAGPIE_CACHE_DIR',$CFG->dataroot.'cache/magpie');
249
250 // Files
251 make_upload_directory('cache/files');
252
253 /// Configure ampersands in URLs
254
255 @ini_set('arg_separator.output', '&amp;');
256
257 /// Refuse to run with register_globals
258 if (ini_get_bool('register_globals')) {
259     die("Elgg cannot run with register_globals on");
260 }
261
262 // Now we use prepared statements everywhere,
263 // we want everything to be stripslashed
264 // rather than addslashed.
265 if (ini_get_bool('magic_quotes_gpc') ) {
266     
267     //do keys as well, cos array_map ignores them
268     function stripslashes_arraykeys($array) {
269         if (is_array($array)) {
270             $array2 = array();
271             foreach ($array as $key => $data) {
272                 if ($key != stripslashes($key)) {
273                     $array2[stripslashes($key)] = $data;
274                 } else {
275                     $array2[$key] = $data;
276                 }
277             }
278             return $array2;
279         } else {
280             return $array;
281         }
282     }
283     
284     function stripslashes_deep($value) {
285         if (is_array($value)) {
286             $value = stripslashes_arraykeys($value);
287             $value = array_map('stripslashes_deep', $value);
288         } else {
289             $value = stripslashes($value);
290         }
291         return $value;
292     }
293     
294     $_POST = stripslashes_arraykeys($_POST);
295     $_GET = stripslashes_arraykeys($_GET);
296     $_COOKIE = stripslashes_arraykeys($_COOKIE);
297     $_REQUEST = stripslashes_arraykeys($_REQUEST);
298     
299     $_POST = array_map('stripslashes_deep', $_POST);
300     $_GET = array_map('stripslashes_deep', $_GET);
301     $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
302     $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
303     if (!empty($_SERVER['REQUEST_URI'])) {
304         $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']);
305     }
306     if (!empty($_SERVER['QUERY_STRING'])) {
307         $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']);
308     }
309     if (!empty($_SERVER['HTTP_REFERER'])) {
310         $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']);
311     }
312     if (!empty($_SERVER['PATH_INFO'])) {
313         $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']);
314     }
315     if (!empty($_SERVER['PHP_SELF'])) {
316         $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']);
317     }
318     if (!empty($_SERVER['PATH_TRANSLATED'])) {
319         $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']);
320     }
321     
322 }
323
324 // wtf? $noelggcookie is never set - Sven
325 if (!isset($noelggcookie)) {
326     session_name('ElggSession'.$CFG->sessioncookie);
327     ini_set("session.cookie_path", $CFG->cookiepath);
328     @session_start();
329     if (! isset($_SESSION['SESSION'])) {
330         $_SESSION['SESSION'] = new Stdclass;
331         $_SESSION['SESSION']->session_test = random_string(10);
332         if (!empty($_COOKIE['ElggSessionTest'.$CFG->sessioncookie])) {
333             $_SESSION['SESSION']->has_timed_out = true;
334         }
335         setcookie('ElggSessionTest'.$CFG->sessioncookie, $_SESSION['SESSION']->session_test, 0, $CFG->cookiepath);
336         $_COOKIE['ElggSessionTest'.$CFG->sessioncookie] = $_SESSION['SESSION']->session_test;
337     }
338     if (! isset($_SESSION['USER']))    {
339         $_SESSION['USER']    = new StdClass;
340     }
341     
342     $SESSION = &$_SESSION['SESSION'];   // Makes them easier to reference
343     $USER    = &$_SESSION['USER'];
344 }
345 else {
346     $SESSION = NULL;
347     $USER    = NULL;
348 }
349
350 // Load textlib
351 require_once($CFG->dirroot . 'lib/textlib.class.php');
352
353 if (defined('FULLME')) {     // Usually in command-line scripts like admin/cron.php
354     $FULLME = FULLME;
355     $ME = FULLME;
356 } else {
357     $FULLME = qualified_me();
358     $ME = strip_querystring($FULLME);
359 }
360
361 /// In VERY rare cases old PHP server bugs (it has been found on PHP 4.1.2 running
362 /// as a CGI under IIS on Windows) may require that you uncomment the following:
363 //  session_register("USER");
364 //  session_register("SESSION");
365
366 /// now do a session test to prevent random user switching
367 if ($SESSION != NULL) {
368     if (empty($_COOKIE['ElggSessionTest'.$CFG->sessioncookie])) {
369         report_session_error();
370     } else if (isset($SESSION->session_test) && $_COOKIE['ElggSessionTest'.$CFG->sessioncookie] != $SESSION->session_test) {
371         report_session_error();
372     }
373 }
374
375 if (!empty($CFG->opentogoogle)) {
376     if (empty($_SESSION['USER'])) {
377         if (!empty($_SERVER['HTTP_USER_AGENT'])) {
378             if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
379                 $USER = guest_user();
380             }
381             if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) {
382                 $USER = guest_user();
383             }
384         }
385         if (empty($_SESSION['USER']) and !empty($_SERVER['HTTP_REFERER'])) {
386             if (strpos($_SERVER['HTTP_REFERER'], 'google') !== false ) {
387                 $USER = guest_user();
388             } else if (strpos($_SERVER['HTTP_REFERER'], 'altavista') !== false ) {
389                 $USER = guest_user();
390             }
391         }
392     }
393 }
394
395 /// Populates an empty $USER if is empty
396 if (empty($USER) || !isset($USER->ident)) {
397     $USER = guest_user();
398 }
399
400 /// backwards compatibility
401 fill_legacy_user_session($USER);
402
403 //////
404 ////// Load some core libraries
405 //////
406 require_once($CFG->dirroot . "lib/templates.php");
407 require_once($CFG->dirroot . "lib/displaylib.php");
408
409 //////
410 ////// Init templating basics
411 //////
412 if (!isset($CFG->templatestore)) { $CFG->templatestore = 'db' ;}
413 if (!isset($CFG->templatesroot)) { $CFG->templatesroot = $CFG->dirroot . "mod/template/templates/";}
414 if (!isset($PAGE->menu       )) { $PAGE->menu        = array();}
415 if (!isset($PAGE->menu_sub   )) { $PAGE->menu_sub    = array();}
416 if (!isset($PAGE->menu_top   )) { $PAGE->menu_top    = array();}
417 if (!isset($PAGE->menu_bottom)) { $PAGE->menu_bottom = array();}
418
419 //////
420 ////// Define what modules we have, and load their libraries
421 //////
422
423 // TODO : set up a modules table so we can do get_records('modules')
424 //        to fetch the enabled ones (instead of all the available modules)
425 //        we can also track db version with it.
426 if ($allmods = get_list_of_plugins('mod') ) {
427     foreach ($allmods as $mod) {
428         $modfile = $CFG->dirroot . 'mod/'.$mod .'/lib.php';
429         if (file_exists($modfile)) {
430             include_once($modfile);
431         }
432     }
433 }
434 // keep the global scope clean
435 unset($allmods); unset ($mod); unset($modfile);
436
437 /// Apache log integration. In apache conf file one can use ${ELGGUSER}n in
438 /// LogFormat to get the current logged in username in Elgg.
439 /// NOTE: we are grabbing the username -- see the commented out lines
440 /// for alternative things that could be logged...
441 if ($USER && function_exists('apache_note')) {
442     $apachelog_username = clean_filename($USER->username);
443     // $apachelog_name     = clean_filename($USER->firstname. " ".$USER->lastname);
444     // $apachelog_userid   = $USER->ident;
445     /* Enable this commented out section ONLY if Elgg can do
446        user masquerading...
447     if (isset($USER->realuser)) {
448         if ($realuser = get_record('users', 'ident', $USER->realuser)) {
449             $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);           
450             // $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
451             // $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
452         }
453     }
454     */
455     apache_note('ELGGUSER', $apachelog_username);
456 }
457
458 /// Adjust ALLOWED_TAGS
459 adjust_allowed_tags();
460
461 // backwards compatibility (this is what elgg used to use)
462 define("db_server", $CFG->dbhost);
463 define("db_user",$CFG->dbuser);
464 define("db_pass",$CFG->dbpass);
465 define("db_name",$CFG->dbname);
466
467 define("sitename", $CFG->sitename);
468 define("url",$CFG->wwwroot);
469 define("path",$CFG->dirroot);
470 define("email",$CFG->sysadminemail);
471 define("locale", $CFG->defaultlocale);
472 //define("public_reg", $CFG->publicreg);
473 if (empty($CFG->default_access)) {
474     $CFG->default_access = "LOGGED_IN";
475 }
476 define("default_access",$CFG->default_access);
477
478 // figure out a noreply address if we don't have one.
479 if (empty($CFG->noreplyaddress)) {
480     $CFG->noreplyaddress = 'noreply@'.preg_replace('/([a-zA-z]*:\/\/)([a-zA-Z0-9-.]*)([:0-9]*)(\/*.*)/','$2',$CFG->wwwroot);
481 }
482
483
484 /***
485  *** init_performance_info() {
486  ***
487  *** Initializes our performance info early.
488  ***
489  *** Pairs up with get_performance_info() which is actually
490  *** in moodlelib.php. This function is here so that we can
491  *** call it before all the libs are pulled in.
492  ***
493  **/
494 function init_performance_info() {
495
496     global $PERF;
497
498     $PERF = new StdClass;
499     $PERF->dbqueries = 0;   
500     $PERF->logwrites = 0;
501     if (function_exists('microtime')) {
502         $PERF->starttime = microtime();
503     }
504     if (function_exists('memory_get_usage')) {
505         $PERF->startmemory = memory_get_usage();
506     }
507     if (function_exists('posix_times')) {
508         $PERF->startposixtimes = posix_times(); 
509     }
510 }
511
512 /**
513  * Basic error handler
514  */
515 function elgg_error_handler($errno, $errmsg, $errfile, $errline, $errcontext) {
516     global $CFG;
517
518     $date = date('Y-m-d H:i:s');
519     $fatal = "$errmsg (# $errno)";
520     $file = sprintf(__gettext("Error in line %d of file %s"),$errline,$errfile);
521     $script = "Script: {$_SERVER['PHP_SELF']}";
522
523     switch ($errno) {
524         case E_USER_NOTICE:
525         case E_NOTICE:
526             if ($CFG->debug == 2047) {
527                 $msg = sprintf(__gettext("%s\nNotice: %s \n %s\n%s\n"),$date,$fatal,$file,$script);
528                 error_log($msg);
529             }
530             break;
531         case E_USER_WARNING:
532         case E_WARNING:
533         case E_CORE_WARNING:
534         case E_COMPILE_WARNING:
535             //log errors if debug enabled
536             if ($CFG->debug >= 7) {
537                 $msg = "$date\nWarning: $fatal\n$file\n$script\n";
538                 $msg = sprintf(__gettext("%s\nWarning: %s\n%s\%s\n"),$date,$fatal,$file,$script);
539                 error_log($msg);
540             }
541             break;
542         case E_USER_ERROR:
543         case E_ERROR:
544         case E_PARSE:
545         case E_CORE_ERROR:
546         case E_COMPILE_ERROR:
547