root/releases/0.672/lib/setup.php

Revision 742, 14.9 kB (checked in by sven, 2 years ago)

very rudimentary memcached experiment

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