Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there)
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.

App.php 44KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  1. <?php
  2. /**
  3. * @file src/App.php
  4. */
  5. namespace Friendica;
  6. use Detection\MobileDetect;
  7. use DOMDocument;
  8. use DOMXPath;
  9. use Exception;
  10. use Friendica\Core\Config\Cache\ConfigCacheLoader;
  11. use Friendica\Core\Config\Cache\IConfigCache;
  12. use Friendica\Core\Config\Configuration;
  13. use Friendica\Database\DBA;
  14. use Friendica\Factory\ConfigFactory;
  15. use Friendica\Network\HTTPException\InternalServerErrorException;
  16. use Friendica\Util\Profiler;
  17. use Psr\Log\LoggerInterface;
  18. /**
  19. *
  20. * class: App
  21. *
  22. * @brief Our main application structure for the life of this page.
  23. *
  24. * Primarily deals with the URL that got us here
  25. * and tries to make some sense of it, and
  26. * stores our page contents and config storage
  27. * and anything else that might need to be passed around
  28. * before we spit the page out.
  29. *
  30. */
  31. class App
  32. {
  33. public $module_loaded = false;
  34. public $module_class = null;
  35. public $query_string = '';
  36. public $page = [];
  37. public $profile;
  38. public $profile_uid;
  39. public $user;
  40. public $cid;
  41. public $contact;
  42. public $contacts;
  43. public $page_contact;
  44. public $content;
  45. public $data = [];
  46. public $error = false;
  47. public $cmd = '';
  48. public $argv;
  49. public $argc;
  50. public $module;
  51. public $timezone;
  52. public $interactive = true;
  53. public $identities;
  54. public $is_mobile = false;
  55. public $is_tablet = false;
  56. public $theme_info = [];
  57. public $category;
  58. // Allow themes to control internal parameters
  59. // by changing App values in theme.php
  60. public $sourcename = '';
  61. public $videowidth = 425;
  62. public $videoheight = 350;
  63. public $force_max_items = 0;
  64. public $theme_events_in_profile = true;
  65. public $stylesheets = [];
  66. public $footerScripts = [];
  67. /**
  68. * @var App\Mode The Mode of the Application
  69. */
  70. private $mode;
  71. /**
  72. * @var string The App base path
  73. */
  74. private $basePath;
  75. /**
  76. * @var string The App URL path
  77. */
  78. private $urlPath;
  79. /**
  80. * @var bool true, if the call is from the Friendica APP, otherwise false
  81. */
  82. private $isFriendicaApp;
  83. /**
  84. * @var bool true, if the call is from an backend node (f.e. worker)
  85. */
  86. private $isBackend;
  87. /**
  88. * @var string The name of the current theme
  89. */
  90. private $currentTheme;
  91. /**
  92. * @var bool check if request was an AJAX (xmlhttprequest) request
  93. */
  94. private $isAjax;
  95. /**
  96. * @var MobileDetect
  97. */
  98. public $mobileDetect;
  99. /**
  100. * @var LoggerInterface The current logger of this App
  101. */
  102. private $logger;
  103. /**
  104. * @var Configuration The config
  105. */
  106. private $config;
  107. /**
  108. * @var Profiler The profiler of this app
  109. */
  110. private $profiler;
  111. /**
  112. * Returns the current config cache of this node
  113. *
  114. * @return IConfigCache
  115. */
  116. public function getConfigCache()
  117. {
  118. return $this->config->getCache();
  119. }
  120. /**
  121. * The basepath of this app
  122. *
  123. * @return string
  124. */
  125. public function getBasePath()
  126. {
  127. return $this->basePath;
  128. }
  129. /**
  130. * The profiler of this app
  131. *
  132. * @return Profiler
  133. */
  134. public function getProfiler()
  135. {
  136. return $this->profiler;
  137. }
  138. /**
  139. * Register a stylesheet file path to be included in the <head> tag of every page.
  140. * Inclusion is done in App->initHead().
  141. * The path can be absolute or relative to the Friendica installation base folder.
  142. *
  143. * @see initHead()
  144. *
  145. * @param string $path
  146. * @throws InternalServerErrorException
  147. */
  148. public function registerStylesheet($path)
  149. {
  150. $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
  151. $this->stylesheets[] = trim($url, '/');
  152. }
  153. /**
  154. * Register a javascript file path to be included in the <footer> tag of every page.
  155. * Inclusion is done in App->initFooter().
  156. * The path can be absolute or relative to the Friendica installation base folder.
  157. *
  158. * @see initFooter()
  159. *
  160. * @param string $path
  161. * @throws InternalServerErrorException
  162. */
  163. public function registerFooterScript($path)
  164. {
  165. $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
  166. $this->footerScripts[] = trim($url, '/');
  167. }
  168. public $process_id;
  169. public $queue;
  170. private $scheme;
  171. private $hostname;
  172. /**
  173. * @brief App constructor.
  174. *
  175. * @param Configuration $config The Configuration
  176. * @param LoggerInterface $logger Logger of this application
  177. * @param Profiler $profiler The profiler of this application
  178. * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
  179. *
  180. * @throws Exception if the Basepath is not usable
  181. */
  182. public function __construct(Configuration $config, LoggerInterface $logger, Profiler $profiler, $isBackend = true)
  183. {
  184. $this->config = $config;
  185. $this->logger = $logger;
  186. $this->profiler = $profiler;
  187. $this->basePath = $this->config->get('system', 'basepath');
  188. if (!Core\System::isDirectoryUsable($this->basePath, false)) {
  189. throw new Exception('Basepath ' . $this->basePath . ' isn\'t usable.');
  190. }
  191. $this->basePath = rtrim($this->basePath, DIRECTORY_SEPARATOR);
  192. BaseObject::setApp($this);
  193. $this->checkBackend($isBackend);
  194. $this->checkFriendicaApp();
  195. $this->profiler->reset();
  196. $this->mode = new App\Mode($this->basePath);
  197. $this->reload();
  198. set_time_limit(0);
  199. // This has to be quite large to deal with embedded private photos
  200. ini_set('pcre.backtrack_limit', 500000);
  201. $this->scheme = 'http';
  202. if (!empty($_SERVER['HTTPS']) ||
  203. !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
  204. !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
  205. !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
  206. !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
  207. !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
  208. ) {
  209. $this->scheme = 'https';
  210. }
  211. if (!empty($_SERVER['SERVER_NAME'])) {
  212. $this->hostname = $_SERVER['SERVER_NAME'];
  213. if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
  214. $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
  215. }
  216. }
  217. set_include_path(
  218. get_include_path() . PATH_SEPARATOR
  219. . $this->basePath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
  220. . $this->basePath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
  221. . $this->basePath);
  222. if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
  223. $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
  224. } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
  225. $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
  226. }
  227. // removing trailing / - maybe a nginx problem
  228. $this->query_string = ltrim($this->query_string, '/');
  229. if (!empty($_GET['pagename'])) {
  230. $this->cmd = trim($_GET['pagename'], '/\\');
  231. } elseif (!empty($_GET['q'])) {
  232. $this->cmd = trim($_GET['q'], '/\\');
  233. }
  234. // fix query_string
  235. $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
  236. // unix style "homedir"
  237. if (substr($this->cmd, 0, 1) === '~') {
  238. $this->cmd = 'profile/' . substr($this->cmd, 1);
  239. }
  240. // Diaspora style profile url
  241. if (substr($this->cmd, 0, 2) === 'u/') {
  242. $this->cmd = 'profile/' . substr($this->cmd, 2);
  243. }
  244. /*
  245. * Break the URL path into C style argc/argv style arguments for our
  246. * modules. Given "http://example.com/module/arg1/arg2", $this->argc
  247. * will be 3 (integer) and $this->argv will contain:
  248. * [0] => 'module'
  249. * [1] => 'arg1'
  250. * [2] => 'arg2'
  251. *
  252. *
  253. * There will always be one argument. If provided a naked domain
  254. * URL, $this->argv[0] is set to "home".
  255. */
  256. $this->argv = explode('/', $this->cmd);
  257. $this->argc = count($this->argv);
  258. if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
  259. $this->module = str_replace('.', '_', $this->argv[0]);
  260. $this->module = str_replace('-', '_', $this->module);
  261. } else {
  262. $this->argc = 1;
  263. $this->argv = ['home'];
  264. $this->module = 'home';
  265. }
  266. // Detect mobile devices
  267. $mobile_detect = new MobileDetect();
  268. $this->mobileDetect = $mobile_detect;
  269. $this->is_mobile = $mobile_detect->isMobile();
  270. $this->is_tablet = $mobile_detect->isTablet();
  271. $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
  272. // Register template engines
  273. Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
  274. }
  275. /**
  276. * Returns the Mode of the Application
  277. *
  278. * @return App\Mode The Application Mode
  279. *
  280. * @throws InternalServerErrorException when the mode isn't created
  281. */
  282. public function getMode()
  283. {
  284. if (empty($this->mode)) {
  285. throw new InternalServerErrorException('Mode of the Application is not defined');
  286. }
  287. return $this->mode;
  288. }
  289. /**
  290. * Returns the Logger of the Application
  291. *
  292. * @return LoggerInterface The Logger
  293. * @throws InternalServerErrorException when the logger isn't created
  294. */
  295. public function getLogger()
  296. {
  297. if (empty($this->logger)) {
  298. throw new InternalServerErrorException('Logger of the Application is not defined');
  299. }
  300. return $this->logger;
  301. }
  302. /**
  303. * Reloads the whole app instance
  304. */
  305. public function reload()
  306. {
  307. $this->getMode()->determine($this->basePath);
  308. $this->determineURLPath();
  309. if ($this->getMode()->has(App\Mode::DBCONFIGAVAILABLE)) {
  310. Core\Config::load();
  311. }
  312. // again because DB-config could change the config
  313. $this->getMode()->determine($this->basePath);
  314. if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
  315. Core\Hook::loadHooks();
  316. $loader = new ConfigCacheLoader($this->basePath);
  317. Core\Hook::callAll('load_config', $loader);
  318. $this->config->getCache()->load($loader->loadCoreConfig('addon'), true);
  319. }
  320. $this->loadDefaultTimezone();
  321. Core\L10n::init();
  322. $this->process_id = Core\System::processID('log');
  323. Core\Logger::setLogger($this->logger);
  324. }
  325. /**
  326. * Loads the default timezone
  327. *
  328. * Include support for legacy $default_timezone
  329. *
  330. * @global string $default_timezone
  331. */
  332. private function loadDefaultTimezone()
  333. {
  334. if ($this->config->get('system', 'default_timezone')) {
  335. $this->timezone = $this->config->get('system', 'default_timezone');
  336. } else {
  337. global $default_timezone;
  338. $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
  339. }
  340. if ($this->timezone) {
  341. date_default_timezone_set($this->timezone);
  342. }
  343. }
  344. /**
  345. * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
  346. */
  347. private function determineURLPath()
  348. {
  349. /* Relative script path to the web server root
  350. * Not all of those $_SERVER properties can be present, so we do by inverse priority order
  351. */
  352. $relative_script_path = '';
  353. $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
  354. $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
  355. $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
  356. $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
  357. $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path);
  358. $this->urlPath = $this->config->get('system', 'urlpath');
  359. /* $relative_script_path gives /relative/path/to/friendica/module/parameter
  360. * QUERY_STRING gives pagename=module/parameter
  361. *
  362. * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
  363. */
  364. if (!empty($relative_script_path)) {
  365. // Module
  366. if (!empty($_SERVER['QUERY_STRING'])) {
  367. $path = trim(rdirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
  368. } else {
  369. // Root page
  370. $path = trim($relative_script_path, '/');
  371. }
  372. if ($path && $path != $this->urlPath) {
  373. $this->urlPath = $path;
  374. }
  375. }
  376. }
  377. public function getScheme()
  378. {
  379. return $this->scheme;
  380. }
  381. /**
  382. * @brief Retrieves the Friendica instance base URL
  383. *
  384. * This function assembles the base URL from multiple parts:
  385. * - Protocol is determined either by the request or a combination of
  386. * system.ssl_policy and the $ssl parameter.
  387. * - Host name is determined either by system.hostname or inferred from request
  388. * - Path is inferred from SCRIPT_NAME
  389. *
  390. * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
  391. *
  392. * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
  393. * @return string Friendica server base URL
  394. * @throws InternalServerErrorException
  395. */
  396. public function getBaseURL($ssl = false)
  397. {
  398. $scheme = $this->scheme;
  399. if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
  400. $scheme = 'https';
  401. }
  402. // Basically, we have $ssl = true on any links which can only be seen by a logged in user
  403. // (and also the login link). Anything seen by an outsider will have it turned off.
  404. if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
  405. if ($ssl) {
  406. $scheme = 'https';
  407. } else {
  408. $scheme = 'http';
  409. }
  410. }
  411. if (Core\Config::get('config', 'hostname') != '') {
  412. $this->hostname = Core\Config::get('config', 'hostname');
  413. }
  414. return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
  415. }
  416. /**
  417. * @brief Initializes the baseurl components
  418. *
  419. * Clears the baseurl cache to prevent inconsistencies
  420. *
  421. * @param string $url
  422. * @throws InternalServerErrorException
  423. */
  424. public function setBaseURL($url)
  425. {
  426. $parsed = @parse_url($url);
  427. $hostname = '';
  428. if (!empty($parsed)) {
  429. if (!empty($parsed['scheme'])) {
  430. $this->scheme = $parsed['scheme'];
  431. }
  432. if (!empty($parsed['host'])) {
  433. $hostname = $parsed['host'];
  434. }
  435. if (!empty($parsed['port'])) {
  436. $hostname .= ':' . $parsed['port'];
  437. }
  438. if (!empty($parsed['path'])) {
  439. $this->urlPath = trim($parsed['path'], '\\/');
  440. }
  441. if (file_exists($this->basePath . '/.htpreconfig.php')) {
  442. include $this->basePath . '/.htpreconfig.php';
  443. }
  444. if (Core\Config::get('config', 'hostname') != '') {
  445. $this->hostname = Core\Config::get('config', 'hostname');
  446. }
  447. if (!isset($this->hostname) || ($this->hostname == '')) {
  448. $this->hostname = $hostname;
  449. }
  450. }
  451. }
  452. public function getHostName()
  453. {
  454. if (Core\Config::get('config', 'hostname') != '') {
  455. $this->hostname = Core\Config::get('config', 'hostname');
  456. }
  457. return $this->hostname;
  458. }
  459. public function getURLPath()
  460. {
  461. return $this->urlPath;
  462. }
  463. /**
  464. * Initializes App->page['htmlhead'].
  465. *
  466. * Includes:
  467. * - Page title
  468. * - Favicons
  469. * - Registered stylesheets (through App->registerStylesheet())
  470. * - Infinite scroll data
  471. * - head.tpl template
  472. */
  473. public function initHead()
  474. {
  475. $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
  476. // If the update is 'deactivated' set it to the highest integer number (~24 days)
  477. if ($interval < 0) {
  478. $interval = 2147483647;
  479. }
  480. if ($interval < 10000) {
  481. $interval = 40000;
  482. }
  483. // compose the page title from the sitename and the
  484. // current module called
  485. if (!$this->module == '') {
  486. $this->page['title'] = $this->config->get('config', 'sitename') . ' (' . $this->module . ')';
  487. } else {
  488. $this->page['title'] = $this->config->get('config', 'sitename');
  489. }
  490. if (!empty(Core\Renderer::$theme['stylesheet'])) {
  491. $stylesheet = Core\Renderer::$theme['stylesheet'];
  492. } else {
  493. $stylesheet = $this->getCurrentThemeStylesheetPath();
  494. }
  495. $this->registerStylesheet($stylesheet);
  496. $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
  497. if ($shortcut_icon == '') {
  498. $shortcut_icon = 'images/friendica-32.png';
  499. }
  500. $touch_icon = Core\Config::get('system', 'touch_icon');
  501. if ($touch_icon == '') {
  502. $touch_icon = 'images/friendica-128.png';
  503. }
  504. Core\Hook::callAll('head', $this->page['htmlhead']);
  505. $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
  506. /* put the head template at the beginning of page['htmlhead']
  507. * since the code added by the modules frequently depends on it
  508. * being first
  509. */
  510. $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
  511. '$baseurl' => $this->getBaseURL(),
  512. '$local_user' => local_user(),
  513. '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
  514. '$delitem' => Core\L10n::t('Delete this item?'),
  515. '$showmore' => Core\L10n::t('show more'),
  516. '$showfewer' => Core\L10n::t('show fewer'),
  517. '$update_interval' => $interval,
  518. '$shortcut_icon' => $shortcut_icon,
  519. '$touch_icon' => $touch_icon,
  520. '$block_public' => intval(Core\Config::get('system', 'block_public')),
  521. '$stylesheets' => $this->stylesheets,
  522. ]) . $this->page['htmlhead'];
  523. }
  524. /**
  525. * Initializes App->page['footer'].
  526. *
  527. * Includes:
  528. * - Javascript homebase
  529. * - Mobile toggle link
  530. * - Registered footer scripts (through App->registerFooterScript())
  531. * - footer.tpl template
  532. */
  533. public function initFooter()
  534. {
  535. // If you're just visiting, let javascript take you home
  536. if (!empty($_SESSION['visitor_home'])) {
  537. $homebase = $_SESSION['visitor_home'];
  538. } elseif (local_user()) {
  539. $homebase = 'profile/' . $this->user['nickname'];
  540. }
  541. if (isset($homebase)) {
  542. $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
  543. }
  544. /*
  545. * Add a "toggle mobile" link if we're using a mobile device
  546. */
  547. if ($this->is_mobile || $this->is_tablet) {
  548. if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
  549. $link = 'toggle_mobile?address=' . urlencode(curPageURL());
  550. } else {
  551. $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
  552. }
  553. $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
  554. '$toggle_link' => $link,
  555. '$toggle_text' => Core\L10n::t('toggle mobile')
  556. ]);
  557. }
  558. Core\Hook::callAll('footer', $this->page['footer']);
  559. $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
  560. $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
  561. '$baseurl' => $this->getBaseURL(),
  562. '$footerScripts' => $this->footerScripts,
  563. ]) . $this->page['footer'];
  564. }
  565. /**
  566. * @brief Removes the base url from an url. This avoids some mixed content problems.
  567. *
  568. * @param string $origURL
  569. *
  570. * @return string The cleaned url
  571. * @throws InternalServerErrorException
  572. */
  573. public function removeBaseURL($origURL)
  574. {
  575. // Remove the hostname from the url if it is an internal link
  576. $nurl = Util\Strings::normaliseLink($origURL);
  577. $base = Util\Strings::normaliseLink($this->getBaseURL());
  578. $url = str_replace($base . '/', '', $nurl);
  579. // if it is an external link return the orignal value
  580. if ($url == Util\Strings::normaliseLink($origURL)) {
  581. return $origURL;
  582. } else {
  583. return $url;
  584. }
  585. }
  586. /**
  587. * Returns the current UserAgent as a String
  588. *
  589. * @return string the UserAgent as a String
  590. * @throws InternalServerErrorException
  591. */
  592. public function getUserAgent()
  593. {
  594. return
  595. FRIENDICA_PLATFORM . " '" .
  596. FRIENDICA_CODENAME . "' " .
  597. FRIENDICA_VERSION . '-' .
  598. DB_UPDATE_VERSION . '; ' .
  599. $this->getBaseURL();
  600. }
  601. /**
  602. * Checks, if the call is from the Friendica App
  603. *
  604. * Reason:
  605. * The friendica client has problems with the GUID in the notify. this is some workaround
  606. */
  607. private function checkFriendicaApp()
  608. {
  609. // Friendica-Client
  610. $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
  611. }
  612. /**
  613. * Is the call via the Friendica app? (not a "normale" call)
  614. *
  615. * @return bool true if it's from the Friendica app
  616. */
  617. public function isFriendicaApp()
  618. {
  619. return $this->isFriendicaApp;
  620. }
  621. /**
  622. * @brief Checks if the site is called via a backend process
  623. *
  624. * This isn't a perfect solution. But we need this check very early.
  625. * So we cannot wait until the modules are loaded.
  626. *
  627. * @param string $backend true, if the backend flag was set during App initialization
  628. *
  629. */
  630. private function checkBackend($backend) {
  631. static $backends = [
  632. '_well_known',
  633. 'api',
  634. 'dfrn_notify',
  635. 'fetch',
  636. 'hcard',
  637. 'hostxrd',
  638. 'nodeinfo',
  639. 'noscrape',
  640. 'p',
  641. 'poco',
  642. 'post',
  643. 'proxy',
  644. 'pubsub',
  645. 'pubsubhubbub',
  646. 'receive',
  647. 'rsd_xml',
  648. 'salmon',
  649. 'statistics_json',
  650. 'xrd',
  651. ];
  652. // Check if current module is in backend or backend flag is set
  653. $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
  654. }
  655. /**
  656. * Returns true, if the call is from a backend node (f.e. from a worker)
  657. *
  658. * @return bool Is it a known backend?
  659. */
  660. public function isBackend()
  661. {
  662. return $this->isBackend;
  663. }
  664. /**
  665. * @brief Checks if the maximum number of database processes is reached
  666. *
  667. * @return bool Is the limit reached?
  668. */
  669. public function isMaxProcessesReached()
  670. {
  671. // Deactivated, needs more investigating if this check really makes sense
  672. return false;
  673. /*
  674. * Commented out to suppress static analyzer issues
  675. *
  676. if ($this->is_backend()) {
  677. $process = 'backend';
  678. $max_processes = Core\Config::get('system', 'max_processes_backend');
  679. if (intval($max_processes) == 0) {
  680. $max_processes = 5;
  681. }
  682. } else {
  683. $process = 'frontend';
  684. $max_processes = Core\Config::get('system', 'max_processes_frontend');
  685. if (intval($max_processes) == 0) {
  686. $max_processes = 20;
  687. }
  688. }
  689. $processlist = DBA::processlist();
  690. if ($processlist['list'] != '') {
  691. Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
  692. if ($processlist['amount'] > $max_processes) {
  693. Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
  694. return true;
  695. }
  696. }
  697. return false;
  698. */
  699. }
  700. /**
  701. * @brief Checks if the minimal memory is reached
  702. *
  703. * @return bool Is the memory limit reached?
  704. * @throws InternalServerErrorException
  705. */
  706. public function isMinMemoryReached()
  707. {
  708. $min_memory = Core\Config::get('system', 'min_memory', 0);
  709. if ($min_memory == 0) {
  710. return false;
  711. }
  712. if (!is_readable('/proc/meminfo')) {
  713. return false;
  714. }
  715. $memdata = explode("\n", file_get_contents('/proc/meminfo'));
  716. $meminfo = [];
  717. foreach ($memdata as $line) {
  718. $data = explode(':', $line);
  719. if (count($data) != 2) {
  720. continue;
  721. }
  722. list($key, $val) = $data;
  723. $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
  724. $meminfo[$key] = (int) ($meminfo[$key] / 1024);
  725. }
  726. if (!isset($meminfo['MemFree'])) {
  727. return false;
  728. }
  729. $free = $meminfo['MemFree'];
  730. $reached = ($free < $min_memory);
  731. if ($reached) {
  732. Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
  733. }
  734. return $reached;
  735. }
  736. /**
  737. * @brief Checks if the maximum load is reached
  738. *
  739. * @return bool Is the load reached?
  740. * @throws InternalServerErrorException
  741. */
  742. public function isMaxLoadReached()
  743. {
  744. if ($this->isBackend()) {
  745. $process = 'backend';
  746. $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
  747. if ($maxsysload < 1) {
  748. $maxsysload = 50;
  749. }
  750. } else {
  751. $process = 'frontend';
  752. $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
  753. if ($maxsysload < 1) {
  754. $maxsysload = 50;
  755. }
  756. }
  757. $load = Core\System::currentLoad();
  758. if ($load) {
  759. if (intval($load) > $maxsysload) {
  760. Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
  761. return true;
  762. }
  763. }
  764. return false;
  765. }
  766. /**
  767. * Executes a child process with 'proc_open'
  768. *
  769. * @param string $command The command to execute
  770. * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
  771. * @throws InternalServerErrorException
  772. */
  773. public function proc_run($command, $args)
  774. {
  775. if (!function_exists('proc_open')) {
  776. return;
  777. }
  778. $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
  779. foreach ($args as $key => $value) {
  780. if (!is_null($value) && is_bool($value) && !$value) {
  781. continue;
  782. }
  783. $cmdline .= ' --' . $key;
  784. if (!is_null($value) && !is_bool($value)) {
  785. $cmdline .= ' ' . $value;
  786. }
  787. }
  788. if ($this->isMinMemoryReached()) {
  789. return;
  790. }
  791. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  792. $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->basePath);
  793. } else {
  794. $resource = proc_open($cmdline . ' &', [], $foo, $this->basePath);
  795. }
  796. if (!is_resource($resource)) {
  797. Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
  798. return;
  799. }
  800. proc_close($resource);
  801. }
  802. /**
  803. * Generates the site's default sender email address
  804. *
  805. * @return string
  806. * @throws InternalServerErrorException
  807. */
  808. public function getSenderEmailAddress()
  809. {
  810. $sender_email = Core\Config::get('config', 'sender_email');
  811. if (empty($sender_email)) {
  812. $hostname = $this->getHostName();
  813. if (strpos($hostname, ':')) {
  814. $hostname = substr($hostname, 0, strpos($hostname, ':'));
  815. }
  816. $sender_email = 'noreply@' . $hostname;
  817. }
  818. return $sender_email;
  819. }
  820. /**
  821. * Returns the current theme name.
  822. *
  823. * @return string the name of the current theme
  824. * @throws InternalServerErrorException
  825. */
  826. public function getCurrentTheme()
  827. {
  828. if ($this->getMode()->isInstall()) {
  829. return '';
  830. }
  831. if (!$this->currentTheme) {
  832. $this->computeCurrentTheme();
  833. }
  834. return $this->currentTheme;
  835. }
  836. public function setCurrentTheme($theme)
  837. {
  838. $this->currentTheme = $theme;
  839. }
  840. /**
  841. * Computes the current theme name based on the node settings, the user settings and the device type
  842. *
  843. * @throws Exception
  844. */
  845. private function computeCurrentTheme()
  846. {
  847. $system_theme = Core\Config::get('system', 'theme');
  848. if (!$system_theme) {
  849. throw new Exception(Core\L10n::t('No system theme config value set.'));
  850. }
  851. // Sane default
  852. $this->currentTheme = $system_theme;
  853. $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
  854. $page_theme = null;
  855. // Find the theme that belongs to the user whose stuff we are looking at
  856. if ($this->profile_uid && ($this->profile_uid != local_user())) {
  857. // Allow folks to override user themes and always use their own on their own site.
  858. // This works only if the user is on the same server
  859. $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
  860. if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
  861. $page_theme = $user['theme'];
  862. }
  863. }
  864. $user_theme = Core\Session::get('theme', $system_theme);
  865. // Specific mobile theme override
  866. if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
  867. $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
  868. $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
  869. // --- means same mobile theme as desktop
  870. if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
  871. $user_theme = $user_mobile_theme;
  872. }
  873. }
  874. if ($page_theme) {
  875. $theme_name = $page_theme;
  876. } else {
  877. $theme_name = $user_theme;
  878. }
  879. if ($theme_name
  880. && in_array($theme_name, $allowed_themes)
  881. && (file_exists('view/theme/' . $theme_name . '/style.css')
  882. || file_exists('view/theme/' . $theme_name . '/style.php'))
  883. ) {
  884. $this->currentTheme = $theme_name;
  885. }
  886. }
  887. /**
  888. * @brief Return full URL to theme which is currently in effect.
  889. *
  890. * Provide a sane default if nothing is chosen or the specified theme does not exist.
  891. *
  892. * @return string
  893. * @throws InternalServerErrorException
  894. */
  895. public function getCurrentThemeStylesheetPath()
  896. {
  897. return Core\Theme::getStylesheetPath($this->getCurrentTheme());
  898. }
  899. /**
  900. * Check if request was an AJAX (xmlhttprequest) request.
  901. *
  902. * @return boolean true if it was an AJAX request
  903. */
  904. public function isAjax()
  905. {
  906. return $this->isAjax;
  907. }
  908. /**
  909. * Returns the value of a argv key
  910. * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
  911. *
  912. * @param int $position the position of the argument
  913. * @param mixed $default the default value if not found
  914. *
  915. * @return mixed returns the value of the argument
  916. */
  917. public function getArgumentValue($position, $default = '')
  918. {
  919. if (array_key_exists($position, $this->argv)) {
  920. return $this->argv[$position];
  921. }
  922. return $default;
  923. }
  924. /**
  925. * Sets the base url for use in cmdline programs which don't have
  926. * $_SERVER variables
  927. */
  928. public function checkURL()
  929. {
  930. $url = Core\Config::get('system', 'url');
  931. // if the url isn't set or the stored url is radically different
  932. // than the currently visited url, store the current value accordingly.
  933. // "Radically different" ignores common variations such as http vs https
  934. // and www.example.com vs example.com.
  935. // We will only change the url to an ip address if there is no existing setting
  936. if (empty($url) || (!Util\Strings::compareLink($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->getHostName()))) {
  937. Core\Config::set('system', 'url', $this->getBaseURL());
  938. }
  939. }
  940. /**
  941. * Frontend App script
  942. *
  943. * The App object behaves like a container and a dispatcher at the same time, including a representation of the
  944. * request and a representation of the response.
  945. *
  946. * This probably should change to limit the size of this monster method.
  947. */
  948. public function runFrontend()
  949. {
  950. // Missing DB connection: ERROR
  951. if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
  952. Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
  953. }
  954. // Max Load Average reached: ERROR
  955. if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
  956. header('Retry-After: 120');
  957. header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
  958. Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
  959. }
  960. if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
  961. Core\System::httpExit(404);
  962. }
  963. if (!$this->getMode()->isInstall()) {
  964. // Force SSL redirection
  965. if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
  966. && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
  967. && strpos($this->getBaseURL(), 'https://') === 0
  968. && $_SERVER['REQUEST_METHOD'] == 'GET') {
  969. header('HTTP/1.1 302 Moved Temporarily');
  970. header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
  971. exit();
  972. }
  973. Core\Session::init();
  974. Core\Hook::callAll('init_1');
  975. }
  976. // Exclude the backend processes from the session management
  977. if (!$this->isBackend()) {
  978. $stamp1 = microtime(true);
  979. session_start();
  980. $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
  981. Core\L10n::setSessionVariable();
  982. Core\L10n::setLangFromSession();
  983. } else {
  984. $_SESSION = [];
  985. Core\Worker::executeIfIdle();
  986. }
  987. // ZRL
  988. if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
  989. $this->query_string = Model\Profile::stripZrls($this->query_string);
  990. if (!local_user()) {
  991. // Only continue when the given profile link seems valid
  992. // Valid profile links contain a path with "/profile/" and no query parameters
  993. if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
  994. strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
  995. if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
  996. $_SESSION['my_url'] = $_GET['zrl'];
  997. $_SESSION['authenticated'] = 0;
  998. }
  999. Model\Profile::zrlInit($this);
  1000. } else {
  1001. // Someone came with an invalid parameter, maybe as a DDoS attempt
  1002. // We simply stop processing here
  1003. Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
  1004. Core\System::httpExit(403, ['title' => '403 Forbidden']);
  1005. }
  1006. }
  1007. }
  1008. if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
  1009. $token = $_GET['owt'];
  1010. $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
  1011. Model\Profile::openWebAuthInit($token);
  1012. }
  1013. Module\Login::sessionAuth();
  1014. if (empty($_SESSION['authenticated'])) {
  1015. header('X-Account-Management-Status: none');
  1016. }
  1017. $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
  1018. $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
  1019. $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
  1020. /*
  1021. * check_config() is responsible for running update scripts. These automatically
  1022. * update the DB schema whenever we push a new one out. It also checks to see if
  1023. * any addons have been added or removed and reacts accordingly.
  1024. */
  1025. // in install mode, any url loads install module
  1026. // but we need "view" module for stylesheet
  1027. if ($this->getMode()->isInstall() && $this->module != 'view') {
  1028. $this->module = 'install';
  1029. } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
  1030. $this->module = 'maintenance';
  1031. } else {
  1032. $this->checkURL();
  1033. Core\Update::check($this->basePath, false);
  1034. Core\Addon::loadAddons();
  1035. Core\Hook::loadHooks();
  1036. }
  1037. $this->page = [
  1038. 'aside' => '',
  1039. 'bottom' => '',
  1040. 'content' => '',
  1041. 'footer' => '',
  1042. 'htmlhead' => '',
  1043. 'nav' => '',
  1044. 'page_title' => '',
  1045. 'right_aside' => '',
  1046. 'template' => '',
  1047. 'title' => ''
  1048. ];
  1049. if (strlen($this->module)) {
  1050. // Compatibility with the Android Diaspora client
  1051. if ($this->module == 'stream') {
  1052. $this->internalRedirect('network?f=&order=post');
  1053. }
  1054. if ($this->module == 'conversations') {
  1055. $this->internalRedirect('message');
  1056. }
  1057. if ($this->module == 'commented') {
  1058. $this->internalRedirect('network?f=&order=comment');
  1059. }
  1060. if ($this->module == 'liked') {
  1061. $this->internalRedirect('network?f=&order=comment');
  1062. }
  1063. if ($this->module == 'activity') {
  1064. $this->internalRedirect('network/?f=&conv=1');
  1065. }
  1066. if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
  1067. $this->internalRedirect('bookmarklet');
  1068. }
  1069. if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
  1070. $this->internalRedirect('settings');
  1071. }
  1072. if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
  1073. $this->internalRedirect('search');
  1074. }
  1075. // Compatibility with the Firefox App
  1076. if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
  1077. $this->module = "login";
  1078. }
  1079. $privateapps = Core\Config::get('config', 'private_addons', false);
  1080. if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
  1081. //Check if module is an app and if public access to apps is allowed or not
  1082. if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
  1083. info(Core\L10n::t("You must be logged in to use addons. "));
  1084. } else {
  1085. include_once "addon/{$this->module}/{$this->module}.php";
  1086. if (function_exists($this->module . '_module')) {
  1087. LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
  1088. $this->module_class = 'Friendica\\LegacyModule';
  1089. $this->module_loaded = true;
  1090. }
  1091. }
  1092. }
  1093. // Controller class routing
  1094. if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
  1095. $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
  1096. $this->module_loaded = true;
  1097. }
  1098. /* If not, next look for a 'standard' program module in the 'mod' directory
  1099. * We emulate a Module class through the LegacyModule class
  1100. */
  1101. if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
  1102. LegacyModule::setModuleFile("mod/{$this->module}.php");
  1103. $this->module_class = 'Friendica\\LegacyModule';
  1104. $this->module_loaded = true;
  1105. }
  1106. /* The URL provided does not resolve to a valid module.
  1107. *
  1108. * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
  1109. * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
  1110. * 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
  1111. * this will often succeed and eventually do the right thing.
  1112. *
  1113. * Otherwise we are going to emit a 404 not found.
  1114. */
  1115. if (! $this->module_loaded) {
  1116. // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
  1117. if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
  1118. exit();
  1119. }
  1120. if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
  1121. Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
  1122. $this->internalRedirect($_SERVER['REQUEST_URI']);
  1123. }
  1124. Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
  1125. header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
  1126. $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
  1127. $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
  1128. '$message' => Core\L10n::t('Page not found.')
  1129. ]);
  1130. }
  1131. }
  1132. $content = '';
  1133. // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
  1134. if ($this->module_loaded) {
  1135. $this->page['page_title'] = $this->module;
  1136. $placeholder = '';
  1137. Core\Hook::callAll($this->module . '_mod_init', $placeholder);
  1138. call_user_func([$this->module_class, 'init']);
  1139. // "rawContent" is especially meant for technical endpoints.
  1140. // This endpoint doesn't need any theme initialization or other comparable stuff.
  1141. if (!$this->error) {
  1142. call_user_func([$this->module_class, 'rawContent']);
  1143. }
  1144. }
  1145. // Load current theme info after module has been initialized as theme could have been set in module
  1146. $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
  1147. if (file_exists($theme_info_file)) {
  1148. require_once $theme_info_file;
  1149. }
  1150. if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
  1151. $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
  1152. $func($this);
  1153. }
  1154. if ($this->module_loaded) {
  1155. if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
  1156. Core\Hook::callAll($this->module . '_mod_post', $_POST);
  1157. call_user_func([$this->module_class, 'post']);
  1158. }
  1159. if (! $this->error) {
  1160. Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
  1161. call_user_func([$this->module_class, 'afterpost']);
  1162. }
  1163. if (! $this->error) {
  1164. $arr = ['content' => $content];
  1165. Core\Hook::callAll($this->module . '_mod_content', $arr);
  1166. $content = $arr['content'];
  1167. $arr = ['content' => call_user_func([$this->module_class, 'content'])];
  1168. Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
  1169. $content .= $arr['content'];
  1170. }
  1171. }
  1172. // initialise content region
  1173. if ($this->getMode()->isNormal()) {
  1174. Core\Hook::callAll('page_content_top', $this->page['content']);
  1175. }
  1176. $this->page['content'] .= $content;
  1177. /* Create the page head after setting the language
  1178. * and getting any auth credentials.
  1179. *
  1180. * Moved initHead() and initFooter() to after
  1181. * all the module functions have executed so that all
  1182. * theme choices made by the modules can take effect.
  1183. */
  1184. $this->initHead();
  1185. /* Build the page ending -- this is stuff that goes right before
  1186. * the closing </body> tag
  1187. */
  1188. $this->initFooter();
  1189. /* now that we've been through the module content, see if the page reported
  1190. * a permission problem and if so, a 403 response would seem to be in order.
  1191. */
  1192. if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
  1193. header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
  1194. }
  1195. // Report anything which needs to be communicated in the notification area (before the main body)
  1196. Core\Hook::callAll('page_end', $this->page['content']);
  1197. // Add the navigation (menu) template
  1198. if ($this->module != 'install' && $this->module != 'maintenance') {
  1199. $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
  1200. $this->page['nav'] = Content\Nav::build($this);
  1201. }
  1202. // Build the page - now that we have all the components
  1203. if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
  1204. $doc = new DOMDocument();
  1205. $target = new DOMDocument();
  1206. $target->loadXML("<root></root>");
  1207. $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
  1208. /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
  1209. @$doc->loadHTML($content);
  1210. $xpath = new DOMXPath($doc);
  1211. $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
  1212. foreach ($list as $item) {
  1213. $item = $target->importNode($item, true);
  1214. // And then append it to the target
  1215. $target->documentElement->appendChild($item);
  1216. }
  1217. if ($_GET["mode"] == "raw") {
  1218. header("Content-type: text/html; charset=utf-8");
  1219. echo substr($target->saveHTML(), 6, -8);
  1220. exit();
  1221. }
  1222. }
  1223. $page = $this->page;
  1224. $profile = $this->profile;
  1225. header("X-Friendica-Version: " . FRIENDICA_VERSION);
  1226. header("Content-type: text/html; charset=utf-8");
  1227. if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
  1228. header("Strict-Transport-Security: max-age=31536000");
  1229. }
  1230. // Some security stuff
  1231. header('X-Content-Type-Options: nosniff');
  1232. header('X-XSS-Protection: 1; mode=block');
  1233. header('X-Permitted-Cross-Domain-Policies: none');
  1234. header('X-Frame-Options: sameorigin');
  1235. // Things like embedded OSM maps don't work, when this is enabled
  1236. // 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'");
  1237. /* We use $_GET["mode"] for special page templates. So we will check if we have
  1238. * to load another page template than the default one.
  1239. * The page templates are located in /view/php/ or in the theme directory.
  1240. */
  1241. if (isset($_GET["mode"])) {
  1242. $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
  1243. }
  1244. // If there is no page template use the default page template
  1245. if (empty($template)) {
  1246. $template = Core\Theme::getPathForFile("default.php");
  1247. }
  1248. // Theme templates expect $a as an App instance
  1249. $a = $this;
  1250. // Used as is in view/php/default.php
  1251. $lang = Core\L10n::getCurrentLang();
  1252. /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
  1253. require_once $template;
  1254. }
  1255. /**
  1256. * Redirects to another module relative to the current Friendica base.
  1257. * If you want to redirect to a external URL, use System::externalRedirectTo()
  1258. *
  1259. * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
  1260. * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
  1261. *
  1262. * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
  1263. */
  1264. public function internalRedirect($toUrl = '', $ssl = false)
  1265. {
  1266. if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
  1267. throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
  1268. }
  1269. $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
  1270. Core\System::externalRedirect($redirectTo);
  1271. }
  1272. /**
  1273. * Automatically redirects to relative or absolute URL
  1274. * Should only be used if it isn't clear if the URL is either internal or external
  1275. *
  1276. * @param string $toUrl The target URL
  1277. * @throws InternalServerErrorException
  1278. */
  1279. public function redirect($toUrl)
  1280. {
  1281. if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
  1282. Core\System::externalRedirect($toUrl);
  1283. } else {
  1284. $this->internalRedirect($toUrl);
  1285. }
  1286. }
  1287. }