]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - index.php
Merge branch '0.9.x' into 1.0.x
[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   Christopher Vollick <psycotica0@gmail.com>
23  * @author   CiaranG <ciaran@ciarang.com>
24  * @author   Craig Andrews <candrews@integralblue.com>
25  * @author   Evan Prodromou <evan@controlezvous.ca>
26  * @author   Gina Haeussge <osd@foosel.net>
27  * @author   Jeffery To <jeffery.to@gmail.com>
28  * @author   Mike Cochrane <mikec@mikenz.geek.nz>
29  * @author   Robin Millette <millette@controlyourself.ca>
30  * @author   Sarven Capadisli <csarven@controlyourself.ca>
31  * @author   Tom Adams <tom@holizz.com>
32  *
33  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
34  */
35
36 define('INSTALLDIR', dirname(__FILE__));
37 define('STATUSNET', true);
38 define('LACONICA', true); // compatibility
39
40 $user = null;
41 $action = null;
42
43 function getPath($req)
44 {
45     if ((common_config('site', 'fancy') || !array_key_exists('PATH_INFO', $_SERVER))
46         && array_key_exists('p', $req)
47     ) {
48         return $req['p'];
49     } else if (array_key_exists('PATH_INFO', $_SERVER)) {
50         $path = $_SERVER['PATH_INFO'];
51         $script = $_SERVER['SCRIPT_NAME'];
52         if (substr($path, 0, mb_strlen($script)) == $script) {
53             return substr($path, mb_strlen($script));
54         } else {
55             return $path;
56         }
57     } else {
58         return null;
59     }
60 }
61
62 /**
63  * logs and then displays error messages
64  *
65  * @return void
66  */
67 function handleError($error)
68 {
69     try {
70
71         if ($error->getCode() == DB_DATAOBJECT_ERROR_NODATA) {
72             return;
73         }
74
75         $logmsg = "PEAR error: " . $error->getMessage();
76         if ($error instanceof PEAR_Exception && common_config('site', 'logdebug')) {
77             $logmsg .= " : ". $error->toText();
78         }
79         // DB queries often end up with a lot of newlines; merge to a single line
80         // for easier grepability...
81         $logmsg = str_replace("\n", " ", $logmsg);
82         common_log(LOG_ERR, $logmsg);
83
84         // @fixme backtrace output should be consistent with exception handling
85         if (common_config('site', 'logdebug')) {
86             $bt = $error->getTrace();
87             foreach ($bt as $n => $line) {
88                 common_log(LOG_ERR, formatBacktraceLine($n, $line));
89             }
90         }
91         if ($error instanceof DB_DataObject_Error
92             || $error instanceof DB_Error
93             || ($error instanceof PEAR_Exception && $error->getCode() == -24)
94         ) {
95             //If we run into a DB error, assume we can't connect to the DB at all
96             //so set the current user to null, so we don't try to access the DB
97             //while rendering the error page.
98             global $_cur;
99             $_cur = null;
100
101             $msg = sprintf(
102                 _(
103                     'The database for %s isn\'t responding correctly, '.
104                     'so the site won\'t work properly. '.
105                     'The site admins probably know about the problem, '.
106                     'but you can contact them at %s to make sure. '.
107                     'Otherwise, wait a few minutes and try again.'
108                 ),
109                 common_config('site', 'name'),
110                 common_config('site', 'email')
111             );
112         } else {
113             $msg = _(
114                 'An important error occured, probably related to email setup. '.
115                 'Check logfiles for more info..'
116             );
117         }
118
119         $dac = new DBErrorAction($msg, 500);
120         $dac->showPage();
121
122     } catch (Exception $e) {
123         echo _('An error occurred.');
124     }
125     exit(-1);
126 }
127
128 set_exception_handler('handleError');
129
130 require_once INSTALLDIR . '/lib/common.php';
131
132 /**
133  * Format a backtrace line for debug output roughly like debug_print_backtrace() does.
134  * Exceptions already have this built in, but PEAR error objects just give us the array.
135  *
136  * @param int $n line number
137  * @param array $line per-frame array item from debug_backtrace()
138  * @return string
139  */
140 function formatBacktraceLine($n, $line)
141 {
142     $out = "#$n ";
143     if (isset($line['class'])) $out .= $line['class'];
144     if (isset($line['type'])) $out .= $line['type'];
145     if (isset($line['function'])) $out .= $line['function'];
146     $out .= '(';
147     if (isset($line['args'])) {
148         $args = array();
149         foreach ($line['args'] as $arg) {
150             // debug_print_backtrace seems to use var_export
151             // but this gets *very* verbose!
152             $args[] = gettype($arg);
153         }
154         $out .= implode(',', $args);
155     }
156     $out .= ')';
157     $out .= ' called at [';
158     if (isset($line['file'])) $out .= $line['file'];
159     if (isset($line['line'])) $out .= ':' . $line['line'];
160     $out .= ']';
161     return $out;
162 }
163
164 function setupRW()
165 {
166     global $config;
167
168     static $alwaysRW = array('session', 'remember_me');
169
170     // We ensure that these tables always are used
171     // on the master DB
172
173     $config['db']['database_rw'] = $config['db']['database'];
174     $config['db']['ini_rw'] = INSTALLDIR.'/classes/statusnet.ini';
175
176     foreach ($alwaysRW as $table) {
177         $config['db']['table_'.$table] = 'rw';
178     }
179 }
180
181 function checkMirror($action_obj, $args)
182 {
183     global $config;
184
185     if (common_config('db', 'mirror') && $action_obj->isReadOnly($args)) {
186         if (is_array(common_config('db', 'mirror'))) {
187             // "load balancing", ha ha
188             $arr = common_config('db', 'mirror');
189             $k = array_rand($arr);
190             $mirror = $arr[$k];
191         } else {
192             $mirror = common_config('db', 'mirror');
193         }
194
195         // everyone else uses the mirror
196
197         $config['db']['database'] = $mirror;
198     }
199 }
200
201 function isLoginAction($action)
202 {
203     static $loginActions =  array('login', 'recoverpassword', 'api', 'doc', 'register', 'publicxrds', 'otp', 'opensearch', 'rsd');
204
205     $login = null;
206
207     if (Event::handle('LoginAction', array($action, &$login))) {
208         $login = in_array($action, $loginActions);
209     }
210
211     return $login;
212 }
213
214 function main()
215 {
216     // fake HTTP redirects using lighttpd's 404 redirects
217     if (strpos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
218         $_lighty_url = $base_url.$_SERVER['REQUEST_URI'];
219         $_lighty_url = @parse_url($_lighty_url);
220
221         if ($_lighty_url['path'] != '/index.php' && $_lighty_url['path'] != '/') {
222             $_lighty_path = preg_replace('/^'.preg_quote(common_config('site', 'path')).'\//', '', substr($_lighty_url['path'], 1));
223             $_SERVER['QUERY_STRING'] = 'p='.$_lighty_path;
224             if ($_lighty_url['query']) {
225                 $_SERVER['QUERY_STRING'] .= '&'.$_lighty_url['query'];
226             }
227             parse_str($_lighty_url['query'], $_lighty_query);
228             foreach ($_lighty_query as $key => $val) {
229                 $_GET[$key] = $_REQUEST[$key] = $val;
230             }
231             $_GET['p'] = $_REQUEST['p'] = $_lighty_path;
232         }
233     }
234     $_SERVER['REDIRECT_URL'] = preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']);
235
236     // quick check for fancy URL auto-detection support in installer.
237     if (isset($_SERVER['REDIRECT_URL']) && (preg_replace("/^\/$/", "", (dirname($_SERVER['REQUEST_URI']))) . '/check-fancy') === $_SERVER['REDIRECT_URL']) {
238         die("Fancy URL support detection succeeded. We suggest you enable this to get fancy (pretty) URLs.");
239     }
240     global $user, $action;
241
242     Snapshot::check();
243
244     if (!_have_config()) {
245         $msg = sprintf(
246             _(
247                 "No configuration file found. Try running ".
248                 "the installation program first."
249             )
250         );
251         $sac = new ServerErrorAction($msg);
252         $sac->showPage();
253         return;
254     }
255
256     // Make sure RW database is setup
257
258     setupRW();
259
260     // XXX: we need a little more structure in this script
261
262     // get and cache current user (may hit RW!)
263
264     $user = common_current_user();
265
266     // initialize language env
267
268     common_init_language();
269
270     $path = getPath($_REQUEST);
271
272     $r = Router::get();
273
274     $args = $r->map($path);
275
276     if (!$args) {
277         $cac = new ClientErrorAction(_('Unknown page'), 404);
278         $cac->showPage();
279         return;
280     }
281
282     $args = array_merge($args, $_REQUEST);
283
284     Event::handle('ArgsInitialize', array(&$args));
285
286     $action = $args['action'];
287
288     if (!$action || !preg_match('/^[a-zA-Z0-9_-]*$/', $action)) {
289         common_redirect(common_local_url('public'));
290         return;
291     }
292
293     // If the site is private, and they're not on one of the "public"
294     // parts of the site, redirect to login
295
296     if (!$user && common_config('site', 'private')
297         && !isLoginAction($action)
298         && !preg_match('/rss$/', $action)
299         && $action != 'robotstxt'
300         && !preg_match('/^Api/', $action)) {
301
302         // set returnto
303         $rargs =& common_copy_args($args);
304         unset($rargs['action']);
305         if (common_config('site', 'fancy')) {
306             unset($rargs['p']);
307         }
308         if (array_key_exists('submit', $rargs)) {
309             unset($rargs['submit']);
310         }
311         foreach (array_keys($_COOKIE) as $cookie) {
312             unset($rargs[$cookie]);
313         }
314         common_set_returnto(common_local_url($action, $rargs));
315
316         common_redirect(common_local_url('login'));
317         return;
318     }
319
320     $action_class = ucfirst($action).'Action';
321
322     if (!class_exists($action_class)) {
323         $cac = new ClientErrorAction(_('Unknown action'), 404);
324         $cac->showPage();
325     } else {
326         $action_obj = new $action_class();
327
328         checkMirror($action_obj, $args);
329
330         try {
331             if ($action_obj->prepare($args)) {
332                 $action_obj->handle($args);
333             }
334         } catch (ClientException $cex) {
335             $cac = new ClientErrorAction($cex->getMessage(), $cex->getCode());
336             $cac->showPage();
337         } catch (ServerException $sex) { // snort snort guffaw
338             $sac = new ServerErrorAction($sex->getMessage(), $sex->getCode(), $sex);
339             $sac->showPage();
340         } catch (Exception $ex) {
341             $sac = new ServerErrorAction($ex->getMessage(), 500, $ex);
342             $sac->showPage();
343         }
344     }
345 }
346
347 main();
348
349 // XXX: cleanup exit() calls or add an exit handler so
350 // this always gets called
351
352 Event::handle('CleanupPlugin');