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