index.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. exit(-1);
  143. }
  144. exit(-1);
  145. }
  146. set_exception_handler('handleError');
  147. // quick check for fancy URL auto-detection support in installer.
  148. if (preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']) === preg_replace("/^\/$/", "", (dirname($_SERVER['REQUEST_URI']))) . '/check-fancy') {
  149. die("Fancy URL support detection succeeded. We suggest you enable this to get fancy (pretty) URLs.");
  150. }
  151. require_once INSTALLDIR . '/lib/common.php';
  152. /**
  153. * Format a backtrace line for debug output roughly like debug_print_backtrace() does.
  154. * Exceptions already have this built in, but PEAR error objects just give us the array.
  155. *
  156. * @param int $n line number
  157. * @param array $line per-frame array item from debug_backtrace()
  158. * @return string
  159. */
  160. function formatBacktraceLine($n, $line)
  161. {
  162. $out = "#$n ";
  163. if (isset($line['class'])) $out .= $line['class'];
  164. if (isset($line['type'])) $out .= $line['type'];
  165. if (isset($line['function'])) $out .= $line['function'];
  166. $out .= '(';
  167. if (isset($line['args'])) {
  168. $args = array();
  169. foreach ($line['args'] as $arg) {
  170. // debug_print_backtrace seems to use var_export
  171. // but this gets *very* verbose!
  172. $args[] = gettype($arg);
  173. }
  174. $out .= implode(',', $args);
  175. }
  176. $out .= ')';
  177. $out .= ' called at [';
  178. if (isset($line['file'])) $out .= $line['file'];
  179. if (isset($line['line'])) $out .= ':' . $line['line'];
  180. $out .= ']';
  181. return $out;
  182. }
  183. function setupRW()
  184. {
  185. global $config;
  186. static $alwaysRW = array('session', 'remember_me');
  187. $rwdb = $config['db']['database'];
  188. if (Event::handle('StartReadWriteTables', array(&$alwaysRW, &$rwdb))) {
  189. // We ensure that these tables always are used
  190. // on the master DB
  191. $config['db']['database_rw'] = $rwdb;
  192. $config['db']['ini_rw'] = INSTALLDIR.'/classes/statusnet.ini';
  193. foreach ($alwaysRW as $table) {
  194. $config['db']['table_'.$table] = 'rw';
  195. }
  196. Event::handle('EndReadWriteTables', array($alwaysRW, $rwdb));
  197. }
  198. return;
  199. }
  200. function isLoginAction($action)
  201. {
  202. static $loginActions = array('login', 'recoverpassword', 'api', 'doc', 'register', 'publicxrds', 'otp', 'opensearch', 'rsd');
  203. $login = null;
  204. if (Event::handle('LoginAction', array($action, &$login))) {
  205. $login = in_array($action, $loginActions);
  206. }
  207. return $login;
  208. }
  209. function main()
  210. {
  211. global $user, $action;
  212. if (!_have_config()) {
  213. $msg = sprintf(
  214. // TRANS: Error message displayed when there is no StatusNet configuration file.
  215. _("No configuration file found. Try running ".
  216. "the installation program first."
  217. )
  218. );
  219. $sac = new ServerErrorAction($msg);
  220. $sac->showPage();
  221. return;
  222. }
  223. // Make sure RW database is setup
  224. setupRW();
  225. // XXX: we need a little more structure in this script
  226. // get and cache current user (may hit RW!)
  227. $user = common_current_user();
  228. // initialize language env
  229. common_init_language();
  230. $path = getPath($_REQUEST);
  231. $r = Router::get();
  232. $args = $r->map($path);
  233. // If the request is HTTP and it should be HTTPS...
  234. if (GNUsocial::useHTTPS() && !GNUsocial::isHTTPS()) {
  235. common_redirect(common_local_url($args['action'], $args));
  236. }
  237. $args = array_merge($args, $_REQUEST ?: []);
  238. Event::handle('ArgsInitialize', array(&$args));
  239. $action = basename($args['action']);
  240. if (!$action || !preg_match('/^[a-zA-Z0-9_-]*$/', $action)) {
  241. common_redirect(common_local_url('public'));
  242. }
  243. // If the site is private, and they're not on one of the "public"
  244. // parts of the site, redirect to login
  245. if (!$user && common_config('site', 'private')
  246. && !isLoginAction($action)
  247. && !preg_match('/rss$/', $action)
  248. && $action != 'robotstxt'
  249. && !preg_match('/^Api/', $action)) {
  250. // set returnto
  251. $rargs =& common_copy_args($args);
  252. unset($rargs['action']);
  253. if (common_config('site', 'fancy')) {
  254. unset($rargs['p']);
  255. }
  256. if (array_key_exists('submit', $rargs)) {
  257. unset($rargs['submit']);
  258. }
  259. foreach (array_keys($_COOKIE) as $cookie) {
  260. unset($rargs[$cookie]);
  261. }
  262. common_set_returnto(common_local_url($action, $rargs));
  263. common_redirect(common_local_url('login'));
  264. }
  265. $action_class = ucfirst($action).'Action';
  266. if (!class_exists($action_class)) {
  267. // TRANS: Error message displayed when trying to perform an undefined action.
  268. throw new ClientException(_('Unknown action'), 404);
  269. }
  270. call_user_func("$action_class::run", $args);
  271. }
  272. main();
  273. // XXX: cleanup exit() calls or add an exit handler so
  274. // this always gets called
  275. Event::handle('CleanupModule');
  276. Event::handle('CleanupPlugin');