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('STATUSNET', true);
45 define('LACONICA', true); // compatibility
47 require_once INSTALLDIR . '/lib/common.php';
49 register_shutdown_function('common_log_perf_counters');
54 function getPath($req)
56 if ((common_config('site', 'fancy') || !array_key_exists('PATH_INFO', $_SERVER))
57 && array_key_exists('p', $req)
60 } else if (array_key_exists('PATH_INFO', $_SERVER)) {
61 $path = $_SERVER['PATH_INFO'];
62 $script = $_SERVER['SCRIPT_NAME'];
63 if (substr($path, 0, mb_strlen($script)) == $script) {
64 return substr($path, mb_strlen($script));
74 * logs and then displays error messages
78 function handleError($error)
80 if ($error->getCode() == DB_DATAOBJECT_ERROR_NODATA) {
84 $logmsg = "PEAR error: " . $error->getMessage();
85 if (common_config('site', 'logdebug')) {
86 $logmsg .= " : ". $error->getDebugInfo();
88 // DB queries often end up with a lot of newlines; merge to a single line
89 // for easier grepability...
90 $logmsg = str_replace("\n", " ", $logmsg);
91 common_log(LOG_ERR, $logmsg);
93 // @fixme backtrace output should be consistent with exception handling
94 if (common_config('site', 'logdebug')) {
95 $bt = $error->getBacktrace();
96 foreach ($bt as $n => $line) {
97 common_log(LOG_ERR, formatBacktraceLine($n, $line));
100 if ($error instanceof DB_DataObject_Error
101 || $error instanceof DB_Error
105 'The database for %s isn\'t responding correctly, '.
106 'so the site won\'t work properly. '.
107 'The site admins probably know about the problem, '.
108 'but you can contact them at %s to make sure. '.
109 'Otherwise, wait a few minutes and try again.'
111 common_config('site', 'name'),
112 common_config('site', 'email')
116 'An important error occured, probably related to email setup. '.
117 'Check logfiles for more info..'
121 $dac = new DBErrorAction($msg, 500);
127 * Format a backtrace line for debug output roughly like debug_print_backtrace() does.
128 * Exceptions already have this built in, but PEAR error objects just give us the array.
130 * @param int $n line number
131 * @param array $line per-frame array item from debug_backtrace()
134 function formatBacktraceLine($n, $line)
137 if (isset($line['class'])) $out .= $line['class'];
138 if (isset($line['type'])) $out .= $line['type'];
139 if (isset($line['function'])) $out .= $line['function'];
141 if (isset($line['args'])) {
143 foreach ($line['args'] as $arg) {
144 // debug_print_backtrace seems to use var_export
145 // but this gets *very* verbose!
146 $args[] = gettype($arg);
148 $out .= implode(',', $args);
151 $out .= ' called at [';
152 if (isset($line['file'])) $out .= $line['file'];
153 if (isset($line['line'])) $out .= ':' . $line['line'];
162 static $alwaysRW = array('session', 'remember_me');
164 // We ensure that these tables always are used
167 $config['db']['database_rw'] = $config['db']['database'];
168 $config['db']['ini_rw'] = INSTALLDIR.'/classes/statusnet.ini';
170 foreach ($alwaysRW as $table) {
171 $config['db']['table_'.$table] = 'rw';
175 function checkMirror($action_obj, $args)
179 if (common_config('db', 'mirror') && $action_obj->isReadOnly($args)) {
180 if (is_array(common_config('db', 'mirror'))) {
181 // "load balancing", ha ha
182 $arr = common_config('db', 'mirror');
183 $k = array_rand($arr);
186 $mirror = common_config('db', 'mirror');
189 // everyone else uses the mirror
191 $config['db']['database'] = $mirror;
195 function isLoginAction($action)
197 static $loginActions = array('login', 'recoverpassword', 'api', 'doc', 'register', 'publicxrds', 'otp', 'opensearch', 'rsd', 'hostmeta');
201 if (Event::handle('LoginAction', array($action, &$login))) {
202 $login = in_array($action, $loginActions);
210 // fake HTTP redirects using lighttpd's 404 redirects
211 if (strpos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
212 $_lighty_url = $_SERVER['REQUEST_URI'];
213 $_lighty_url = @parse_url($_lighty_url);
215 if ($_lighty_url['path'] != '/index.php' && $_lighty_url['path'] != '/') {
216 $_lighty_path = preg_replace('/^'.preg_quote(common_config('site', 'path')).'\//', '', substr($_lighty_url['path'], 1));
217 $_SERVER['QUERY_STRING'] = 'p='.$_lighty_path;
218 if (isset($_lighty_url['query']) && $_lighty_url['query'] != '') {
219 $_SERVER['QUERY_STRING'] .= '&'.$_lighty_url['query'];
220 parse_str($_lighty_url['query'], $_lighty_query);
221 foreach ($_lighty_query as $key => $val) {
222 $_GET[$key] = $_REQUEST[$key] = $val;
225 $_GET['p'] = $_REQUEST['p'] = $_lighty_path;
228 $_SERVER['REDIRECT_URL'] = preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']);
230 // quick check for fancy URL auto-detection support in installer.
231 if (isset($_SERVER['REDIRECT_URL']) && (preg_replace("/^\/$/", "", (dirname($_SERVER['REQUEST_URI']))) . '/check-fancy') === $_SERVER['REDIRECT_URL']) {
232 die("Fancy URL support detection succeeded. We suggest you enable this to get fancy (pretty) URLs.");
234 global $user, $action;
238 if (!_have_config()) {
241 "No configuration file found. Try running ".
242 "the installation program first."
245 $sac = new ServerErrorAction($msg);
250 // For database errors
252 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handleError');
254 // Make sure RW database is setup
258 // XXX: we need a little more structure in this script
260 // get and cache current user (may hit RW!)
262 $user = common_current_user();
264 // initialize language env
266 common_init_language();
268 $path = getPath($_REQUEST);
272 $args = $r->map($path);
275 $cac = new ClientErrorAction(_('Unknown page'), 404);
280 $args = array_merge($args, $_REQUEST);
282 Event::handle('ArgsInitialize', array(&$args));
284 $action = $args['action'];
286 if (!$action || !preg_match('/^[a-zA-Z0-9_-]*$/', $action)) {
287 common_redirect(common_local_url('public'));
291 // If the site is private, and they're not on one of the "public"
292 // parts of the site, redirect to login
294 if (!$user && common_config('site', 'private')
295 && !isLoginAction($action)
296 && !preg_match('/rss$/', $action)
297 && $action != 'robotstxt'
298 && !preg_match('/^Api/', $action)) {
301 $rargs =& common_copy_args($args);
302 unset($rargs['action']);
303 if (common_config('site', 'fancy')) {
306 if (array_key_exists('submit', $rargs)) {
307 unset($rargs['submit']);
309 foreach (array_keys($_COOKIE) as $cookie) {
310 unset($rargs[$cookie]);
312 common_set_returnto(common_local_url($action, $rargs));
314 common_redirect(common_local_url('login'));
318 $action_class = ucfirst($action).'Action';
320 if (!class_exists($action_class)) {
321 $cac = new ClientErrorAction(_('Unknown action'), 404);
324 $action_obj = new $action_class();
326 checkMirror($action_obj, $args);
329 if ($action_obj->prepare($args)) {
330 $action_obj->handle($args);
332 } catch (ClientException $cex) {
333 $cac = new ClientErrorAction($cex->getMessage(), $cex->getCode());
335 } catch (ServerException $sex) { // snort snort guffaw
336 $sac = new ServerErrorAction($sex->getMessage(), $sex->getCode(), $sex);
338 } catch (Exception $ex) {
339 $sac = new ServerErrorAction($ex->getMessage(), 500, $ex);
347 // XXX: cleanup exit() calls or add an exit handler so
348 // this always gets called
350 Event::handle('CleanupPlugin');