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.

507 lines
14KB

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