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