3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
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.
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.
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/>.
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
37 * @license GNU Affero General Public License http://www.gnu.org/licenses/
40 $_startTime = microtime(true);
41 $_perfCounters = array();
43 define('INSTALLDIR', dirname(__FILE__));
44 define('GNUSOCIAL', true);
45 define('STATUSNET', true); // compatibility
50 function getPath($req)
54 if ((common_config('site', 'fancy') || !array_key_exists('PATH_INFO', $_SERVER))
55 && array_key_exists('p', $req)
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);
70 // Trim all initial '/'
78 * logs and then displays error messages
82 function handleError($error)
86 if ($error->getCode() == DB_DATAOBJECT_ERROR_NODATA) {
90 $logmsg = "PEAR error: " . $error->getMessage();
91 if ($error instanceof PEAR_Exception && common_config('site', 'logdebug')) {
92 $logmsg .= " : ". $error->toText();
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);
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));
106 if ($error instanceof DB_DataObject_Error
107 || $error instanceof DB_Error
108 || ($error instanceof PEAR_Exception && $error->getCode() == -24)
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.
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.'
124 common_config('site', 'name'),
125 common_config('site', 'email')
128 $dac = new DBErrorAction($msg, 500);
131 $sac = new ServerErrorAction($error->getMessage(), 500, $error);
135 } catch (Exception $e) {
136 // TRANS: Error message.
137 echo _('An error occurred.');
142 set_exception_handler('handleError');
144 require_once INSTALLDIR . '/lib/common.php';
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.
150 * @param int $n line number
151 * @param array $line per-frame array item from debug_backtrace()
154 function formatBacktraceLine($n, $line)
157 if (isset($line['class'])) $out .= $line['class'];
158 if (isset($line['type'])) $out .= $line['type'];
159 if (isset($line['function'])) $out .= $line['function'];
161 if (isset($line['args'])) {
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);
168 $out .= implode(',', $args);
171 $out .= ' called at [';
172 if (isset($line['file'])) $out .= $line['file'];
173 if (isset($line['line'])) $out .= ':' . $line['line'];
182 static $alwaysRW = array('session', 'remember_me');
184 $rwdb = $config['db']['database'];
186 if (Event::handle('StartReadWriteTables', array(&$alwaysRW, &$rwdb))) {
188 // We ensure that these tables always are used
191 $config['db']['database_rw'] = $rwdb;
192 $config['db']['ini_rw'] = INSTALLDIR.'/classes/statusnet.ini';
194 foreach ($alwaysRW as $table) {
195 $config['db']['table_'.$table] = 'rw';
198 Event::handle('EndReadWriteTables', array($alwaysRW, $rwdb));
204 function isLoginAction($action)
206 static $loginActions = array('login', 'recoverpassword', 'api', 'doc', 'register', 'publicxrds', 'otp', 'opensearch', 'rsd');
210 if (Event::handle('LoginAction', array($action, &$login))) {
211 $login = in_array($action, $loginActions);
219 // fake HTTP redirects using lighttpd's 404 redirects
220 if (strpos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
221 $_lighty_url = $_SERVER['REQUEST_URI'];
222 $_lighty_url = @parse_url($_lighty_url);
224 if ($_lighty_url['path'] != '/index.php' && $_lighty_url['path'] != '/') {
225 $_lighty_path = preg_replace('/^'.preg_quote(common_config('site', 'path')).'\//', '', substr($_lighty_url['path'], 1));
226 $_SERVER['QUERY_STRING'] = 'p='.$_lighty_path;
227 if (isset($_lighty_url['query']) && $_lighty_url['query'] != '') {
228 $_SERVER['QUERY_STRING'] .= '&'.$_lighty_url['query'];
229 parse_str($_lighty_url['query'], $_lighty_query);
230 foreach ($_lighty_query as $key => $val) {
231 $_GET[$key] = $_REQUEST[$key] = $val;
234 $_GET['p'] = $_REQUEST['p'] = $_lighty_path;
237 $_SERVER['REDIRECT_URL'] = preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']);
239 // quick check for fancy URL auto-detection support in installer.
240 if (isset($_SERVER['REDIRECT_URL']) && (preg_replace("/^\/$/", "", (dirname($_SERVER['REQUEST_URI']))) . '/check-fancy') === $_SERVER['REDIRECT_URL']) {
241 die("Fancy URL support detection succeeded. We suggest you enable this to get fancy (pretty) URLs.");
243 global $user, $action;
245 if (!_have_config()) {
247 // TRANS: Error message displayed when there is no StatusNet configuration file.
248 _("No configuration file found. Try running ".
249 "the installation program first."
252 $sac = new ServerErrorAction($msg);
257 // Make sure RW database is setup
261 // XXX: we need a little more structure in this script
263 // get and cache current user (may hit RW!)
265 $user = common_current_user();
267 // initialize language env
269 common_init_language();
271 $path = getPath($_REQUEST);
275 $args = $r->map($path);
278 // TRANS: Error message displayed when trying to access a non-existing page.
279 $cac = new ClientErrorAction(_('Unknown page'), 404);
284 $site_ssl = common_config('site', 'ssl');
286 // If the request is HTTP and it should be HTTPS...
287 if ($site_ssl != 'never' && !StatusNet::isHTTPS() && common_is_sensitive($args['action'])) {
288 common_redirect(common_local_url($args['action'], $args));
291 $args = array_merge($args, $_REQUEST);
293 Event::handle('ArgsInitialize', array(&$args));
295 $action = basename($args['action']);
297 if (!$action || !preg_match('/^[a-zA-Z0-9_-]*$/', $action)) {
298 common_redirect(common_local_url('public'));
301 // If the site is private, and they're not on one of the "public"
302 // parts of the site, redirect to login
304 if (!$user && common_config('site', 'private')
305 && !isLoginAction($action)
306 && !preg_match('/rss$/', $action)
307 && $action != 'robotstxt'
308 && !preg_match('/^Api/', $action)) {
311 $rargs =& common_copy_args($args);
312 unset($rargs['action']);
313 if (common_config('site', 'fancy')) {
316 if (array_key_exists('submit', $rargs)) {
317 unset($rargs['submit']);
319 foreach (array_keys($_COOKIE) as $cookie) {
320 unset($rargs[$cookie]);
322 common_set_returnto(common_local_url($action, $rargs));
324 common_redirect(common_local_url('login'));
327 $action_class = ucfirst($action).'Action';
329 if (!class_exists($action_class)) {
330 // TRANS: Error message displayed when trying to perform an undefined action.
331 $cac = new ClientErrorAction(_('Unknown action'), 404);
335 call_user_func("$action_class::run", $args);
336 } catch (ClientException $cex) {
337 $cac = new ClientErrorAction($cex->getMessage(), $cex->getCode());
339 } catch (ServerException $sex) { // snort snort guffaw
340 $sac = new ServerErrorAction($sex->getMessage(), $sex->getCode(), $sex);
342 } catch (Exception $ex) {
343 $sac = new ServerErrorAction($ex->getMessage(), 500, $ex);
351 // XXX: cleanup exit() calls or add an exit handler so
352 // this always gets called
354 Event::handle('CleanupPlugin');