index.php 11 KB

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