]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - index.php
Merge remote branch 'gitorious/1.0.x' into 1.0.x
[quix0rs-gnu-social.git] / index.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  * @category StatusNet
20  * @package  StatusNet
21  * @author   Brenda Wallace <shiny@cpan.org>
22  * @author   Brion Vibber <brion@pobox.com>
23  * @author   Christopher Vollick <psycotica0@gmail.com>
24  * @author   CiaranG <ciaran@ciarang.com>
25  * @author   Craig Andrews <candrews@integralblue.com>
26  * @author   Evan Prodromou <evan@controlezvous.ca>
27  * @author   Gina Haeussge <osd@foosel.net>
28  * @author   James Walker <walkah@walkah.net>
29  * @author   Jeffery To <jeffery.to@gmail.com>
30  * @author   Mike Cochrane <mikec@mikenz.geek.nz>
31  * @author   Robin Millette <millette@controlyourself.ca>
32  * @author   Sarven Capadisli <csarven@controlyourself.ca>
33  * @author   Tom Adams <tom@holizz.com>
34  * @author   Zach Copley <zach@status.net>
35  * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
36  *
37  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
38  */
39
40 define('INSTALLDIR', dirname(__FILE__));
41 define('STATUSNET', true);
42 define('LACONICA', true); // compatibility
43
44 $user = null;
45 $action = null;
46
47 function getPath($req)
48 {
49     if ((common_config('site', 'fancy') || !array_key_exists('PATH_INFO', $_SERVER))
50         && array_key_exists('p', $req)
51     ) {
52         return $req['p'];
53     } else if (array_key_exists('PATH_INFO', $_SERVER)) {
54         $path = $_SERVER['PATH_INFO'];
55         $script = $_SERVER['SCRIPT_NAME'];
56         if (substr($path, 0, mb_strlen($script)) == $script) {
57             return substr($path, mb_strlen($script));
58         } else {
59             return $path;
60         }
61     } else {
62         return null;
63     }
64 }
65
66 /**
67  * logs and then displays error messages
68  *
69  * @return void
70  */
71 function handleError($error)
72 {
73     try {
74
75         if ($error->getCode() == DB_DATAOBJECT_ERROR_NODATA) {
76             return;
77         }
78
79         $logmsg = "PEAR error: " . $error->getMessage();
80         if ($error instanceof PEAR_Exception && common_config('site', 'logdebug')) {
81             $logmsg .= " : ". $error->toText();
82         }
83         // DB queries often end up with a lot of newlines; merge to a single line
84         // for easier grepability...
85         $logmsg = str_replace("\n", " ", $logmsg);
86         common_log(LOG_ERR, $logmsg);
87
88         // @fixme backtrace output should be consistent with exception handling
89         if (common_config('site', 'logdebug')) {
90             $bt = $error->getTrace();
91             foreach ($bt as $n => $line) {
92                 common_log(LOG_ERR, formatBacktraceLine($n, $line));
93             }
94         }
95         if ($error instanceof DB_DataObject_Error
96             || $error instanceof DB_Error
97             || ($error instanceof PEAR_Exception && $error->getCode() == -24)
98         ) {
99             //If we run into a DB error, assume we can't connect to the DB at all
100             //so set the current user to null, so we don't try to access the DB
101             //while rendering the error page.
102             global $_cur;
103             $_cur = null;
104
105             $msg = sprintf(
106                 _(
107                     'The database for %s isn\'t responding correctly, '.
108                     'so the site won\'t work properly. '.
109                     'The site admins probably know about the problem, '.
110                     'but you can contact them at %s to make sure. '.
111                     'Otherwise, wait a few minutes and try again.'
112                 ),
113                 common_config('site', 'name'),
114                 common_config('site', 'email')
115             );
116         } else {
117             $msg = _(
118                 'An important error occured, probably related to email setup. '.
119                 'Check logfiles for more info..'
120             );
121         }
122
123         $dac = new DBErrorAction($msg, 500);
124         $dac->showPage();
125
126     } catch (Exception $e) {
127         echo _('An error occurred.');
128     }
129     exit(-1);
130 }
131
132 set_exception_handler('handleError');
133
134 require_once INSTALLDIR . '/lib/common.php';
135
136 /**
137  * Format a backtrace line for debug output roughly like debug_print_backtrace() does.
138  * Exceptions already have this built in, but PEAR error objects just give us the array.
139  *
140  * @param int $n line number
141  * @param array $line per-frame array item from debug_backtrace()
142  * @return string
143  */
144 function formatBacktraceLine($n, $line)
145 {
146     $out = "#$n ";
147     if (isset($line['class'])) $out .= $line['class'];
148     if (isset($line['type'])) $out .= $line['type'];
149     if (isset($line['function'])) $out .= $line['function'];
150     $out .= '(';
151     if (isset($line['args'])) {
152         $args = array();
153         foreach ($line['args'] as $arg) {
154             // debug_print_backtrace seems to use var_export
155             // but this gets *very* verbose!
156             $args[] = gettype($arg);
157         }
158         $out .= implode(',', $args);
159     }
160     $out .= ')';
161     $out .= ' called at [';
162     if (isset($line['file'])) $out .= $line['file'];
163     if (isset($line['line'])) $out .= ':' . $line['line'];
164     $out .= ']';
165     return $out;
166 }
167
168 function setupRW()
169 {
170     global $config;
171
172     static $alwaysRW = array('session', 'remember_me');
173
174     // We ensure that these tables always are used
175     // on the master DB
176
177     $config['db']['database_rw'] = $config['db']['database'];
178     $config['db']['ini_rw'] = INSTALLDIR.'/classes/statusnet.ini';
179
180     foreach ($alwaysRW as $table) {
181         $config['db']['table_'.$table] = 'rw';
182     }
183 }
184
185 function checkMirror($action_obj, $args)
186 {
187     global $config;
188
189     if (common_config('db', 'mirror') && $action_obj->isReadOnly($args)) {
190         if (is_array(common_config('db', 'mirror'))) {
191             // "load balancing", ha ha
192             $arr = common_config('db', 'mirror');
193             $k = array_rand($arr);
194             $mirror = $arr[$k];
195         } else {
196             $mirror = common_config('db', 'mirror');
197         }
198
199         // everyone else uses the mirror
200
201         $config['db']['database'] = $mirror;
202     }
203 }
204
205 function isLoginAction($action)
206 {
207     static $loginActions =  array('login', 'recoverpassword', 'api', 'doc', 'register', 'publicxrds', 'otp', 'opensearch', 'rsd', 'hostmeta');
208
209     $login = null;
210
211     if (Event::handle('LoginAction', array($action, &$login))) {
212         $login = in_array($action, $loginActions);
213     }
214
215     return $login;
216 }
217
218 function main()
219 {
220     // fake HTTP redirects using lighttpd's 404 redirects
221     if (strpos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
222         $_lighty_url = $base_url.$_SERVER['REQUEST_URI'];
223         $_lighty_url = @parse_url($_lighty_url);
224
225         if ($_lighty_url['path'] != '/index.php' && $_lighty_url['path'] != '/') {
226             $_lighty_path = preg_replace('/^'.preg_quote(common_config('site', 'path')).'\//', '', substr($_lighty_url['path'], 1));
227             $_SERVER['QUERY_STRING'] = 'p='.$_lighty_path;
228             if (isset($_lighty_url['query']) && $_lighty_url['query'] != '') {
229                 $_SERVER['QUERY_STRING'] .= '&'.$_lighty_url['query'];
230                 parse_str($_lighty_url['query'], $_lighty_query);
231                 foreach ($_lighty_query as $key => $val) {
232                     $_GET[$key] = $_REQUEST[$key] = $val;
233                 }
234             }
235             $_GET['p'] = $_REQUEST['p'] = $_lighty_path;
236         }
237     }
238     $_SERVER['REDIRECT_URL'] = preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']);
239
240     // quick check for fancy URL auto-detection support in installer.
241     if (isset($_SERVER['REDIRECT_URL']) && (preg_replace("/^\/$/", "", (dirname($_SERVER['REQUEST_URI']))) . '/check-fancy') === $_SERVER['REDIRECT_URL']) {
242         die("Fancy URL support detection succeeded. We suggest you enable this to get fancy (pretty) URLs.");
243     }
244     global $user, $action;
245
246     Snapshot::check();
247
248     if (!_have_config()) {
249         $msg = sprintf(
250             _(
251                 "No configuration file found. Try running ".
252                 "the installation program first."
253             )
254         );
255         $sac = new ServerErrorAction($msg);
256         $sac->showPage();
257         return;
258     }
259
260     // Make sure RW database is setup
261
262     setupRW();
263
264     // XXX: we need a little more structure in this script
265
266     // get and cache current user (may hit RW!)
267
268     $user = common_current_user();
269
270     // initialize language env
271
272     common_init_language();
273
274     $path = getPath($_REQUEST);
275
276     $r = Router::get();
277
278     $args = $r->map($path);
279
280     if (!$args) {
281         $cac = new ClientErrorAction(_('Unknown page'), 404);
282         $cac->showPage();
283         return;
284     }
285
286     $site_ssl = common_config('site', 'ssl');
287
288     // If the request is HTTP and it should be HTTPS...
289     if ($site_ssl != 'never' && !StatusNet::isHTTPS() && common_is_sensitive($args['action'])) {
290         common_redirect(common_local_url($args['action'], $args));
291         return;
292     }
293
294     $args = array_merge($args, $_REQUEST);
295
296     Event::handle('ArgsInitialize', array(&$args));
297
298     $action = $args['action'];
299
300     if (!$action || !preg_match('/^[a-zA-Z0-9_-]*$/', $action)) {
301         common_redirect(common_local_url('public'));
302         return;
303     }
304
305     // If the site is private, and they're not on one of the "public"
306     // parts of the site, redirect to login
307
308     if (!$user && common_config('site', 'private')
309         && !isLoginAction($action)
310         && !preg_match('/rss$/', $action)
311         && $action != 'robotstxt'
312         && !preg_match('/^Api/', $action)) {
313
314         // set returnto
315         $rargs =& common_copy_args($args);
316         unset($rargs['action']);
317         if (common_config('site', 'fancy')) {
318             unset($rargs['p']);
319         }
320         if (array_key_exists('submit', $rargs)) {
321             unset($rargs['submit']);
322         }
323         foreach (array_keys($_COOKIE) as $cookie) {
324             unset($rargs[$cookie]);
325         }
326         common_set_returnto(common_local_url($action, $rargs));
327
328         common_redirect(common_local_url('login'));
329         return;
330     }
331
332     $action_class = ucfirst($action).'Action';
333
334     if (!class_exists($action_class)) {
335         $cac = new ClientErrorAction(_('Unknown action'), 404);
336         $cac->showPage();
337     } else {
338         $action_obj = new $action_class();
339
340         checkMirror($action_obj, $args);
341
342         try {
343             if ($action_obj->prepare($args)) {
344                 $action_obj->handle($args);
345             }
346         } catch (ClientException $cex) {
347             $cac = new ClientErrorAction($cex->getMessage(), $cex->getCode());
348             $cac->showPage();
349         } catch (ServerException $sex) { // snort snort guffaw
350             $sac = new ServerErrorAction($sex->getMessage(), $sex->getCode(), $sex);
351             $sac->showPage();
352         } catch (Exception $ex) {
353             $sac = new ServerErrorAction($ex->getMessage(), 500, $ex);
354             $sac->showPage();
355         }
356     }
357 }
358
359 main();
360
361 // XXX: cleanup exit() calls or add an exit handler so
362 // this always gets called
363
364 Event::handle('CleanupPlugin');