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.

1604 lines
47KB

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