index.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Main GNU social entry point
  18. *
  19. * @package GNUsocial
  20. * @author Brenda Wallace <shiny@cpan.org>
  21. * @author Brion Vibber <brion@pobox.com>
  22. * @author Brion Vibber <brion@status.net>
  23. * @author Christopher Vollick <candrews@integralblue.com>
  24. * @author CiaranG <ciaran@ciarang.com>
  25. * @author Craig Andrews <candrews@integralblue.com>
  26. * @author Craig Andrews <evan@status.net>
  27. * @author Evan Prodromou <evan@controlezvous.ca>
  28. * @author Evan Prodromou <evan@controlyourself.ca>
  29. * @author Evan Prodromou <evan@prodromou.name>
  30. * @author Evan Prodromou <evan@status.net>
  31. * @author Gina Haeussge <osd@foosel.net>
  32. * @author James Walker <walkah@walkah.net>
  33. * @author Jeffery To <candrews@integralblue.com>
  34. * @author Jeffery To <jeffery.to@gmail.com>
  35. * @author Mikael Nordfeldth <mmn@hethane.se>
  36. * @author Mike Cochrane <mikec@mikenz.geek.nz>
  37. * @author Robin Millette <millette@controlyourself.ca>
  38. * @author Sarven Capadisli <csarven@controlyourself.ca>
  39. * @author Sarven Capadisli <csarven@status.net>
  40. * @author Siebrand Mazeland <s.mazeland@xs4all.nl>
  41. * @author Tom Adams <candrews@integralblue.com>
  42. * @author Tom Adams <tom@holizz.com>
  43. * @author Zach Copley <zach@status.net>
  44. * @author Diogo Cordeiro <diogo@fc.up.pt>
  45. * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
  46. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  47. */
  48. $_startTime = microtime(true);
  49. $_perfCounters = array();
  50. // We provide all our dependencies through our own autoload.
  51. // This will probably be configurable for distributing with
  52. // system packages (like with Debian apt etc. where included
  53. // libraries are maintained through repositories)
  54. set_include_path('.'); // mainly fixes an issue where /usr/share/{pear,php*}/DB/DataObject.php is _old_ on various systems...
  55. define('INSTALLDIR', dirname(__DIR__));
  56. define('PUBLICDIR', INSTALLDIR . DIRECTORY_SEPARATOR . 'public');
  57. define('GNUSOCIAL', true);
  58. define('STATUSNET', true); // compatibility
  59. $user = null;
  60. $action = null;
  61. function getPath($req)
  62. {
  63. $p = null;
  64. if ((common_config('site', 'fancy') || !array_key_exists('PATH_INFO', $_SERVER))
  65. && array_key_exists('p', $req)
  66. ) {
  67. $p = $req['p'];
  68. } else if (array_key_exists('PATH_INFO', $_SERVER)) {
  69. $path = $_SERVER['PATH_INFO'];
  70. $script = $_SERVER['SCRIPT_NAME'];
  71. if (substr($path, 0, mb_strlen($script)) == $script) {
  72. $p = substr($path, mb_strlen($script) + 1);
  73. } else {
  74. $p = $path;
  75. }
  76. } else {
  77. $p = null;
  78. }
  79. // Trim all initial '/'
  80. $p = ltrim($p, '/');
  81. return $p;
  82. }
  83. /**
  84. * logs and then displays error messages
  85. *
  86. * @return void
  87. */
  88. function handleError($error)
  89. {
  90. try {
  91. if ($error->getCode() == DB_DATAOBJECT_ERROR_NODATA) {
  92. return;
  93. }
  94. $logmsg = "Exception thrown: " . _ve($error->getMessage());
  95. if ($error instanceof PEAR_Exception && common_config('log', 'debugtrace')) {
  96. $logmsg .= " PEAR: ". $error->toText();
  97. }
  98. // DB queries often end up with a lot of newlines; merge to a single line
  99. // for easier grepability...
  100. $logmsg = str_replace("\n", " ", $logmsg);
  101. common_log(LOG_ERR, $logmsg);
  102. // @fixme backtrace output should be consistent with exception handling
  103. if (common_config('log', 'debugtrace')) {
  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. $msg = sprintf(
  119. // TRANS: Database error message.
  120. _('The database for %1$s is not responding correctly, '.
  121. 'so the site will not work properly. '.
  122. 'The site admins probably know about the problem, '.
  123. 'but you can contact them at %2$s to make sure. '.
  124. 'Otherwise, wait a few minutes and try again.'
  125. ),
  126. common_config('site', 'name'),
  127. common_config('site', 'email')
  128. );
  129. $erraction = new DBErrorAction($msg, 500);
  130. } elseif ($error instanceof ClientException) {
  131. $erraction = new ClientErrorAction($error->getMessage(), $error->getCode());
  132. } elseif ($error instanceof ServerException) {
  133. $erraction = new ServerErrorAction($error->getMessage(), $error->getCode(), $error);
  134. } else {
  135. // If it wasn't specified more closely which kind of exception it was
  136. $erraction = new ServerErrorAction($error->getMessage(), 500, $error);
  137. }
  138. $erraction->showPage();
  139. } catch (Exception $e) {
  140. // TRANS: Error message.
  141. echo _('An error occurred.');
  142. error_log('Uncaught Exception: ' . $error);
  143. exit(-1);
  144. }
  145. exit(-1);
  146. }
  147. set_exception_handler('handleError');
  148. // quick check for fancy URL auto-detection support in installer.
  149. if (preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']) === preg_replace("/^\/$/", "", (dirname($_SERVER['REQUEST_URI']))) . '/check-fancy') {
  150. die("Fancy URL support detection succeeded. We suggest you enable this to get fancy (pretty) URLs.");
  151. }
  152. require_once INSTALLDIR . '/lib/util/common.php';
  153. /**
  154. * Format a backtrace line for debug output roughly like debug_print_backtrace() does.
  155. * Exceptions already have this built in, but PEAR error objects just give us the array.
  156. *
  157. * @param int $n line number
  158. * @param array $line per-frame array item from debug_backtrace()
  159. * @return string
  160. */
  161. function formatBacktraceLine($n, $line)
  162. {
  163. $out = "#$n ";
  164. if (isset($line['class'])) $out .= $line['class'];
  165. if (isset($line['type'])) $out .= $line['type'];
  166. if (isset($line['function'])) $out .= $line['function'];
  167. $out .= '(';
  168. if (isset($line['args'])) {
  169. $args = array();
  170. foreach ($line['args'] as $arg) {
  171. // debug_print_backtrace seems to use var_export
  172. // but this gets *very* verbose!
  173. $args[] = gettype($arg);
  174. }
  175. $out .= implode(',', $args);
  176. }
  177. $out .= ')';
  178. $out .= ' called at [';
  179. if (isset($line['file'])) $out .= $line['file'];
  180. if (isset($line['line'])) $out .= ':' . $line['line'];
  181. $out .= ']';
  182. return $out;
  183. }
  184. function setupRW()
  185. {
  186. global $config;
  187. static $alwaysRW = array('session', 'remember_me');
  188. $rwdb = $config['db']['database'];
  189. if (Event::handle('StartReadWriteTables', array(&$alwaysRW, &$rwdb))) {
  190. // We ensure that these tables always are used
  191. // on the master DB
  192. $config['db']['database_rw'] = $rwdb;
  193. $config['db']['ini_rw'] = INSTALLDIR.'/classes/statusnet.ini';
  194. foreach ($alwaysRW as $table) {
  195. $config['db']['table_'.$table] = 'rw';
  196. }
  197. Event::handle('EndReadWriteTables', array($alwaysRW, $rwdb));
  198. }
  199. return;
  200. }
  201. function isLoginAction($action)
  202. {
  203. static $loginActions = array('login', 'recoverpassword', 'api', 'doc', 'register', 'publicxrds', 'otp', 'opensearch', 'rsd');
  204. $login = null;
  205. if (Event::handle('LoginAction', array($action, &$login))) {
  206. $login = in_array($action, $loginActions);
  207. }
  208. return $login;
  209. }
  210. function main()
  211. {
  212. global $user, $action;
  213. if (!_have_config()) {
  214. $msg = sprintf(
  215. // TRANS: Error message displayed when there is no StatusNet configuration file.
  216. _("No configuration file found. Try running ".
  217. "the installation program first."
  218. )
  219. );
  220. $sac = new ServerErrorAction($msg);
  221. $sac->showPage();
  222. return;
  223. }
  224. // Make sure RW database is setup
  225. setupRW();
  226. // XXX: we need a little more structure in this script
  227. // get and cache current user (may hit RW!)
  228. $user = common_current_user();
  229. // initialize language env
  230. common_init_language();
  231. $path = getPath($_REQUEST);
  232. $r = Router::get();
  233. $args = $r->map($path);
  234. // If the request is HTTP and it should be HTTPS...
  235. if (GNUsocial::useHTTPS() && !GNUsocial::isHTTPS()) {
  236. common_redirect(common_local_url($args['action'], $args));
  237. }
  238. $args = array_merge($args, $_REQUEST ?: []);
  239. Event::handle('ArgsInitialize', array(&$args));
  240. $action = basename($args['action']);
  241. if (!$action || !preg_match('/^[a-zA-Z0-9_-]*$/', $action)) {
  242. common_redirect(common_local_url('public'));
  243. }
  244. // If the site is private, and they're not on one of the "public"
  245. // parts of the site, redirect to login
  246. if (!$user && common_config('site', 'private')
  247. && !isLoginAction($action)
  248. && !preg_match('/rss$/', $action)
  249. && $action != 'robotstxt'
  250. && !preg_match('/^Api/', $action)) {
  251. // set returnto
  252. $rargs =& common_copy_args($args);
  253. unset($rargs['action']);
  254. if (common_config('site', 'fancy')) {
  255. unset($rargs['p']);
  256. }
  257. if (array_key_exists('submit', $rargs)) {
  258. unset($rargs['submit']);
  259. }
  260. foreach (array_keys($_COOKIE) as $cookie) {
  261. unset($rargs[$cookie]);
  262. }
  263. common_set_returnto(common_local_url($action, $rargs));
  264. common_redirect(common_local_url('login'));
  265. }
  266. $action_class = ucfirst($action).'Action';
  267. if (!class_exists($action_class)) {
  268. // TRANS: Error message displayed when trying to perform an undefined action.
  269. throw new ClientException(_('Unknown action'), 404);
  270. }
  271. call_user_func("$action_class::run", $args);
  272. }
  273. main();
  274. // XXX: cleanup exit() calls or add an exit handler so
  275. // this always gets called
  276. Event::handle('CleanupModule');
  277. Event::handle('CleanupPlugin');