index.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. define('INSTALLDIR', dirname(__FILE__));
  42. define('GNUSOCIAL', true);
  43. define('STATUSNET', true); // compatibility
  44. $user = null;
  45. $action = null;
  46. function getPath($req)
  47. {
  48. $p = null;
  49. if ((common_config('site', 'fancy') || !array_key_exists('PATH_INFO', $_SERVER))
  50. && array_key_exists('p', $req)
  51. ) {
  52. $p = $req['p'];
  53. } else if (array_key_exists('PATH_INFO', $_SERVER)) {
  54. $path = $_SERVER['PATH_INFO'];
  55. $script = $_SERVER['SCRIPT_NAME'];
  56. if (substr($path, 0, mb_strlen($script)) == $script) {
  57. $p = substr($path, mb_strlen($script) + 1);
  58. } else {
  59. $p = $path;
  60. }
  61. } else {
  62. $p = null;
  63. }
  64. // Trim all initial '/'
  65. $p = ltrim($p, '/');
  66. return $p;
  67. }
  68. /**
  69. * logs and then displays error messages
  70. *
  71. * @return void
  72. */
  73. function handleError($error)
  74. {
  75. try {
  76. if ($error->getCode() == DB_DATAOBJECT_ERROR_NODATA) {
  77. return;
  78. }
  79. $logmsg = "PEAR error: " . $error->getMessage();
  80. if ($error instanceof PEAR_Exception && common_config('site', 'logdebug')) {
  81. $logmsg .= " : ". $error->toText();
  82. }
  83. // DB queries often end up with a lot of newlines; merge to a single line
  84. // for easier grepability...
  85. $logmsg = str_replace("\n", " ", $logmsg);
  86. common_log(LOG_ERR, $logmsg);
  87. // @fixme backtrace output should be consistent with exception handling
  88. if (common_config('site', 'logdebug')) {
  89. $bt = $error->getTrace();
  90. foreach ($bt as $n => $line) {
  91. common_log(LOG_ERR, formatBacktraceLine($n, $line));
  92. }
  93. }
  94. if ($error instanceof DB_DataObject_Error
  95. || $error instanceof DB_Error
  96. || ($error instanceof PEAR_Exception && $error->getCode() == -24)
  97. ) {
  98. //If we run into a DB error, assume we can't connect to the DB at all
  99. //so set the current user to null, so we don't try to access the DB
  100. //while rendering the error page.
  101. global $_cur;
  102. $_cur = null;
  103. $msg = sprintf(
  104. // TRANS: Database error message.
  105. _('The database for %1$s is not responding correctly, '.
  106. 'so the site will not work properly. '.
  107. 'The site admins probably know about the problem, '.
  108. 'but you can contact them at %2$s to make sure. '.
  109. 'Otherwise, wait a few minutes and try again.'
  110. ),
  111. common_config('site', 'name'),
  112. common_config('site', 'email')
  113. );
  114. $dac = new DBErrorAction($msg, 500);
  115. $dac->showPage();
  116. } else {
  117. $sac = new ServerErrorAction($error->getMessage(), 500, $error);
  118. $sac->showPage();
  119. }
  120. } catch (Exception $e) {
  121. // TRANS: Error message.
  122. echo _('An error occurred.');
  123. }
  124. exit(-1);
  125. }
  126. set_exception_handler('handleError');
  127. // quick check for fancy URL auto-detection support in installer.
  128. if (preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']) === preg_replace("/^\/$/", "", (dirname($_SERVER['REQUEST_URI']))) . '/check-fancy') {
  129. die("Fancy URL support detection succeeded. We suggest you enable this to get fancy (pretty) URLs.");
  130. }
  131. require_once INSTALLDIR . '/lib/common.php';
  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. function setupRW()
  164. {
  165. global $config;
  166. static $alwaysRW = array('session', 'remember_me');
  167. $rwdb = $config['db']['database'];
  168. if (Event::handle('StartReadWriteTables', array(&$alwaysRW, &$rwdb))) {
  169. // We ensure that these tables always are used
  170. // on the master DB
  171. $config['db']['database_rw'] = $rwdb;
  172. $config['db']['ini_rw'] = INSTALLDIR.'/classes/statusnet.ini';
  173. foreach ($alwaysRW as $table) {
  174. $config['db']['table_'.$table] = 'rw';
  175. }
  176. Event::handle('EndReadWriteTables', array($alwaysRW, $rwdb));
  177. }
  178. return;
  179. }
  180. function isLoginAction($action)
  181. {
  182. static $loginActions = array('login', 'recoverpassword', 'api', 'doc', 'register', 'publicxrds', 'otp', 'opensearch', 'rsd');
  183. $login = null;
  184. if (Event::handle('LoginAction', array($action, &$login))) {
  185. $login = in_array($action, $loginActions);
  186. }
  187. return $login;
  188. }
  189. function main()
  190. {
  191. global $user, $action;
  192. if (!_have_config()) {
  193. $msg = sprintf(
  194. // TRANS: Error message displayed when there is no StatusNet configuration file.
  195. _("No configuration file found. Try running ".
  196. "the installation program first."
  197. )
  198. );
  199. $sac = new ServerErrorAction($msg);
  200. $sac->showPage();
  201. return;
  202. }
  203. // Make sure RW database is setup
  204. setupRW();
  205. // XXX: we need a little more structure in this script
  206. // get and cache current user (may hit RW!)
  207. $user = common_current_user();
  208. // initialize language env
  209. common_init_language();
  210. $path = getPath($_REQUEST);
  211. $r = Router::get();
  212. $args = $r->map($path);
  213. if (!$args) {
  214. // TRANS: Error message displayed when trying to access a non-existing page.
  215. $cac = new ClientErrorAction(_('Unknown page'), 404);
  216. $cac->showPage();
  217. return;
  218. }
  219. $site_ssl = common_config('site', 'ssl');
  220. // If the request is HTTP and it should be HTTPS...
  221. if ($site_ssl != 'never' && !StatusNet::isHTTPS() && common_is_sensitive($args['action'])) {
  222. common_redirect(common_local_url($args['action'], $args));
  223. }
  224. $args = array_merge($args, $_REQUEST);
  225. Event::handle('ArgsInitialize', array(&$args));
  226. $action = basename($args['action']);
  227. if (!$action || !preg_match('/^[a-zA-Z0-9_-]*$/', $action)) {
  228. common_redirect(common_local_url('public'));
  229. }
  230. // If the site is private, and they're not on one of the "public"
  231. // parts of the site, redirect to login
  232. if (!$user && common_config('site', 'private')
  233. && !isLoginAction($action)
  234. && !preg_match('/rss$/', $action)
  235. && $action != 'robotstxt'
  236. && !preg_match('/^Api/', $action)) {
  237. // set returnto
  238. $rargs =& common_copy_args($args);
  239. unset($rargs['action']);
  240. if (common_config('site', 'fancy')) {
  241. unset($rargs['p']);
  242. }
  243. if (array_key_exists('submit', $rargs)) {
  244. unset($rargs['submit']);
  245. }
  246. foreach (array_keys($_COOKIE) as $cookie) {
  247. unset($rargs[$cookie]);
  248. }
  249. common_set_returnto(common_local_url($action, $rargs));
  250. common_redirect(common_local_url('login'));
  251. }
  252. $action_class = ucfirst($action).'Action';
  253. if (!class_exists($action_class)) {
  254. // TRANS: Error message displayed when trying to perform an undefined action.
  255. $cac = new ClientErrorAction(_('Unknown action'), 404);
  256. $cac->showPage();
  257. } else {
  258. try {
  259. call_user_func("$action_class::run", $args);
  260. } catch (ClientException $cex) {
  261. $cac = new ClientErrorAction($cex->getMessage(), $cex->getCode());
  262. $cac->showPage();
  263. } catch (ServerException $sex) { // snort snort guffaw
  264. $sac = new ServerErrorAction($sex->getMessage(), $sex->getCode(), $sex);
  265. $sac->showPage();
  266. } catch (Exception $ex) {
  267. $sac = new ServerErrorAction($ex->getMessage(), 500, $ex);
  268. $sac->showPage();
  269. }
  270. }
  271. }
  272. main();
  273. // XXX: cleanup exit() calls or add an exit handler so
  274. // this always gets called
  275. Event::handle('CleanupPlugin');