root/releases/0.6rc2/lib/setup.php

Revision 310, 12.6 kB (checked in by carmartin, 3 years ago)

templates: introducing CFG->templatesroot and CFG->templatestore to control on-disk templates

Signed-off-by: Martin Langhoff <martin@catalyst.net.nz>

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