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.

1564 lines
45 KiB

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