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
require_once INSTALLDIR . '/lib/common.php';
48
49
register_shutdown_function('common_log_perf_counters');
50
51
$user = null;
52
$action = null;
53
54
function getPath($req)
55
{
56
    if ((common_config('site', 'fancy') || !array_key_exists('PATH_INFO', $_SERVER))
57
        && array_key_exists('p', $req)
58
    ) {
59
        return $req['p'];
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));
65
        } else {
66
            return $path;
67
        }
68
    } else {
69
        return null;
70
    }
71
}
72
73
/**
74
 * logs and then displays error messages
75
 *
76
 * @return void
77
 */
78
function handleError($error)
79
{
80
    if ($error->getCode() == DB_DATAOBJECT_ERROR_NODATA) {
81
        return;
82
    }
83
84
    $logmsg = "PEAR error: " . $error->getMessage();
85
    if (common_config('site', 'logdebug')) {
86
        $logmsg .= " : ". $error->getDebugInfo();
87
    }
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);
92
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));
98
        }
99
    }
100
    if ($error instanceof DB_DataObject_Error
101
        || $error instanceof DB_Error
102
    ) {
103
        $msg = sprintf(
104
            _(
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.'
110
            ),
111
            common_config('site', 'name'),
112
            common_config('site', 'email')
113
        );
114
    } else {
115
        $msg = _(
116
            'An important error occured, probably related to email setup. '.
117
            'Check logfiles for more info..'
118
        );
119
    }
120
121
    $dac = new DBErrorAction($msg, 500);
122
    $dac->showPage();
123
    exit(-1);
124
}
125
126
/**
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.
129
 *
130
 * @param int $n line number
131
 * @param array $line per-frame array item from debug_backtrace()
132
 * @return string
133
 */
134
function formatBacktraceLine($n, $line)
135
{
136
    $out = "#$n ";
137
    if (isset($line['class'])) $out .= $line['class'];
138
    if (isset($line['type'])) $out .= $line['type'];
139
    if (isset($line['function'])) $out .= $line['function'];
140
    $out .= '(';
141
    if (isset($line['args'])) {
142
        $args = array();
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);
147
        }
148
        $out .= implode(',', $args);
149
    }
150
    $out .= ')';
151
    $out .= ' called at [';
152
    if (isset($line['file'])) $out .= $line['file'];
153
    if (isset($line['line'])) $out .= ':' . $line['line'];
154
    $out .= ']';
155
    return $out;
156
}
157
158
function setupRW()
159
{
160
    global $config;
161
162
    static $alwaysRW = array('session', 'remember_me');
163
164
    // We ensure that these tables always are used
165
    // on the master DB
166
167
    $config['db']['database_rw'] = $config['db']['database'];
168
    $config['db']['ini_rw'] = INSTALLDIR.'/classes/statusnet.ini';
169
170
    foreach ($alwaysRW as $table) {
171
        $config['db']['table_'.$table] = 'rw';
172
    }
173
}
174
175
function checkMirror($action_obj, $args)
176
{
177
    global $config;
178
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);
184
            $mirror = $arr[$k];
185
        } else {
186
            $mirror = common_config('db', 'mirror');
187
        }
188
189
        // everyone else uses the mirror
190
191
        $config['db']['database'] = $mirror;
192
    }
193
}
194
195
function isLoginAction($action)
196
{
197
    static $loginActions =  array('login', 'recoverpassword', 'api', 'doc', 'register', 'publicxrds', 'otp', 'opensearch', 'rsd', 'hostmeta');
198
199
    $login = null;
200
201
    if (Event::handle('LoginAction', array($action, &$login))) {
202
        $login = in_array($action, $loginActions);
203
    }
204
205
    return $login;
206
}
207
208
function main()
209
{
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);
214
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;
223
                }
224
            }
225
            $_GET['p'] = $_REQUEST['p'] = $_lighty_path;
226
        }
227
    }
228
    $_SERVER['REDIRECT_URL'] = preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']);
229
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.");
233
    }
234
    global $user, $action;
235
236
    Snapshot::check();
237
238
    if (!_have_config()) {
239
        $msg = sprintf(
240
            _(
241
                "No configuration file found. Try running ".
242
                "the installation program first."
243
            )
244
        );
245
        $sac = new ServerErrorAction($msg);
246
        $sac->showPage();
247
        return;
248
    }
249
250
    // For database errors
251
252
    PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handleError');
253
254
    // Make sure RW database is setup
255
256
    setupRW();
257
258
    // XXX: we need a little more structure in this script
259
260
    // get and cache current user (may hit RW!)
261
262
    $user = common_current_user();
263
264
    // initialize language env
265
266
    common_init_language();
267
268
    $path = getPath($_REQUEST);
269
270
    $r = Router::get();
271
272
    $args = $r->map($path);
273
274
    if (!$args) {
275
        $cac = new ClientErrorAction(_('Unknown page'), 404);
276
        $cac->showPage();
277
        return;
278
    }
279
280
    $args = array_merge($args, $_REQUEST);
281
282
    Event::handle('ArgsInitialize', array(&$args));
283
284
    $action = $args['action'];
285
286
    if (!$action || !preg_match('/^[a-zA-Z0-9_-]*$/', $action)) {
287
        common_redirect(common_local_url('public'));
288
        return;
289
    }
290
291
    // If the site is private, and they're not on one of the "public"
292
    // parts of the site, redirect to login
293
294
    if (!$user && common_config('site', 'private')
295
        && !isLoginAction($action)
296
        && !preg_match('/rss$/', $action)
297
        && $action != 'robotstxt'
298
        && !preg_match('/^Api/', $action)) {
299
300
        // set returnto
301
        $rargs =& common_copy_args($args);
302
        unset($rargs['action']);
303
        if (common_config('site', 'fancy')) {
304
            unset($rargs['p']);
305
        }
306
        if (array_key_exists('submit', $rargs)) {
307
            unset($rargs['submit']);
308
        }
309
        foreach (array_keys($_COOKIE) as $cookie) {
310
            unset($rargs[$cookie]);
311
        }
312
        common_set_returnto(common_local_url($action, $rargs));
313
314
        common_redirect(common_local_url('login'));
315
        return;
316
    }
317
318
    $action_class = ucfirst($action).'Action';
319
320
    if (!class_exists($action_class)) {
321
        $cac = new ClientErrorAction(_('Unknown action'), 404);
322
        $cac->showPage();
323
    } else {
324
        $action_obj = new $action_class();
325
326
        checkMirror($action_obj, $args);
327
328
        try {
329
            if ($action_obj->prepare($args)) {
330
                $action_obj->handle($args);
331
            }
332
        } catch (ClientException $cex) {
333
            $cac = new ClientErrorAction($cex->getMessage(), $cex->getCode());
334
            $cac->showPage();
335
        } catch (ServerException $sex) { // snort snort guffaw
336
            $sac = new ServerErrorAction($sex->getMessage(), $sex->getCode(), $sex);
337
            $sac->showPage();
338
        } catch (Exception $ex) {
339
            $sac = new ServerErrorAction($ex->getMessage(), 500, $ex);
340
            $sac->showPage();
341
        }
342
    }
343
}
344
345
main();
346
347
// XXX: cleanup exit() calls or add an exit handler so
348
// this always gets called
349
350
Event::handle('CleanupPlugin');