Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

526 lines
16 KiB

  1. <?php
  2. /**
  3. * @file index.php
  4. * Friendica
  5. */
  6. /**
  7. * Bootstrap the application
  8. */
  9. use Friendica\App;
  10. use Friendica\BaseObject;
  11. use Friendica\Content\Nav;
  12. use Friendica\Core\Addon;
  13. use Friendica\Core\Config;
  14. use Friendica\Core\L10n;
  15. use Friendica\Core\Session;
  16. use Friendica\Core\System;
  17. use Friendica\Core\Theme;
  18. use Friendica\Core\Worker;
  19. use Friendica\Database\DBM;
  20. use Friendica\Model\Profile;
  21. use Friendica\Module\Login;
  22. require_once 'boot.php';
  23. if (empty($a)) {
  24. $a = new App(__DIR__);
  25. }
  26. BaseObject::setApp($a);
  27. // We assume that the index.php is called by a frontend process
  28. // The value is set to "true" by default in boot.php
  29. $a->backend = false;
  30. /**
  31. * Load the configuration file which contains our DB credentials.
  32. * Ignore errors. If the file doesn't exist or is empty, we are running in
  33. * installation mode.
  34. */
  35. $install = ((file_exists('.htconfig.php') && filesize('.htconfig.php')) ? false : true);
  36. // Only load config if found, don't surpress errors
  37. if (!$install) {
  38. include ".htconfig.php";
  39. }
  40. /**
  41. * Try to open the database;
  42. */
  43. require_once "include/dba.php";
  44. if (!$install) {
  45. dba::connect($db_host, $db_user, $db_pass, $db_data, $install);
  46. unset($db_host, $db_user, $db_pass, $db_data);
  47. /**
  48. * Load configs from db. Overwrite configs from .htconfig.php
  49. */
  50. Config::load();
  51. if ($a->max_processes_reached() || $a->maxload_reached()) {
  52. header($_SERVER["SERVER_PROTOCOL"] . ' 503 Service Temporarily Unavailable');
  53. header('Retry-After: 120');
  54. header('Refresh: 120; url=' . System::baseUrl() . "/" . $a->query_string);
  55. die("System is currently unavailable. Please try again later");
  56. }
  57. if (Config::get('system', 'force_ssl') && ($a->get_scheme() == "http")
  58. && (intval(Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL)
  59. && (substr(System::baseUrl(), 0, 8) == "https://")
  60. && ($_SERVER['REQUEST_METHOD'] == 'GET')) {
  61. header("HTTP/1.1 302 Moved Temporarily");
  62. header("Location: " . System::baseUrl() . "/" . $a->query_string);
  63. exit();
  64. }
  65. Session::init();
  66. Addon::loadHooks();
  67. Addon::callHooks('init_1');
  68. $maintenance = Config::get('system', 'maintenance');
  69. }
  70. $lang = L10n::getBrowserLanguage();
  71. L10n::loadTranslationTable($lang);
  72. /**
  73. * Important stuff we always need to do.
  74. *
  75. * The order of these may be important so use caution if you think they're all
  76. * intertwingled with no logical order and decide to sort it out. Some of the
  77. * dependencies have changed, but at least at one time in the recent past - the
  78. * order was critical to everything working properly
  79. */
  80. // Exclude the backend processes from the session management
  81. if (!$a->is_backend()) {
  82. $stamp1 = microtime(true);
  83. session_start();
  84. $a->save_timestamp($stamp1, "parser");
  85. } else {
  86. $_SESSION = [];
  87. Worker::executeIfIdle();
  88. }
  89. /**
  90. * Language was set earlier, but we can over-ride it in the session.
  91. * We have to do it here because the session was just now opened.
  92. */
  93. if (x($_SESSION, 'authenticated') && !x($_SESSION, 'language')) {
  94. // we haven't loaded user data yet, but we need user language
  95. $user = dba::selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
  96. $_SESSION['language'] = $lang;
  97. if (DBM::is_result($user)) {
  98. $_SESSION['language'] = $user['language'];
  99. }
  100. }
  101. if ((x($_SESSION, 'language')) && ($_SESSION['language'] !== $lang)) {
  102. $lang = $_SESSION['language'];
  103. L10n::loadTranslationTable($lang);
  104. }
  105. if ((x($_GET, 'zrl')) && (!$install && !$maintenance)) {
  106. // Only continue when the given profile link seems valid
  107. // Valid profile links contain a path with "/profile/" and no query parameters
  108. if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "")
  109. && strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")
  110. ) {
  111. $_SESSION['my_url'] = $_GET['zrl'];
  112. $a->query_string = preg_replace('/[\?&]zrl=(.*?)([\?&]|$)/is', '', $a->query_string);
  113. Profile::zrlInit($a);
  114. } else {
  115. // Someone came with an invalid parameter, maybe as a DDoS attempt
  116. // We simply stop processing here
  117. logger("Invalid ZRL parameter ".$_GET['zrl'], LOGGER_DEBUG);
  118. header('HTTP/1.1 403 Forbidden');
  119. echo "<h1>403 Forbidden</h1>";
  120. killme();
  121. }
  122. }
  123. /**
  124. * For Mozilla auth manager - still needs sorting, and this might conflict with LRDD header.
  125. * Apache/PHP lumps the Link: headers into one - and other services might not be able to parse it
  126. * this way. There's a PHP flag to link the headers because by default this will over-write any other
  127. * link header.
  128. *
  129. * What we really need to do is output the raw headers ourselves so we can keep them separate.
  130. */
  131. // header('Link: <' . System::baseUrl() . '/amcd>; rel="acct-mgmt";');
  132. Login::sessionAuth();
  133. if (! x($_SESSION, 'authenticated')) {
  134. header('X-Account-Management-Status: none');
  135. }
  136. /* set up page['htmlhead'] and page['end'] for the modules to use */
  137. $a->page['htmlhead'] = '';
  138. $a->page['end'] = '';
  139. $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
  140. $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
  141. $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
  142. /*
  143. * check_config() is responsible for running update scripts. These automatically
  144. * update the DB schema whenever we push a new one out. It also checks to see if
  145. * any addons have been added or removed and reacts accordingly.
  146. */
  147. // in install mode, any url loads install module
  148. // but we need "view" module for stylesheet
  149. if ($install && $a->module!="view") {
  150. $a->module = 'install';
  151. } elseif ($maintenance && $a->module!="view") {
  152. $a->module = 'maintenance';
  153. } else {
  154. check_url($a);
  155. check_db(false);
  156. check_addons($a);
  157. }
  158. Nav::setSelected('nothing');
  159. //Don't populate apps_menu if apps are private
  160. $privateapps = Config::get('config', 'private_addons');
  161. if ((local_user()) || (! $privateapps === "1")) {
  162. $arr = ['app_menu' => $a->apps];
  163. Addon::callHooks('app_menu', $arr);
  164. $a->apps = $arr['app_menu'];
  165. }
  166. /**
  167. * We have already parsed the server path into $a->argc and $a->argv
  168. *
  169. * $a->argv[0] is our module name. We will load the file mod/{$a->argv[0]}.php
  170. * and use it for handling our URL request.
  171. * The module file contains a few functions that we call in various circumstances
  172. * and in the following order:
  173. *
  174. * "module"_init
  175. * "module"_post (only called if there are $_POST variables)
  176. * "module"_afterpost
  177. * "module"_content - the string return of this function contains our page body
  178. *
  179. * Modules which emit other serialisations besides HTML (XML,JSON, etc.) should do
  180. * so within the module init and/or post functions and then invoke killme() to terminate
  181. * further processing.
  182. */
  183. if (strlen($a->module)) {
  184. /**
  185. * We will always have a module name.
  186. * First see if we have an addon which is masquerading as a module.
  187. */
  188. // Compatibility with the Android Diaspora client
  189. if ($a->module == "stream") {
  190. $a->module = "network";
  191. }
  192. // Compatibility with the Firefox App
  193. if (($a->module == "users") && ($a->cmd == "users/sign_in")) {
  194. $a->module = "login";
  195. }
  196. $privateapps = Config::get('config', 'private_addons');
  197. if (is_array($a->addons) && in_array($a->module, $a->addons) && file_exists("addon/{$a->module}/{$a->module}.php")) {
  198. //Check if module is an app and if public access to apps is allowed or not
  199. if ((!local_user()) && Addon::isApp($a->module) && $privateapps === "1") {
  200. info(L10n::t("You must be logged in to use addons. "));
  201. } else {
  202. include_once "addon/{$a->module}/{$a->module}.php";
  203. if (function_exists($a->module . '_module')) {
  204. $a->module_loaded = true;
  205. }
  206. }
  207. }
  208. // Controller class routing
  209. if (! $a->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($a->module))) {
  210. $a->module_class = 'Friendica\\Module\\' . ucfirst($a->module);
  211. $a->module_loaded = true;
  212. }
  213. /**
  214. * If not, next look for a 'standard' program module in the 'mod' directory
  215. */
  216. if (! $a->module_loaded && file_exists("mod/{$a->module}.php")) {
  217. include_once "mod/{$a->module}.php";
  218. $a->module_loaded = true;
  219. }
  220. /**
  221. * The URL provided does not resolve to a valid module.
  222. *
  223. * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
  224. * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
  225. * we are going to trap this and redirect back to the requested page. As long as you don't have a critical error on your page
  226. * this will often succeed and eventually do the right thing.
  227. *
  228. * Otherwise we are going to emit a 404 not found.
  229. */
  230. if (! $a->module_loaded) {
  231. // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
  232. if ((x($_SERVER, 'QUERY_STRING')) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
  233. killme();
  234. }
  235. if ((x($_SERVER, 'QUERY_STRING')) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
  236. logger('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
  237. goaway(System::baseUrl() . $_SERVER['REQUEST_URI']);
  238. }
  239. logger('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], LOGGER_DEBUG);
  240. header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . L10n::t('Not Found'));
  241. $tpl = get_markup_template("404.tpl");
  242. $a->page['content'] = replace_macros(
  243. $tpl,
  244. [
  245. '$message' => L10n::t('Page not found.')]
  246. );
  247. }
  248. }
  249. /**
  250. * Load current theme info
  251. */
  252. $theme_info_file = "view/theme/".current_theme()."/theme.php";
  253. if (file_exists($theme_info_file)) {
  254. require_once $theme_info_file;
  255. }
  256. /* initialise content region */
  257. if (! x($a->page, 'content')) {
  258. $a->page['content'] = '';
  259. }
  260. if (!$install && !$maintenance) {
  261. Addon::callHooks('page_content_top', $a->page['content']);
  262. }
  263. /**
  264. * Call module functions
  265. */
  266. if ($a->module_loaded) {
  267. $a->page['page_title'] = $a->module;
  268. $placeholder = '';
  269. if ($a->module_class) {
  270. Addon::callHooks($a->module . '_mod_init', $placeholder);
  271. call_user_func([$a->module_class, 'init']);
  272. } else if (function_exists($a->module . '_init')) {
  273. Addon::callHooks($a->module . '_mod_init', $placeholder);
  274. $func = $a->module . '_init';
  275. $func($a);
  276. }
  277. if (function_exists(str_replace('-', '_', current_theme()) . '_init')) {
  278. $func = str_replace('-', '_', current_theme()) . '_init';
  279. $func($a);
  280. }
  281. if (! $a->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
  282. Addon::callHooks($a->module . '_mod_post', $_POST);
  283. if ($a->module_class) {
  284. call_user_func([$a->module_class, 'post']);
  285. } else if (function_exists($a->module . '_post')) {
  286. $func = $a->module . '_post';
  287. $func($a);
  288. }
  289. }
  290. if (! $a->error) {
  291. Addon::callHooks($a->module . '_mod_afterpost', $placeholder);
  292. if ($a->module_class) {
  293. call_user_func([$a->module_class, 'afterpost']);
  294. } else if (function_exists($a->module . '_afterpost')) {
  295. $func = $a->module . '_afterpost';
  296. $func($a);
  297. }
  298. }
  299. if (! $a->error) {
  300. $arr = ['content' => $a->page['content']];
  301. Addon::callHooks($a->module . '_mod_content', $arr);
  302. $a->page['content'] = $arr['content'];
  303. if ($a->module_class) {
  304. $arr = ['content' => call_user_func([$a->module_class, 'content'])];
  305. } else if (function_exists($a->module . '_content')) {
  306. $func = $a->module . '_content';
  307. $arr = ['content' => $func($a)];
  308. }
  309. Addon::callHooks($a->module . '_mod_aftercontent', $arr);
  310. $a->page['content'] .= $arr['content'];
  311. }
  312. if (function_exists(str_replace('-', '_', current_theme()) . '_content_loaded')) {
  313. $func = str_replace('-', '_', current_theme()) . '_content_loaded';
  314. $func($a);
  315. }
  316. }
  317. /*
  318. * Create the page head after setting the language
  319. * and getting any auth credentials.
  320. *
  321. * Moved init_pagehead() and init_page_end() to after
  322. * all the module functions have executed so that all
  323. * theme choices made by the modules can take effect.
  324. */
  325. $a->init_pagehead();
  326. /*
  327. * Build the page ending -- this is stuff that goes right before
  328. * the closing </body> tag
  329. */
  330. $a->init_page_end();
  331. // If you're just visiting, let javascript take you home
  332. if (x($_SESSION, 'visitor_home')) {
  333. $homebase = $_SESSION['visitor_home'];
  334. } elseif (local_user()) {
  335. $homebase = 'profile/' . $a->user['nickname'];
  336. }
  337. if (isset($homebase)) {
  338. $a->page['content'] .= '<script>var homebase="' . $homebase . '" ; </script>';
  339. }
  340. /*
  341. * now that we've been through the module content, see if the page reported
  342. * a permission problem and if so, a 403 response would seem to be in order.
  343. */
  344. if (stristr(implode("", $_SESSION['sysmsg']), L10n::t('Permission denied'))) {
  345. header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . L10n::t('Permission denied.'));
  346. }
  347. /*
  348. * Report anything which needs to be communicated in the notification area (before the main body)
  349. */
  350. Addon::callHooks('page_end', $a->page['content']);
  351. /*
  352. * Add the navigation (menu) template
  353. */
  354. if ($a->module != 'install' && $a->module != 'maintenance') {
  355. Nav::build($a);
  356. }
  357. /*
  358. * Add a "toggle mobile" link if we're using a mobile device
  359. */
  360. if ($a->is_mobile || $a->is_tablet) {
  361. if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
  362. $link = 'toggle_mobile?address=' . curPageURL();
  363. } else {
  364. $link = 'toggle_mobile?off=1&address=' . curPageURL();
  365. }
  366. $a->page['footer'] = replace_macros(
  367. get_markup_template("toggle_mobile_footer.tpl"),
  368. [
  369. '$toggle_link' => $link,
  370. '$toggle_text' => L10n::t('toggle mobile')]
  371. );
  372. }
  373. /**
  374. * Build the page - now that we have all the components
  375. */
  376. if (!$a->theme['stylesheet']) {
  377. $stylesheet = current_theme_url();
  378. } else {
  379. $stylesheet = $a->theme['stylesheet'];
  380. }
  381. $a->page['htmlhead'] = str_replace('{{$stylesheet}}', $stylesheet, $a->page['htmlhead']);
  382. //$a->page['htmlhead'] = replace_macros($a->page['htmlhead'], array('$stylesheet' => $stylesheet));
  383. if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
  384. $doc = new DOMDocument();
  385. $target = new DOMDocument();
  386. $target->loadXML("<root></root>");
  387. $content = mb_convert_encoding($a->page["content"], 'HTML-ENTITIES', "UTF-8");
  388. /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
  389. @$doc->loadHTML($content);
  390. $xpath = new DOMXPath($doc);
  391. $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
  392. foreach ($list as $item) {
  393. $item = $target->importNode($item, true);
  394. // And then append it to the target
  395. $target->documentElement->appendChild($item);
  396. }
  397. }
  398. if (isset($_GET["mode"]) && ($_GET["mode"] == "raw")) {
  399. header("Content-type: text/html; charset=utf-8");
  400. echo substr($target->saveHTML(), 6, -8);
  401. killme();
  402. }
  403. $page = $a->page;
  404. $profile = $a->profile;
  405. header("X-Friendica-Version: " . FRIENDICA_VERSION);
  406. header("Content-type: text/html; charset=utf-8");
  407. if (Config::get('system', 'hsts') && (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
  408. header("Strict-Transport-Security: max-age=31536000");
  409. }
  410. // Some security stuff
  411. header('X-Content-Type-Options: nosniff');
  412. header('X-XSS-Protection: 1; mode=block');
  413. header('X-Permitted-Cross-Domain-Policies: none');
  414. header('X-Frame-Options: sameorigin');
  415. // Things like embedded OSM maps don't work, when this is enabled
  416. // header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' https: data:; media-src 'self' https:; child-src 'self' https:; object-src 'none'");
  417. /*
  418. * We use $_GET["mode"] for special page templates. So we will check if we have
  419. * to load another page template than the default one.
  420. * The page templates are located in /view/php/ or in the theme directory.
  421. */
  422. if (isset($_GET["mode"])) {
  423. $template = Theme::getPathForFile($_GET["mode"] . '.php');
  424. }
  425. // If there is no page template use the default page template
  426. if (empty($template)) {
  427. $template = Theme::getPathForFile("default.php");
  428. }
  429. /// @TODO Looks unsafe (remote-inclusion), is maybe not but Theme::getPathForFile() uses file_exists() but does not escape anything
  430. require_once $template;
  431. killme();