index.php 10 KB

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