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