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.

477 lines
14KB

  1. <?php
  2. namespace Friendica\App;
  3. use ArrayAccess;
  4. use DOMDocument;
  5. use DOMXPath;
  6. use Friendica\App;
  7. use Friendica\Content\Nav;
  8. use Friendica\Core\Config\Configuration;
  9. use Friendica\Core\Config\PConfiguration;
  10. use Friendica\Core\Hook;
  11. use Friendica\Core\L10n\L10n;
  12. use Friendica\Core\Renderer;
  13. use Friendica\Core\Theme;
  14. use Friendica\Module\Special\HTTPException as ModuleHTTPException;
  15. use Friendica\Network\HTTPException;
  16. /**
  17. * Contains the page specific environment variables for the current Page
  18. * - Contains all stylesheets
  19. * - Contains all footer-scripts
  20. * - Contains all page specific content (header, footer, content, ...)
  21. *
  22. * The run() method is the single point where the page will get printed to the screen
  23. */
  24. class Page implements ArrayAccess
  25. {
  26. /**
  27. * @var array Contains all stylesheets, which should get loaded during page
  28. */
  29. private $stylesheets;
  30. /**
  31. * @var array Contains all scripts, which are added to the footer at last
  32. */
  33. private $footerScripts;
  34. /**
  35. * @var array The page content, which are showed directly
  36. */
  37. private $page;
  38. /**
  39. * @var string The basepath of the page
  40. */
  41. private $basePath;
  42. /**
  43. * @param string $basepath The Page basepath
  44. */
  45. public function __construct(string $basepath)
  46. {
  47. $this->basePath = $basepath;
  48. $this->page = [
  49. 'aside' => '',
  50. 'bottom' => '',
  51. 'content' => '',
  52. 'footer' => '',
  53. 'htmlhead' => '',
  54. 'nav' => '',
  55. 'page_title' => '',
  56. 'right_aside' => '',
  57. 'template' => '',
  58. 'title' => ''
  59. ];
  60. }
  61. /**
  62. * Whether a offset exists
  63. *
  64. * @link https://php.net/manual/en/arrayaccess.offsetexists.php
  65. *
  66. * @param mixed $offset <p>
  67. * An offset to check for.
  68. * </p>
  69. *
  70. * @return boolean true on success or false on failure.
  71. * </p>
  72. * <p>
  73. * The return value will be casted to boolean if non-boolean was returned.
  74. * @since 5.0.0
  75. */
  76. public function offsetExists($offset)
  77. {
  78. return isset($this->page[$offset]);
  79. }
  80. /**
  81. * Offset to retrieve
  82. *
  83. * @link https://php.net/manual/en/arrayaccess.offsetget.php
  84. *
  85. * @param mixed $offset <p>
  86. * The offset to retrieve.
  87. * </p>
  88. *
  89. * @return mixed Can return all value types.
  90. * @since 5.0.0
  91. */
  92. public function offsetGet($offset)
  93. {
  94. return $this->page[$offset] ?? null;
  95. }
  96. /**
  97. * Offset to set
  98. *
  99. * @link https://php.net/manual/en/arrayaccess.offsetset.php
  100. *
  101. * @param mixed $offset <p>
  102. * The offset to assign the value to.
  103. * </p>
  104. * @param mixed $value <p>
  105. * The value to set.
  106. * </p>
  107. *
  108. * @return void
  109. * @since 5.0.0
  110. */
  111. public function offsetSet($offset, $value)
  112. {
  113. $this->page[$offset] = $value;
  114. }
  115. /**
  116. * Offset to unset
  117. *
  118. * @link https://php.net/manual/en/arrayaccess.offsetunset.php
  119. *
  120. * @param mixed $offset <p>
  121. * The offset to unset.
  122. * </p>
  123. *
  124. * @return void
  125. * @since 5.0.0
  126. */
  127. public function offsetUnset($offset)
  128. {
  129. if (isset($this->page[$offset])) {
  130. unset($this->page[$offset]);
  131. }
  132. }
  133. /**
  134. * Register a stylesheet file path to be included in the <head> tag of every page.
  135. * Inclusion is done in App->initHead().
  136. * The path can be absolute or relative to the Friendica installation base folder.
  137. *
  138. * @param string $path
  139. *
  140. * @see Page::initHead()
  141. *
  142. */
  143. public function registerStylesheet($path)
  144. {
  145. if (mb_strpos($path, $this->basePath . DIRECTORY_SEPARATOR) === 0) {
  146. $path = mb_substr($path, mb_strlen($this->basePath . DIRECTORY_SEPARATOR));
  147. }
  148. $this->stylesheets[] = trim($path, '/');
  149. }
  150. /**
  151. * Initializes Page->page['htmlhead'].
  152. *
  153. * Includes:
  154. * - Page title
  155. * - Favicons
  156. * - Registered stylesheets (through App->registerStylesheet())
  157. * - Infinite scroll data
  158. * - head.tpl template
  159. *
  160. * @param App $app The Friendica App instance
  161. * @param Module $module The loaded Friendica module
  162. * @param L10n $l10n The l10n language instance
  163. * @param Configuration $config The Friendica configuration
  164. * @param PConfiguration $pConfig The Friendica personal configuration (for user)
  165. *
  166. * @throws HTTPException\InternalServerErrorException
  167. */
  168. private function initHead(App $app, Module $module, L10n $l10n, Configuration $config, PConfiguration $pConfig)
  169. {
  170. $interval = ((local_user()) ? $pConfig->get(local_user(), 'system', 'update_interval') : 40000);
  171. // If the update is 'deactivated' set it to the highest integer number (~24 days)
  172. if ($interval < 0) {
  173. $interval = 2147483647;
  174. }
  175. if ($interval < 10000) {
  176. $interval = 40000;
  177. }
  178. // Default title: current module called
  179. if (empty($this->page['title']) && $module->getName()) {
  180. $this->page['title'] = ucfirst($module->getName());
  181. }
  182. // Prepend the sitename to the page title
  183. $this->page['title'] = $config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
  184. if (!empty(Renderer::$theme['stylesheet'])) {
  185. $stylesheet = Renderer::$theme['stylesheet'];
  186. } else {
  187. $stylesheet = $app->getCurrentThemeStylesheetPath();
  188. }
  189. $this->registerStylesheet($stylesheet);
  190. $shortcut_icon = $config->get('system', 'shortcut_icon');
  191. if ($shortcut_icon == '') {
  192. $shortcut_icon = 'images/friendica-32.png';
  193. }
  194. $touch_icon = $config->get('system', 'touch_icon');
  195. if ($touch_icon == '') {
  196. $touch_icon = 'images/friendica-128.png';
  197. }
  198. Hook::callAll('head', $this->page['htmlhead']);
  199. $tpl = Renderer::getMarkupTemplate('head.tpl');
  200. /* put the head template at the beginning of page['htmlhead']
  201. * since the code added by the modules frequently depends on it
  202. * being first
  203. */
  204. $this->page['htmlhead'] = Renderer::replaceMacros($tpl, [
  205. '$local_user' => local_user(),
  206. '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
  207. '$delitem' => $l10n->t('Delete this item?'),
  208. '$update_interval' => $interval,
  209. '$shortcut_icon' => $shortcut_icon,
  210. '$touch_icon' => $touch_icon,
  211. '$block_public' => intval($config->get('system', 'block_public')),
  212. '$stylesheets' => $this->stylesheets,
  213. ]) . $this->page['htmlhead'];
  214. }
  215. /**
  216. * Initializes Page->page['footer'].
  217. *
  218. * Includes:
  219. * - Javascript homebase
  220. * - Mobile toggle link
  221. * - Registered footer scripts (through App->registerFooterScript())
  222. * - footer.tpl template
  223. *
  224. * @param App $app The Friendica App instance
  225. * @param Mode $mode The Friendica runtime mode
  226. * @param L10n $l10n The l10n instance
  227. *
  228. * @throws HTTPException\InternalServerErrorException
  229. */
  230. private function initFooter(App $app, Mode $mode, L10n $l10n)
  231. {
  232. // If you're just visiting, let javascript take you home
  233. if (!empty($_SESSION['visitor_home'])) {
  234. $homebase = $_SESSION['visitor_home'];
  235. } elseif (local_user()) {
  236. $homebase = 'profile/' . $app->user['nickname'];
  237. }
  238. if (isset($homebase)) {
  239. $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
  240. }
  241. /*
  242. * Add a "toggle mobile" link if we're using a mobile device
  243. */
  244. if ($mode->isMobile() || $mode->isTablet()) {
  245. if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
  246. $link = 'toggle_mobile?address=' . urlencode(curPageURL());
  247. } else {
  248. $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
  249. }
  250. $this->page['footer'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
  251. '$toggle_link' => $link,
  252. '$toggle_text' => $l10n->t('toggle mobile')
  253. ]);
  254. }
  255. Hook::callAll('footer', $this->page['footer']);
  256. $tpl = Renderer::getMarkupTemplate('footer.tpl');
  257. $this->page['footer'] = Renderer::replaceMacros($tpl, [
  258. '$footerScripts' => $this->footerScripts,
  259. ]) . $this->page['footer'];
  260. }
  261. /**
  262. * Initializes Page->page['content'].
  263. *
  264. * Includes:
  265. * - module content
  266. * - hooks for content
  267. *
  268. * @param Module $module The module
  269. * @param Mode $mode The Friendica execution mode
  270. *
  271. * @throws HTTPException\InternalServerErrorException
  272. */
  273. private function initContent(Module $module, Mode $mode)
  274. {
  275. $content = '';
  276. try {
  277. $moduleClass = $module->getClassName();
  278. $arr = ['content' => $content];
  279. Hook::callAll($moduleClass . '_mod_content', $arr);
  280. $content = $arr['content'];
  281. $arr = ['content' => call_user_func([$moduleClass, 'content'], $module->getParameters())];
  282. Hook::callAll($moduleClass . '_mod_aftercontent', $arr);
  283. $content .= $arr['content'];
  284. } catch (HTTPException $e) {
  285. $content = ModuleHTTPException::content($e);
  286. }
  287. // initialise content region
  288. if ($mode->isNormal()) {
  289. Hook::callAll('page_content_top', $this->page['content']);
  290. }
  291. $this->page['content'] .= $content;
  292. }
  293. /**
  294. * Register a javascript file path to be included in the <footer> tag of every page.
  295. * Inclusion is done in App->initFooter().
  296. * The path can be absolute or relative to the Friendica installation base folder.
  297. *
  298. * @param string $path
  299. *
  300. * @see Page::initFooter()
  301. *
  302. */
  303. public function registerFooterScript($path)
  304. {
  305. $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
  306. $this->footerScripts[] = trim($url, '/');
  307. }
  308. /**
  309. * Executes the creation of the current page and prints it to the screen
  310. *
  311. * @param App $app The Friendica App
  312. * @param BaseURL $baseURL The Friendica Base URL
  313. * @param Mode $mode The current node mode
  314. * @param Module $module The loaded Friendica module
  315. * @param L10n $l10n The l10n language class
  316. * @param Configuration $config The Configuration of this node
  317. * @param PConfiguration $pconfig The personal/user configuration
  318. *
  319. * @throws HTTPException\InternalServerErrorException
  320. */
  321. public function run(App $app, BaseURL $baseURL, Mode $mode, Module $module, L10n $l10n, Configuration $config, PConfiguration $pconfig)
  322. {
  323. $moduleName = $module->getName();
  324. /* Create the page content.
  325. * Calls all hooks which are including content operations
  326. *
  327. * Sets the $Page->page['content'] variable
  328. */
  329. $this->initContent($module, $mode);
  330. // Load current theme info after module has been initialized as theme could have been set in module
  331. $currentTheme = $app->getCurrentTheme();
  332. $theme_info_file = 'view/theme/' . $currentTheme . '/theme.php';
  333. if (file_exists($theme_info_file)) {
  334. require_once $theme_info_file;
  335. }
  336. if (function_exists(str_replace('-', '_', $currentTheme) . '_init')) {
  337. $func = str_replace('-', '_', $currentTheme) . '_init';
  338. $func($app);
  339. }
  340. /* Create the page head after setting the language
  341. * and getting any auth credentials.
  342. *
  343. * Moved initHead() and initFooter() to after
  344. * all the module functions have executed so that all
  345. * theme choices made by the modules can take effect.
  346. */
  347. $this->initHead($app, $module, $l10n, $config, $pconfig);
  348. /* Build the page ending -- this is stuff that goes right before
  349. * the closing </body> tag
  350. */
  351. $this->initFooter($app, $mode, $l10n);
  352. if (!$mode->isAjax()) {
  353. Hook::callAll('page_end', $this->page['content']);
  354. }
  355. // Add the navigation (menu) template
  356. if ($moduleName != 'install' && $moduleName != 'maintenance') {
  357. $this->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('nav_head.tpl'), []);
  358. $this->page['nav'] = Nav::build($app);
  359. }
  360. // Build the page - now that we have all the components
  361. if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
  362. $doc = new DOMDocument();
  363. $target = new DOMDocument();
  364. $target->loadXML("<root></root>");
  365. $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
  366. /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
  367. @$doc->loadHTML($content);
  368. $xpath = new DOMXPath($doc);
  369. $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
  370. foreach ($list as $item) {
  371. $item = $target->importNode($item, true);
  372. // And then append it to the target
  373. $target->documentElement->appendChild($item);
  374. }
  375. if ($_GET["mode"] == "raw") {
  376. header("Content-type: text/html; charset=utf-8");
  377. echo substr($target->saveHTML(), 6, -8);
  378. exit();
  379. }
  380. }
  381. $page = $this->page;
  382. $profile = $app->profile;
  383. header("X-Friendica-Version: " . FRIENDICA_VERSION);
  384. header("Content-type: text/html; charset=utf-8");
  385. if ($config->get('system', 'hsts') && ($baseURL->getSSLPolicy() == BaseURL::SSL_POLICY_FULL)) {
  386. header("Strict-Transport-Security: max-age=31536000");
  387. }
  388. // Some security stuff
  389. header('X-Content-Type-Options: nosniff');
  390. header('X-XSS-Protection: 1; mode=block');
  391. header('X-Permitted-Cross-Domain-Policies: none');
  392. header('X-Frame-Options: sameorigin');
  393. // Things like embedded OSM maps don't work, when this is enabled
  394. // 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'");
  395. /* We use $_GET["mode"] for special page templates. So we will check if we have
  396. * to load another page template than the default one.
  397. * The page templates are located in /view/php/ or in the theme directory.
  398. */
  399. if (isset($_GET["mode"])) {
  400. $template = Theme::getPathForFile($_GET["mode"] . '.php');
  401. }
  402. // If there is no page template use the default page template
  403. if (empty($template)) {
  404. $template = Theme::getPathForFile("default.php");
  405. }
  406. // Theme templates expect $a as an App instance
  407. $a = $app;
  408. // Used as is in view/php/default.php
  409. $lang = $l10n->getCurrentLang();
  410. /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
  411. require_once $template;
  412. }
  413. }