]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - index.php
Merge commit 'refs/merge-requests/165' of git://gitorious.org/statusnet/mainline...
[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
120             $dac = new DBErrorAction($msg, 500);
121             $dac->showPage();
122         } else {
123             $sac = new ServerErrorAction($error->getMessage(), 500, $error);
124             $sac->showPage();
125         }
126
127     } catch (Exception $e) {
128         // TRANS: Error message.
129         echo _('An error occurred.');
130     }
131     exit(-1);
132 }
133
134 set_exception_handler('handleError');
135
136 require_once INSTALLDIR . '/lib/common.php';
137
138 /**
139  * Format a backtrace line for debug output roughly like debug_print_backtrace() does.
140  * Exceptions already have this built in, but PEAR error objects just give us the array.
141  *
142  * @param int $n line number
143  * @param array $line per-frame array item from debug_backtrace()
144  * @return string
145  */
146 function formatBacktraceLine($n, $line)
147 {
148     $out = "#$n ";
149     if (isset($line['class'])) $out .= $line['class'];
150     if (isset($line['type'])) $out .= $line['type'];
151     if (isset($line['function'])) $out .= $line['function'];
152     $out .= '(';
153     if (isset($line['args'])) {
154         $args = array();
155         foreach ($line['args'] as $arg) {
156             // debug_print_backtrace seems to use var_export
157             // but this gets *very* verbose!
158             $args[] = gettype($arg);
159         }
160         $out .= implode(',', $args);
161     }
162     $out .= ')';
163     $out .= ' called at [';
164     if (isset($line['file'])) $out .= $line['file'];
165     if (isset($line['line'])) $out .= ':' . $line['line'];
166     $out .= ']';
167     return $out;
168 }
169
170 function setupRW()
171 {
172     global $config;
173
174     static $alwaysRW = array('session', 'remember_me');
175
176     $rwdb = $config['db']['database'];
177
178     if (Event::handle('StartReadWriteTables', array(&$alwaysRW, &$rwdb))) {
179
180         // We ensure that these tables always are used
181         // on the master DB
182
183         $config['db']['database_rw'] = $rwdb;
184         $config['db']['ini_rw'] = INSTALLDIR.'/classes/statusnet.ini';
185
186         foreach ($alwaysRW as $table) {
187             $config['db']['table_'.$table] = 'rw';
188         }
189
190         Event::handle('EndReadWriteTables', array($alwaysRW, $rwdb));
191     }
192
193     return;
194 }
195
196 function checkMirror($action_obj, $args)
197 {
198     global $config;
199
200     if (common_config('db', 'mirror') && $action_obj->isReadOnly($args)) {
201         if (is_array(common_config('db', 'mirror'))) {
202             // "load balancing", ha ha
203             $arr = common_config('db', 'mirror');
204             $k = array_rand($arr);
205             $mirror = $arr[$k];
206         } else {
207             $mirror = common_config('db', 'mirror');
208         }
209
210         // everyone else uses the mirror
211
212         $config['db']['database'] = $mirror;
213     }
214 }
215
216 function isLoginAction($action)
217 {
218     static $loginActions =  array('login', 'recoverpassword', 'api', 'doc', 'register', 'publicxrds', 'otp', 'opensearch', 'rsd', 'hostmeta');
219
220     $login = null;
221
222     if (Event::handle('LoginAction', array($action, &$login))) {
223         $login = in_array($action, $loginActions);
224     }
225
226     return $login;
227 }
228
229 function main()
230 {
231     // fake HTTP redirects using lighttpd's 404 redirects
232     if (strpos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
233         $_lighty_url = $_SERVER['REQUEST_URI'];
234         $_lighty_url = @parse_url($_lighty_url);
235
236         if ($_lighty_url['path'] != '/index.php' && $_lighty_url['path'] != '/') {
237             $_lighty_path = preg_replace('/^'.preg_quote(common_config('site', 'path')).'\//', '', substr($_lighty_url['path'], 1));
238             $_SERVER['QUERY_STRING'] = 'p='.$_lighty_path;
239             if (isset($_lighty_url['query']) && $_lighty_url['query'] != '') {
240                 $_SERVER['QUERY_STRING'] .= '&'.$_lighty_url['query'];
241                 parse_str($_lighty_url['query'], $_lighty_query);
242                 foreach ($_lighty_query as $key => $val) {
243                     $_GET[$key] = $_REQUEST[$key] = $val;
244                 }
245             }
246             $_GET['p'] = $_REQUEST['p'] = $_lighty_path;
247         }
248     }
249     $_SERVER['REDIRECT_URL'] = preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']);
250
251     // quick check for fancy URL auto-detection support in installer.
252     if (isset($_SERVER['REDIRECT_URL']) && (preg_replace("/^\/$/", "", (dirname($_SERVER['REQUEST_URI']))) . '/check-fancy') === $_SERVER['REDIRECT_URL']) {
253         die("Fancy URL support detection succeeded. We suggest you enable this to get fancy (pretty) URLs.");
254     }
255     global $user, $action;
256
257     Snapshot::check();
258
259     if (!_have_config()) {
260         $msg = sprintf(
261             // TRANS: Error message displayed when there is no StatusNet configuration file.
262             _("No configuration file found. Try running ".
263               "the installation program first."
264             )
265         );
266         $sac = new ServerErrorAction($msg);
267         $sac->showPage();
268         return;
269     }
270
271     // Make sure RW database is setup
272
273     setupRW();
274
275     // XXX: we need a little more structure in this script
276
277     // get and cache current user (may hit RW!)
278
279     $user = common_current_user();
280
281     // initialize language env
282
283     common_init_language();
284
285     $path = getPath($_REQUEST);
286
287     $r = Router::get();
288
289     $args = $r->map($path);
290
291     if (!$args) {
292         // TRANS: Error message displayed when trying to access a non-existing page.
293         $cac = new ClientErrorAction(_('Unknown page'), 404);
294         $cac->showPage();
295         return;
296     }
297
298     $site_ssl = common_config('site', 'ssl');
299
300     // If the request is HTTP and it should be HTTPS...
301     if ($site_ssl != 'never' && !StatusNet::isHTTPS() && common_is_sensitive($args['action'])) {
302         common_redirect(common_local_url($args['action'], $args));
303         return;
304     }
305
306     $args = array_merge($args, $_REQUEST);
307
308     Event::handle('ArgsInitialize', array(&$args));
309
310     $action = $args['action'];
311
312     if (!$action || !preg_match('/^[a-zA-Z0-9_-]*$/', $action)) {
313         common_redirect(common_local_url('public'));
314         return;
315     }
316
317     // If the site is private, and they're not on one of the "public"
318     // parts of the site, redirect to login
319
320     if (!$user && common_config('site', 'private')
321         && !isLoginAction($action)
322         && !preg_match('/rss$/', $action)
323         && $action != 'robotstxt'
324         && !preg_match('/^Api/', $action)) {
325
326         // set returnto
327         $rargs =& common_copy_args($args);
328         unset($rargs['action']);
329         if (common_config('site', 'fancy')) {
330             unset($rargs['p']);
331         }
332         if (array_key_exists('submit', $rargs)) {
333             unset($rargs['submit']);
334         }
335         foreach (array_keys($_COOKIE) as $cookie) {
336             unset($rargs[$cookie]);
337         }
338         common_set_returnto(common_local_url($action, $rargs));
339
340         common_redirect(common_local_url('login'));
341         return;
342     }
343
344     $action_class = ucfirst($action).'Action';
345
346     if (!class_exists($action_class)) {
347         // TRANS: Error message displayed when trying to perform an undefined action.
348         $cac = new ClientErrorAction(_('Unknown action'), 404);
349         $cac->showPage();
350     } else {
351         $action_obj = new $action_class();
352
353         checkMirror($action_obj, $args);
354
355         try {
356             if ($action_obj->prepare($args)) {
357                 $action_obj->handle($args);
358             }
359         } catch (ClientException $cex) {
360             $cac = new ClientErrorAction($cex->getMessage(), $cex->getCode());
361             $cac->showPage();
362         } catch (ServerException $sex) { // snort snort guffaw
363             $sac = new ServerErrorAction($sex->getMessage(), $sex->getCode(), $sex);
364             $sac->showPage();
365         } catch (Exception $ex) {
366             $sac = new ServerErrorAction($ex->getMessage(), 500, $ex);
367             $sac->showPage();
368         }
369     }
370 }
371
372 main();
373
374 // XXX: cleanup exit() calls or add an exit handler so
375 // this always gets called
376
377 Event::handle('CleanupPlugin');