The official, canonical postActiv repository. http://www.postactiv.com

index.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. <?php
  2. /* ============================================================================
  3. * Title: Entry Point
  4. * Main postActiv entry point
  5. *
  6. * postActiv:
  7. * the micro-blogging software
  8. *
  9. * Copyright:
  10. * Copyright (C) 2016-2017, Maiyannah Bishop
  11. *
  12. * Derived from code copyright various sources:
  13. * o GNU Social (C) 2013-2016, Free Software Foundation, Inc
  14. * o StatusNet (C) 2008-2012, StatusNet, Inc
  15. * ----------------------------------------------------------------------------
  16. * License:
  17. * This program is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License as published by
  19. * the Free Software Foundation, either version 3 of the License, or
  20. * (at your option) any later version.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  29. *
  30. * <https://www.gnu.org/licenses/agpl.html>
  31. * ----------------------------------------------------------------------------
  32. * About:
  33. * Main postActiv entry point
  34. *
  35. * Please note that the software will not execute if the install code is present
  36. * on a live install.
  37. *
  38. * Defines:
  39. * o INSTALLDIR - root directory of the install where index.php is running from
  40. * o POSTACTIV - security constant
  41. * o GNUSOCIAL - legacy security constant
  42. * o STATUSNET - legacy security constant
  43. *
  44. * PHP version:
  45. * Tested with PHP 7
  46. * ----------------------------------------------------------------------------
  47. * File Authors:
  48. * o Evan Prodromou
  49. * o Gina Haeussge <osd@foosel.net>
  50. * o Mike Cochrane <mikec@mikenz.geek.nz>
  51. * o Ciaran Gultneiks <ciaran@ciarang.com>
  52. * o Robin Millette <robin@millette.info>
  53. * o Sarven Capadisli
  54. * o Jeffery To <jeffery.to@gmail.com>
  55. * o Tom Adams <tom@holizz.com>
  56. * o Christopher Vollick <psycotica0@gmail.com>
  57. * o Craig Andrews <candrews@integralblue.com>
  58. * o Brenda Wallace <shiny@cpan.org>
  59. * o Zach Copley
  60. * o Brion Vibber <brion@pobox.com>
  61. * o James Walker <walkah@walkah.net>
  62. * o Siebrand Mazeland <s.mazeland@xs4all.nl>
  63. * o Mikael Nordfeldth <mmn@hethane.se>
  64. * o Maiyannah Bishop <maiyannah.bishop@postactiv.com>
  65. *
  66. * Web:
  67. * o postActiv <http://www.postactiv.com>
  68. * o GNU social <https://www.gnu.org/s/social/>
  69. * ============================================================================
  70. */
  71. // This file is formatted so that it provides useful documentation output in
  72. // NaturalDocs. Please be considerate of this before changing formatting.
  73. $_startTime = microtime(true);
  74. $_perfCounters = array();
  75. // We provide all our dependencies through our own autoload.
  76. // This will probably be configurable for distributing with
  77. // system packages (like with Debian apt etc. where included
  78. // libraries are maintained through repositories)
  79. set_include_path('.'); // mainly fixes an issue where /usr/share/{pear,php*}/DB/DataObject.php is _old_ on various systems...
  80. define('INSTALLDIR', dirname(__FILE__));
  81. define('POSTACTIV', true);
  82. define('GNUSOCIAL', true); // compatibility
  83. define('STATUSNET', true); // compatibility
  84. $user = null;
  85. $action = null;
  86. if (file_exists(INSTALLDIR . '/install.php') & file_exists(INSTALLDIR . '/config.php'))
  87. {
  88. die("Installation script present on a live install. Please remove the installation script.");
  89. }
  90. // =============================================================================
  91. // Group: Helper functions
  92. // Functions used to help bootstrap the application.
  93. // -----------------------------------------------------------------------------
  94. // function: getPath
  95. // Returns the path we are operating postActiv under.
  96. //
  97. // Parameters:
  98. // $req
  99. //
  100. // Returns:
  101. // string
  102. function getPath($req)
  103. {
  104. $p = null;
  105. if ((common_config('site', 'fancy') || !array_key_exists('PATH_INFO', $_SERVER))
  106. && array_key_exists('p', $req)
  107. ) {
  108. $p = $req['p'];
  109. } else if (array_key_exists('PATH_INFO', $_SERVER)) {
  110. $path = $_SERVER['PATH_INFO'];
  111. $script = $_SERVER['SCRIPT_NAME'];
  112. if (substr($path, 0, mb_strlen($script)) == $script) {
  113. $p = substr($path, mb_strlen($script) + 1);
  114. } else {
  115. $p = $path;
  116. }
  117. } else {
  118. $p = null;
  119. }
  120. // Trim all initial '/'
  121. $p = ltrim($p, '/');
  122. return $p;
  123. }
  124. // -----------------------------------------------------------------------------
  125. // Function: handleError
  126. // Logs and then displays error messages
  127. //
  128. // Parameters:
  129. // $error - exception
  130. //
  131. // Return:
  132. // void
  133. function handleError($error)
  134. {
  135. try {
  136. if ($error->getCode() == DB_DATAOBJECT_ERROR_NODATA) {
  137. return;
  138. }
  139. $logmsg = "Exception thrown: " . _ve($error->getMessage());
  140. if ($error instanceof PEAR_Exception && common_config('log', 'debugtrace')) {
  141. $logmsg .= " PEAR: ". $error->toText();
  142. }
  143. // DB queries often end up with a lot of newlines; merge to a single line
  144. // for easier grepability...
  145. $logmsg = str_replace("\n", " ", $logmsg);
  146. common_log(LOG_ERR, $logmsg);
  147. // @fixme backtrace output should be consistent with exception handling
  148. if (common_config('log', 'debugtrace')) {
  149. $bt = $error->getTrace();
  150. foreach ($bt as $n => $line) {
  151. common_log(LOG_ERR, formatBacktraceLine($n, $line));
  152. }
  153. }
  154. if ($error instanceof DB_DataObject_Error
  155. || $error instanceof DB_Error
  156. || ($error instanceof PEAR_Exception && $error->getCode() == -24)
  157. ) {
  158. //If we run into a DB error, assume we can't connect to the DB at all
  159. //so set the current user to null, so we don't try to access the DB
  160. //while rendering the error page.
  161. global $_cur;
  162. $_cur = null;
  163. $msg = sprintf(
  164. // TRANS: Database error message.
  165. _('The database for %1$s is not responding correctly, '.
  166. 'so the site will not work properly. '.
  167. 'The site admins probably know about the problem, '.
  168. 'but you can contact them at %2$s to make sure. '.
  169. 'Otherwise, wait a few minutes and try again.'
  170. ),
  171. common_config('site', 'name'),
  172. common_config('site', 'email')
  173. );
  174. $erraction = new DBErrorAction($msg, 500);
  175. } elseif ($error instanceof ClientException) {
  176. $erraction = new ClientErrorAction($error->getMessage(), $error->getCode());
  177. } elseif ($error instanceof ServerException) {
  178. $erraction = new ServerErrorAction($error->getMessage(), $error->getCode(), $error);
  179. } else {
  180. // If it wasn't specified more closely which kind of exception it was
  181. $erraction = new ServerErrorAction($error->getMessage(), 500, $error);
  182. }
  183. $erraction->showPage();
  184. } catch (Exception $e) {
  185. // TRANS: Error message.
  186. echo _('An error occurred.');
  187. exit(-1);
  188. }
  189. exit(-1);
  190. }
  191. set_exception_handler('handleError');
  192. // quick check for fancy URL auto-detection support in installer.
  193. if (preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']) === preg_replace("/^\/$/", "", (dirname($_SERVER['REQUEST_URI']))) . '/check-fancy') {
  194. die("Fancy URL support detection succeeded. We suggest you enable this to get fancy (pretty) URLs.");
  195. }
  196. require_once INSTALLDIR . '/lib/common.php';
  197. // -----------------------------------------------------------------------------
  198. // function: formatBacktraceLine
  199. // Format a backtrace line for debug output roughly like debug_print_backtrace() does.
  200. // Exceptions already have this built in, but PEAR error objects just give us the array.
  201. //
  202. // Parameters:
  203. // o $n - int line number
  204. // o $line - per-frame array item from debug_backtrace()
  205. //
  206. // Returns:
  207. // string
  208. function formatBacktraceLine($n, $line)
  209. {
  210. $out = "#$n ";
  211. if (isset($line['class'])) $out .= $line['class'];
  212. if (isset($line['type'])) $out .= $line['type'];
  213. if (isset($line['function'])) $out .= $line['function'];
  214. $out .= '(';
  215. if (isset($line['args'])) {
  216. $args = array();
  217. foreach ($line['args'] as $arg) {
  218. // debug_print_backtrace seems to use var_export
  219. // but this gets *very* verbose!
  220. $args[] = gettype($arg);
  221. }
  222. $out .= implode(',', $args);
  223. }
  224. $out .= ')';
  225. $out .= ' called at [';
  226. if (isset($line['file'])) $out .= $line['file'];
  227. if (isset($line['line'])) $out .= ':' . $line['line'];
  228. $out .= ']';
  229. return $out;
  230. }
  231. // -----------------------------------------------------------------------------
  232. // function: setupRW
  233. // Sets up read/write access to the underlying database
  234. //
  235. // Parameters:
  236. // None
  237. //
  238. // Returns:
  239. // Void
  240. function setupRW()
  241. {
  242. global $config;
  243. static $alwaysRW = array('session', 'remember_me');
  244. $rwdb = $config['db']['database'];
  245. if (Event::handle('StartReadWriteTables', array(&$alwaysRW, &$rwdb))) {
  246. // We ensure that these tables always are used
  247. // on the master DB
  248. $config['db']['database_rw'] = $rwdb;
  249. $config['db']['ini_rw'] = INSTALLDIR.'/classes/statusnet.ini';
  250. foreach ($alwaysRW as $table) {
  251. $config['db']['table_'.$table] = 'rw';
  252. }
  253. Event::handle('EndReadWriteTables', array($alwaysRW, $rwdb));
  254. }
  255. return;
  256. }
  257. // ============================================================================
  258. // Group: Entry points
  259. // ----------------------------------------------------------------------------
  260. // Function: isLoginAction
  261. // Returns true of the index is being accessed as part of a login action, false
  262. // if not
  263. //
  264. // Parameters:
  265. // $action
  266. //
  267. // Returns
  268. // boolean
  269. function isLoginAction($action)
  270. {
  271. static $loginActions = array('login', 'recoverpassword', 'api', 'doc', 'register', 'publicxrds', 'otp', 'opensearch', 'rsd');
  272. $login = null;
  273. if (Event::handle('LoginAction', array($action, &$login))) {
  274. $login = in_array($action, $loginActions);
  275. }
  276. return $login;
  277. }
  278. // ----------------------------------------------------------------------------
  279. // Function: main
  280. // Main entry point for the server application
  281. //
  282. // Parameters:
  283. // None
  284. //
  285. // Returns:
  286. // Void
  287. function main()
  288. {
  289. global $user, $action;
  290. if (!_have_config()) {
  291. $msg = sprintf(
  292. // TRANS: Error message displayed when there is no StatusNet configuration file.
  293. _("No configuration file found. Try running ".
  294. "the installation program first."
  295. )
  296. );
  297. $sac = new ServerErrorAction($msg);
  298. $sac->showPage();
  299. return;
  300. }
  301. // Make sure RW database is setup
  302. setupRW();
  303. // XXX: we need a little more structure in this script
  304. // get and cache current user (may hit RW!)
  305. $user = common_current_user();
  306. // initialize language env
  307. common_init_language();
  308. $path = getPath($_REQUEST);
  309. $r = Router::get();
  310. $args = $r->map($path);
  311. // If the request is HTTP and it should be HTTPS...
  312. if (postActiv::useHTTPS() && !postActiv::isHTTPS()) {
  313. common_redirect(common_local_url($args['action'], $args));
  314. }
  315. $args = array_merge($args, $_REQUEST);
  316. Event::handle('ArgsInitialize', array(&$args));
  317. $action = basename($args['action']);
  318. if (!$action || !preg_match('/^[a-zA-Z0-9_-]*$/', $action)) {
  319. common_redirect(common_local_url('public'));
  320. }
  321. // If the site is private, and they're not on one of the "public"
  322. // parts of the site, redirect to login
  323. if (!$user && common_config('site', 'private')
  324. && !isLoginAction($action)
  325. && !preg_match('/rss$/', $action)
  326. && $action != 'robotstxt'
  327. && !preg_match('/^Api/', $action)) {
  328. // set returnto
  329. $rargs =& common_copy_args($args);
  330. unset($rargs['action']);
  331. if (common_config('site', 'fancy')) {
  332. unset($rargs['p']);
  333. }
  334. if (array_key_exists('submit', $rargs)) {
  335. unset($rargs['submit']);
  336. }
  337. foreach (array_keys($_COOKIE) as $cookie) {
  338. unset($rargs[$cookie]);
  339. }
  340. common_set_returnto(common_local_url($action, $rargs));
  341. common_redirect(common_local_url('login'));
  342. }
  343. $action_class = ucfirst($action).'Action';
  344. if (!class_exists($action_class)) {
  345. // TRANS: Error message displayed when trying to perform an undefined action.
  346. throw new ClientException(_('Unknown action'), 404);
  347. }
  348. call_user_func("$action_class::run", $args);
  349. }
  350. main();
  351. // XXX: cleanup exit() calls or add an exit handler so
  352. // this always gets called
  353. Event::handle('CleanupPlugin');
  354. // END OF FILE
  355. // =============================================================================
  356. ?>