Introduced common_location_shared() to check if location sharing is always,
[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   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 // Comment in if you have xdebug installed and need a detailed backtrace:
41 //xdebug_start_trace();
42
43 $_startTime = microtime(true);
44 $_perfCounters = array();
45
46 define('INSTALLDIR', dirname(__FILE__));
47 define('GNUSOCIAL', true);
48 define('STATUSNET', true);  // compatibility
49
50 $user = null;
51 $action = null;
52
53 function getPath($req)
54 {
55     $p = null;
56
57     if ((common_config('site', 'fancy') || !array_key_exists('PATH_INFO', $_SERVER))
58         && array_key_exists('p', $req)
59     ) {
60         $p = $req['p'];
61     } else if (array_key_exists('PATH_INFO', $_SERVER)) {
62         $path = $_SERVER['PATH_INFO'];
63         $script = $_SERVER['SCRIPT_NAME'];
64         if (substr($path, 0, mb_strlen($script)) == $script) {
65             $p = substr($path, mb_strlen($script) + 1);
66         } else {
67             $p = $path;
68         }
69     } else {
70         $p = null;
71     }
72
73     // Trim all initial '/'
74
75     $p = ltrim($p, '/');
76
77     return $p;
78 }
79
80 /**
81  * logs and then displays error messages
82  *
83  * @return void
84  */
85 function handleError($error)
86 {
87     try {
88
89         if ($error->getCode() == DB_DATAOBJECT_ERROR_NODATA) {
90             return;
91         }
92
93         $logmsg = "PEAR error: " . $error->getMessage();
94         if ($error instanceof PEAR_Exception && common_config('site', 'logdebug')) {
95             $logmsg .= " : ". $error->toText();
96         }
97         // DB queries often end up with a lot of newlines; merge to a single line
98         // for easier grepability...
99         $logmsg = str_replace("\n", " ", $logmsg);
100         common_log(LOG_ERR, $logmsg);
101
102         // @fixme backtrace output should be consistent with exception handling
103         if (common_config('site', 'logdebug')) {
104             $bt = $error->getTrace();
105             foreach ($bt as $n => $line) {
106                 common_log(LOG_ERR, formatBacktraceLine($n, $line));
107             }
108         }
109         if ($error instanceof DB_DataObject_Error
110             || $error instanceof DB_Error
111             || ($error instanceof PEAR_Exception && $error->getCode() == -24)
112         ) {
113             //If we run into a DB error, assume we can't connect to the DB at all
114             //so set the current user to null, so we don't try to access the DB
115             //while rendering the error page.
116             global $_cur;
117             $_cur = null;
118
119             $msg = sprintf(
120                 // TRANS: Database error message.
121                 _('The database for %1$s is not responding correctly, '.
122                   'so the site will not work properly. '.
123                   'The site admins probably know about the problem, '.
124                   'but you can contact them at %2$s to make sure. '.
125                   'Otherwise, wait a few minutes and try again.'
126                 ),
127                 common_config('site', 'name'),
128                 common_config('site', 'email')
129             );
130
131             $dac = new DBErrorAction($msg, 500);
132             $dac->showPage();
133         } else {
134             $sac = new ServerErrorAction($error->getMessage(), 500, $error);
135             $sac->showPage();
136         }
137
138     } catch (Exception $e) {
139         // TRANS: Error message.
140         echo _('An error occurred.');
141     }
142     exit(-1);
143 }
144
145 set_exception_handler('handleError');
146
147 // quick check for fancy URL auto-detection support in installer.
148 if (preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']) === preg_replace("/^\/$/", "", (dirname($_SERVER['REQUEST_URI']))) . '/check-fancy') {
149     die("Fancy URL support detection succeeded. We suggest you enable this to get fancy (pretty) URLs.");
150 }
151
152 require_once INSTALLDIR . '/lib/common.php';
153
154 /**
155  * Format a backtrace line for debug output roughly like debug_print_backtrace() does.
156  * Exceptions already have this built in, but PEAR error objects just give us the array.
157  *
158  * @param int $n line number
159  * @param array $line per-frame array item from debug_backtrace()
160  * @return string
161  */
162 function formatBacktraceLine($n, $line)
163 {
164     $out = "#$n ";
165     if (isset($line['class'])) $out .= $line['class'];
166     if (isset($line['type'])) $out .= $line['type'];
167     if (isset($line['function'])) $out .= $line['function'];
168     $out .= '(';
169     if (isset($line['args'])) {
170         $args = array();
171         foreach ($line['args'] as $arg) {
172             // debug_print_backtrace seems to use var_export
173             // but this gets *very* verbose!
174             $args[] = gettype($arg);
175         }
176         $out .= implode(',', $args);
177     }
178     $out .= ')';
179     $out .= ' called at [';
180     if (isset($line['file'])) $out .= $line['file'];
181     if (isset($line['line'])) $out .= ':' . $line['line'];
182     $out .= ']';
183     return $out;
184 }
185
186 function setupRW()
187 {
188     global $config;
189
190     static $alwaysRW = array('session', 'remember_me');
191
192     $rwdb = $config['db']['database'];
193
194     if (Event::handle('StartReadWriteTables', array(&$alwaysRW, &$rwdb))) {
195
196         // We ensure that these tables always are used
197         // on the master DB
198
199         $config['db']['database_rw'] = $rwdb;
200         $config['db']['ini_rw'] = INSTALLDIR.'/classes/statusnet.ini';
201
202         foreach ($alwaysRW as $table) {
203             $config['db']['table_'.$table] = 'rw';
204         }
205
206         Event::handle('EndReadWriteTables', array($alwaysRW, $rwdb));
207     }
208
209     return;
210 }
211
212 function isLoginAction($action)
213 {
214     static $loginActions =  array('login', 'recoverpassword', 'api', 'doc', 'register', 'publicxrds', 'otp', 'opensearch', 'rsd');
215
216     $login = null;
217
218     if (Event::handle('LoginAction', array($action, &$login))) {
219         $login = in_array($action, $loginActions);
220     }
221
222     return $login;
223 }
224
225 function main()
226 {
227     global $user, $action;
228
229     if (!_have_config()) {
230         $msg = sprintf(
231             // TRANS: Error message displayed when there is no StatusNet configuration file.
232             _("No configuration file found. Try running ".
233               "the installation program first."
234             )
235         );
236         $sac = new ServerErrorAction($msg);
237         $sac->showPage();
238         return;
239     }
240
241     // Make sure RW database is setup
242
243     setupRW();
244
245     // XXX: we need a little more structure in this script
246
247     // get and cache current user (may hit RW!)
248
249     $user = common_current_user();
250
251     // initialize language env
252
253     common_init_language();
254
255     $path = getPath($_REQUEST);
256
257     $r = Router::get();
258
259     $args = $r->map($path);
260
261     if (!$args) {
262         // TRANS: Error message displayed when trying to access a non-existing page.
263         $cac = new ClientErrorAction(_('Unknown page'), 404);
264         $cac->showPage();
265         return;
266     }
267
268     $site_ssl = common_config('site', 'ssl');
269
270     // If the request is HTTP and it should be HTTPS...
271     if ($site_ssl != 'never' && !GNUsocial::isHTTPS() && common_is_sensitive($args['action'])) {
272         common_redirect(common_local_url($args['action'], $args));
273     }
274
275     $args = array_merge($args, $_REQUEST);
276
277     Event::handle('ArgsInitialize', array(&$args));
278
279     $action = basename($args['action']);
280
281     if (!$action || !preg_match('/^[a-zA-Z0-9_-]*$/', $action)) {
282         common_redirect(common_local_url('public'));
283     }
284
285     // If the site is private, and they're not on one of the "public"
286     // parts of the site, redirect to login
287
288     if (!$user && common_config('site', 'private')
289         && !isLoginAction($action)
290         && !preg_match('/rss$/', $action)
291         && $action != 'robotstxt'
292         && !preg_match('/^Api/', $action)) {
293
294         // set returnto
295         $rargs =& common_copy_args($args);
296         unset($rargs['action']);
297         if (common_config('site', 'fancy')) {
298             unset($rargs['p']);
299         }
300         if (array_key_exists('submit', $rargs)) {
301             unset($rargs['submit']);
302         }
303         foreach (array_keys($_COOKIE) as $cookie) {
304             unset($rargs[$cookie]);
305         }
306         common_set_returnto(common_local_url($action, $rargs));
307
308         common_redirect(common_local_url('login'));
309     }
310
311     $action_class = ucfirst($action).'Action';
312
313     if (!class_exists($action_class)) {
314         // TRANS: Error message displayed when trying to perform an undefined action.
315         $cac = new ClientErrorAction(_('Unknown action'), 404);
316         $cac->showPage();
317     } else {
318         try {
319             call_user_func("$action_class::run", $args);
320         } catch (ClientException $e) {
321             $cac = new ClientErrorAction($e->getMessage(), $e->getCode());
322             $cac->showPage();
323         } catch (ServerException $e) { // snort snort guffaw
324             $sac = new ServerErrorAction($e->getMessage(), $e->getCode(), $e);
325             $sac->showPage();
326         } catch (Exception $e) {
327             $sac = new ServerErrorAction($e->getMessage(), 500, $e);
328             $sac->showPage();
329         }
330     }
331 }
332
333 main();
334
335 // XXX: cleanup exit() calls or add an exit handler so
336 // this always gets called
337
338 Event::handle('CleanupPlugin');