]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - index.php
Merge branch 'fatals' into 0.9.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 require_once INSTALLDIR . '/lib/common.php';
45
46 $user = null;
47 $action = null;
48
49 function getPath($req)
50 {
51     if ((common_config('site', 'fancy') || !array_key_exists('PATH_INFO', $_SERVER))
52         && array_key_exists('p', $req)
53     ) {
54         return $req['p'];
55     } else if (array_key_exists('PATH_INFO', $_SERVER)) {
56         $path = $_SERVER['PATH_INFO'];
57         $script = $_SERVER['SCRIPT_NAME'];
58         if (substr($path, 0, mb_strlen($script)) == $script) {
59             return substr($path, mb_strlen($script));
60         } else {
61             return $path;
62         }
63     } else {
64         return null;
65     }
66 }
67
68 /**
69  * logs and then displays error messages
70  *
71  * @return void
72  */
73 function handleError($error)
74 {
75     if ($error->getCode() == DB_DATAOBJECT_ERROR_NODATA) {
76         return;
77     }
78
79     $logmsg = "PEAR error: " . $error->getMessage();
80     if (common_config('site', 'logdebug')) {
81         $logmsg .= " : ". $error->getDebugInfo();
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->getBacktrace();
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     ) {
98         $msg = sprintf(
99             _(
100                 'The database for %s isn\'t responding correctly, '.
101                 'so the site won\'t work properly. '.
102                 'The site admins probably know about the problem, '.
103                 'but you can contact them at %s to make sure. '.
104                 'Otherwise, wait a few minutes and try again.'
105             ),
106             common_config('site', 'name'),
107             common_config('site', 'email')
108         );
109     } else {
110         $msg = _(
111             'An important error occured, probably related to email setup. '.
112             'Check logfiles for more info..'
113         );
114     }
115
116     $dac = new DBErrorAction($msg, 500);
117     $dac->showPage();
118     exit(-1);
119 }
120
121 /**
122  * Format a backtrace line for debug output roughly like debug_print_backtrace() does.
123  * Exceptions already have this built in, but PEAR error objects just give us the array.
124  *
125  * @param int $n line number
126  * @param array $line per-frame array item from debug_backtrace()
127  * @return string
128  */
129 function formatBacktraceLine($n, $line)
130 {
131     $out = "#$n ";
132     if (isset($line['class'])) $out .= $line['class'];
133     if (isset($line['type'])) $out .= $line['type'];
134     if (isset($line['function'])) $out .= $line['function'];
135     $out .= '(';
136     if (isset($line['args'])) {
137         $args = array();
138         foreach ($line['args'] as $arg) {
139             // debug_print_backtrace seems to use var_export
140             // but this gets *very* verbose!
141             $args[] = gettype($arg);
142         }
143         $out .= implode(',', $args);
144     }
145     $out .= ')';
146     $out .= ' called at [';
147     if (isset($line['file'])) $out .= $line['file'];
148     if (isset($line['line'])) $out .= ':' . $line['line'];
149     $out .= ']';
150     return $out;
151 }
152
153 function setupRW()
154 {
155     global $config;
156
157     static $alwaysRW = array('session', 'remember_me');
158
159     // We ensure that these tables always are used
160     // on the master DB
161
162     $config['db']['database_rw'] = $config['db']['database'];
163     $config['db']['ini_rw'] = INSTALLDIR.'/classes/statusnet.ini';
164
165     foreach ($alwaysRW as $table) {
166         $config['db']['table_'.$table] = 'rw';
167     }
168 }
169
170 function checkMirror($action_obj, $args)
171 {
172     global $config;
173
174     if (common_config('db', 'mirror') && $action_obj->isReadOnly($args)) {
175         if (is_array(common_config('db', 'mirror'))) {
176             // "load balancing", ha ha
177             $arr = common_config('db', 'mirror');
178             $k = array_rand($arr);
179             $mirror = $arr[$k];
180         } else {
181             $mirror = common_config('db', 'mirror');
182         }
183
184         // everyone else uses the mirror
185
186         $config['db']['database'] = $mirror;
187     }
188 }
189
190 function isLoginAction($action)
191 {
192     static $loginActions =  array('login', 'recoverpassword', 'api', 'doc', 'register', 'publicxrds', 'otp', 'opensearch', 'rsd');
193
194     $login = null;
195
196     if (Event::handle('LoginAction', array($action, &$login))) {
197         $login = in_array($action, $loginActions);
198     }
199
200     return $login;
201 }
202
203 function main()
204 {
205     // fake HTTP redirects using lighttpd's 404 redirects
206     if (strpos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
207         $_lighty_url = $base_url.$_SERVER['REQUEST_URI'];
208         $_lighty_url = @parse_url($_lighty_url);
209
210         if ($_lighty_url['path'] != '/index.php' && $_lighty_url['path'] != '/') {
211             $_lighty_path = preg_replace('/^'.preg_quote(common_config('site', 'path')).'\//', '', substr($_lighty_url['path'], 1));
212             $_SERVER['QUERY_STRING'] = 'p='.$_lighty_path;
213             if (isset($_lighty_url['query']) && $_lighty_url['query'] != '') {
214                 $_SERVER['QUERY_STRING'] .= '&'.$_lighty_url['query'];
215                 parse_str($_lighty_url['query'], $_lighty_query);
216                 foreach ($_lighty_query as $key => $val) {
217                     $_GET[$key] = $_REQUEST[$key] = $val;
218                 }
219             }
220             $_GET['p'] = $_REQUEST['p'] = $_lighty_path;
221         }
222     }
223     $_SERVER['REDIRECT_URL'] = preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']);
224
225     // quick check for fancy URL auto-detection support in installer.
226     if (isset($_SERVER['REDIRECT_URL']) && (preg_replace("/^\/$/", "", (dirname($_SERVER['REQUEST_URI']))) . '/check-fancy') === $_SERVER['REDIRECT_URL']) {
227         die("Fancy URL support detection succeeded. We suggest you enable this to get fancy (pretty) URLs.");
228     }
229     global $user, $action;
230
231     Snapshot::check();
232
233     if (!_have_config()) {
234         $msg = sprintf(
235             _(
236                 "No configuration file found. Try running ".
237                 "the installation program first."
238             )
239         );
240         $sac = new ServerErrorAction($msg);
241         $sac->showPage();
242         return;
243     }
244
245     // For database errors
246
247     PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handleError');
248
249     // Make sure RW database is setup
250
251     setupRW();
252
253     // XXX: we need a little more structure in this script
254
255     // get and cache current user (may hit RW!)
256
257     $user = common_current_user();
258
259     // initialize language env
260
261     common_init_language();
262
263     $path = getPath($_REQUEST);
264
265     $r = Router::get();
266
267     $args = $r->map($path);
268
269     if (!$args) {
270         $cac = new ClientErrorAction(_('Unknown page'), 404);
271         $cac->showPage();
272         return;
273     }
274
275     $args = array_merge($args, $_REQUEST);
276
277     Event::handle('ArgsInitialize', array(&$args));
278
279     $action = $args['action'];
280
281     if (!$action || !preg_match('/^[a-zA-Z0-9_-]*$/', $action)) {
282         common_redirect(common_local_url('public'));
283         return;
284     }
285
286     // If the site is private, and they're not on one of the "public"
287     // parts of the site, redirect to login
288
289     if (!$user && common_config('site', 'private')
290         && !isLoginAction($action)
291         && !preg_match('/rss$/', $action)
292         && $action != 'robotstxt'
293         && !preg_match('/^Api/', $action)) {
294
295         // set returnto
296         $rargs =& common_copy_args($args);
297         unset($rargs['action']);
298         if (common_config('site', 'fancy')) {
299             unset($rargs['p']);
300         }
301         if (array_key_exists('submit', $rargs)) {
302             unset($rargs['submit']);
303         }
304         foreach (array_keys($_COOKIE) as $cookie) {
305             unset($rargs[$cookie]);
306         }
307         common_set_returnto(common_local_url($action, $rargs));
308
309         common_redirect(common_local_url('login'));
310         return;
311     }
312
313     $action_class = ucfirst($action).'Action';
314
315     if (!class_exists($action_class)) {
316         $cac = new ClientErrorAction(_('Unknown action'), 404);
317         $cac->showPage();
318     } else {
319         $action_obj = new $action_class();
320
321         checkMirror($action_obj, $args);
322
323         try {
324             if ($action_obj->prepare($args)) {
325                 $action_obj->handle($args);
326             }
327         } catch (ClientException $cex) {
328             $cac = new ClientErrorAction($cex->getMessage(), $cex->getCode());
329             $cac->showPage();
330         } catch (ServerException $sex) { // snort snort guffaw
331             $sac = new ServerErrorAction($sex->getMessage(), $sex->getCode(), $sex);
332             $sac->showPage();
333         } catch (Exception $ex) {
334             $sac = new ServerErrorAction($ex->getMessage(), 500, $ex);
335             $sac->showPage();
336         }
337     }
338 }
339
340 main();
341
342 // XXX: cleanup exit() calls or add an exit handler so
343 // this always gets called
344
345 Event::handle('CleanupPlugin');