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