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
20
define('INSTALLDIR', dirname(__FILE__));
21
define('STATUSNET', true);
22
define('LACONICA', true); // compatibility
23
24
require_once INSTALLDIR . '/lib/common.php';
25
26
$user = null;
27
$action = null;
28
29
function getPath($req)
30
{
31
    if ((common_config('site', 'fancy') || !array_key_exists('PATH_INFO', $_SERVER))
32
        && array_key_exists('p', $req)) {
33
        return $req['p'];
34
    } else if (array_key_exists('PATH_INFO', $_SERVER)) {
35
        return $_SERVER['PATH_INFO'];
36
    } else {
37
        return null;
38
    }
39
}
40
41
function handleError($error)
42
{
43
    if ($error->getCode() == DB_DATAOBJECT_ERROR_NODATA) {
44
        return;
45
    }
46
47
    $logmsg = "PEAR error: " . $error->getMessage();
48
    if(common_config('site', 'logdebug')) {
49
        $logmsg .= " : ". $error->getDebugInfo();
50
    }
51
    common_log(LOG_ERR, $logmsg);
52
    if(common_config('site', 'logdebug')) {
53
        $bt = $error->getBacktrace();
54
        foreach ($bt as $line) {
55
            common_log(LOG_ERR, $line);
56
        }
57
    }
58
    if ($error instanceof DB_DataObject_Error ||
59
        $error instanceof DB_Error) {
60
        $msg = sprintf(_('The database for %s isn\'t responding correctly, '.
61
                         'so the site won\'t work properly. '.
62
                         'The site admins probably know about the problem, '.
63
                         'but you can contact them at %s to make sure. '.
64
                         'Otherwise, wait a few minutes and try again.'),
65
                       common_config('site', 'name'),
66
                       common_config('site', 'email'));
67
    } else {
68
        $msg = _('An important error occured, probably related to email setup. '.
69
                 'Check logfiles for more info..');
70
    }
71
72
    $dac = new DBErrorAction($msg, 500);
73
    $dac->showPage();
74
    exit(-1);
75
}
76
77
function checkMirror($action_obj, $args)
78
{
79
    global $config;
80
81
    static $alwaysRW = array('session', 'remember_me');
82
83
    if (common_config('db', 'mirror') && $action_obj->isReadOnly($args)) {
84
        if (is_array(common_config('db', 'mirror'))) {
85
            // "load balancing", ha ha
86
            $arr = common_config('db', 'mirror');
87
            $k = array_rand($arr);
88
            $mirror = $arr[$k];
89
        } else {
90
            $mirror = common_config('db', 'mirror');
91
        }
92
93
        // We ensure that these tables always are used
94
        // on the master DB
95
96
        $config['db']['database_rw'] = $config['db']['database'];
97
        $config['db']['ini_rw'] = INSTALLDIR.'/classes/statusnet.ini';
98
99
        foreach ($alwaysRW as $table) {
100
            $config['db']['table_'.$table] = 'rw';
101
        }
102
103
        // everyone else uses the mirror
104
105
        $config['db']['database'] = $mirror;
106
    }
107
}
108
109
function main()
110
{
111
    // fake HTTP redirects using lighttpd's 404 redirects
112
    if (strpos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
113
        $_lighty_url = $base_url.$_SERVER['REQUEST_URI'];
114
        $_lighty_url = @parse_url($_lighty_url);
115
116
        if ($_lighty_url['path'] != '/index.php' && $_lighty_url['path'] != '/') {
117
            $_lighty_path = preg_replace('/^'.preg_quote(common_config('site','path')).'\//', '', substr($_lighty_url['path'], 1));
118
            $_SERVER['QUERY_STRING'] = 'p='.$_lighty_path;
119
            if ($_lighty_url['query'])
120
                $_SERVER['QUERY_STRING'] .= '&'.$_lighty_url['query'];
121
            parse_str($_lighty_url['query'], $_lighty_query);
122
            foreach ($_lighty_query as $key => $val) {
123
                $_GET[$key] = $_REQUEST[$key] = $val;
124
            }
125
            $_GET['p'] = $_REQUEST['p'] = $_lighty_path;
126
        }
127
    }
128
    $_SERVER['REDIRECT_URL'] = preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']);
129
130
    // quick check for fancy URL auto-detection support in installer.
131
    if (isset($_SERVER['REDIRECT_URL']) && (preg_replace("/^\/$/","",(dirname($_SERVER['REQUEST_URI']))) . '/check-fancy') === $_SERVER['REDIRECT_URL']) {
132
        die("Fancy URL support detection succeeded. We suggest you enable this to get fancy (pretty) URLs.");
133
    }
134
    global $user, $action;
135
136
    Snapshot::check();
137
138
    if (!_have_config()) {
139
        $msg = sprintf(_("No configuration file found. Try running ".
140
                         "the installation program first."));
141
        $sac = new ServerErrorAction($msg);
142
        $sac->showPage();
143
        return;
144
    }
145
146
    // For database errors
147
148
    PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handleError');
149
150
    // XXX: we need a little more structure in this script
151
152
    // get and cache current user
153
154
    $user = common_current_user();
155
156
    // initialize language env
157
158
    common_init_language();
159
160
    $path = getPath($_REQUEST);
161
162
    $r = Router::get();
163
164
    $args = $r->map($path);
165
166
    if (!$args) {
167
        $cac = new ClientErrorAction(_('Unknown page'), 404);
168
        $cac->showPage();
169
        return;
170
    }
171
172
    $args = array_merge($args, $_REQUEST);
173
174
    Event::handle('ArgsInitialize', array(&$args));
175
176
    $action = $args['action'];
177
178
    if (!$action || !preg_match('/^[a-zA-Z0-9_-]*$/', $action)) {
179
        common_redirect(common_local_url('public'));
180
        return;
181
    }
182
183
    // If the site is private, and they're not on one of the "public"
184
    // parts of the site, redirect to login
185
186
    if (!$user && common_config('site', 'private')) {
187
        $public_actions = array('openidlogin', 'finishopenidlogin',
188
                                'recoverpassword', 'api', 'doc',
189
                                'opensearch');
190
        $login_action = 'openidlogin';
191
        if (!common_config('site', 'openidonly')) {
192
            $public_actions[] = 'login';
193
            $public_actions[] = 'register';
194
            $login_action = 'login';
195
        }
196
        if (!in_array($action, $public_actions) &&
197
            !preg_match('/rss$/', $action)) {
198
199
            // set returnto
200
            $rargs =& common_copy_args($args);
201
            unset($rargs['action']);
202
            if (common_config('site', 'fancy')) {
203
                unset($rargs['p']);
204
            }
205
            if (array_key_exists('submit', $rargs)) {
206
                unset($rargs['submit']);
207
            }
208
            foreach (array_keys($_COOKIE) as $cookie) {
209
                unset($rargs[$cookie]);
210
            }
211
            common_set_returnto(common_local_url($action, $rargs));
212
213
            common_redirect(common_local_url($login_action));
214
            return;
215
        }
216
    }
217
218
    $action_class = ucfirst($action).'Action';
219
220
    if (!class_exists($action_class)) {
221
        $cac = new ClientErrorAction(_('Unknown action'), 404);
222
        $cac->showPage();
223
    } else {
224
        $action_obj = new $action_class();
225
226
        checkMirror($action_obj, $args);
227
228
        try {
229
            if ($action_obj->prepare($args)) {
230
                $action_obj->handle($args);
231
            }
232
        } catch (ClientException $cex) {
233
            $cac = new ClientErrorAction($cex->getMessage(), $cex->getCode());
234
            $cac->showPage();
235
        } catch (ServerException $sex) { // snort snort guffaw
236
            $sac = new ServerErrorAction($sex->getMessage(), $sex->getCode());
237
            $sac->showPage();
238
        } catch (Exception $ex) {
239
            $sac = new ServerErrorAction($ex->getMessage());
240
            $sac->showPage();
241
        }
242
    }
243
}
244
245
main();
246
247
// XXX: cleanup exit() calls or add an exit handler so
248
// this always gets called
249
250
Event::handle('CleanupPlugin');