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