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.

1484 lines
43KB

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