3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\App;
28 use Friendica\Content\Nav;
29 use Friendica\Core\Config\Capability\IManageConfigValues;
30 use Friendica\Core\Hook;
31 use Friendica\Core\L10n;
32 use Friendica\Core\Logger;
33 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
34 use Friendica\Core\Renderer;
35 use Friendica\Core\System;
36 use Friendica\Core\Theme;
37 use Friendica\Module\Response;
38 use Friendica\Network\HTTPException;
39 use Friendica\Util\Network;
40 use Friendica\Util\Profiler;
41 use Friendica\Util\Strings;
42 use Psr\Http\Message\ResponseInterface;
45 * Contains the page specific environment variables for the current Page
46 * - Contains all stylesheets
47 * - Contains all footer-scripts
48 * - Contains all page specific content (header, footer, content, ...)
50 * The run() method is the single point where the page will get printed to the screen
52 class Page implements ArrayAccess
55 * @var array Contains all stylesheets, which should get loaded during page
57 private $stylesheets = [];
59 * @var array Contains all scripts, which are added to the footer at last
61 private $footerScripts = [];
63 * @var array The page content, which are showed directly
80 * @var string The basepath of the page
84 private $timestamp = 0;
87 private $command = '';
90 * @param string $basepath The Page basepath
92 public function __construct(string $basepath)
94 $this->timestamp = microtime(true);
95 $this->basePath = $basepath;
98 public function setLogging(string $method, string $module, string $command)
100 $this->method = $method;
101 $this->module = $module;
102 $this->command = $command;
105 public function logRuntime(IManageConfigValues $config, string $origin = '')
107 $ignore = $config->get('system', 'runtime_ignore');
108 if (in_array($this->module, $ignore) || in_array($this->command, $ignore)) {
112 $signature = !empty($_SERVER['HTTP_SIGNATURE']);
113 $load = number_format(System::currentLoad(), 2);
114 $runtime = number_format(microtime(true) - $this->timestamp, 3);
115 if ($runtime > $config->get('system', 'runtime_loglimit')) {
116 Logger::debug('Runtime', ['method' => $this->method, 'module' => $this->module, 'runtime' => $runtime, 'load' => $load, 'origin' => $origin, 'signature' => $signature, 'request' => $_SERVER['REQUEST_URI'] ?? '']);
120 // ArrayAccess interface
125 #[\ReturnTypeWillChange]
126 public function offsetExists($offset): bool
128 return isset($this->page[$offset]);
134 #[\ReturnTypeWillChange]
135 public function offsetGet($offset)
137 return $this->page[$offset] ?? null;
143 #[\ReturnTypeWillChange]
144 public function offsetSet($offset, $value): void
146 $this->page[$offset] = $value;
152 #[\ReturnTypeWillChange]
153 public function offsetUnset($offset): void
155 if (isset($this->page[$offset])) {
156 unset($this->page[$offset]);
161 * Register a stylesheet file path to be included in the <head> tag of every page.
162 * Inclusion is done in App->initHead().
163 * The path can be absolute or relative to the Friendica installation base folder.
165 * @param string $path
166 * @param string $media
167 * @see Page::initHead()
169 public function registerStylesheet(string $path, string $media = 'screen')
171 $path = Network::appendQueryParam($path, ['v' => App::VERSION]);
173 if (mb_strpos($path, $this->basePath . DIRECTORY_SEPARATOR) === 0) {
174 $path = mb_substr($path, mb_strlen($this->basePath . DIRECTORY_SEPARATOR));
177 $this->stylesheets[trim($path, '/')] = $media;
181 * Initializes Page->page['htmlhead'].
186 * - Registered stylesheets (through App->registerStylesheet())
187 * - Infinite scroll data
188 * - head.tpl template
190 * @param App $app The Friendica App instance
191 * @param Arguments $args The Friendica App Arguments
192 * @param L10n $l10n The l10n language instance
193 * @param IManageConfigValues $config The Friendica configuration
194 * @param IManagePersonalConfigValues $pConfig The Friendica personal configuration (for user)
195 * @param int $localUID The local user id
197 * @throws HTTPException\InternalServerErrorException
199 private function initHead(App $app, Arguments $args, L10n $l10n, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, int $localUID)
201 $interval = ($localUID ? $pConfig->get($localUID, 'system', 'update_interval') : 40000);
203 // If the update is 'deactivated' set it to the highest integer number (~24 days)
205 $interval = 2147483647;
208 if ($interval < 10000) {
212 // Default title: current module called
213 if (empty($this->page['title']) && $args->getModuleName()) {
214 $this->page['title'] = ucfirst($args->getModuleName());
217 // Prepend the sitename to the page title
218 $this->page['title'] = $config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
220 if (!empty(Renderer::$theme['stylesheet'])) {
221 $stylesheet = Renderer::$theme['stylesheet'];
223 $stylesheet = $app->getCurrentThemeStylesheetPath();
226 $this->registerStylesheet($stylesheet);
228 $shortcut_icon = $config->get('system', 'shortcut_icon');
229 if ($shortcut_icon == '') {
230 $shortcut_icon = 'images/friendica.svg';
233 $touch_icon = $config->get('system', 'touch_icon');
234 if ($touch_icon == '') {
235 $touch_icon = 'images/friendica-192.png';
238 Hook::callAll('head', $this->page['htmlhead']);
240 $tpl = Renderer::getMarkupTemplate('head.tpl');
241 /* put the head template at the beginning of page['htmlhead']
242 * since the code added by the modules frequently depends on it
245 $this->page['htmlhead'] = Renderer::replaceMacros($tpl, [
246 '$local_user' => $localUID,
247 '$generator' => 'Friendica' . ' ' . App::VERSION,
248 '$delitem' => $l10n->t('Delete this item?'),
249 '$blockAuthor' => $l10n->t('Block this author? They won\'t be able to follow you nor see your public posts, and you won\'t be able to see their posts and their notifications.'),
250 '$ignoreAuthor' => $l10n->t('Ignore this author? You won\'t be able to see their posts and their notifications.'),
251 '$update_interval' => $interval,
252 '$shortcut_icon' => $shortcut_icon,
253 '$touch_icon' => $touch_icon,
254 '$block_public' => intval($config->get('system', 'block_public')),
255 '$stylesheets' => $this->stylesheets,
256 '$likeError' => $l10n->t('Like not successfull'),
257 '$dislikeError' => $l10n->t('Dislike not successfull'),
258 '$announceError' => $l10n->t('Sharing not successfull'),
259 '$srvError' => $l10n->t('Backend error'),
260 '$netError' => $l10n->t('Network error'),
261 ]) . $this->page['htmlhead'];
265 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
267 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
269 private function curPageURL(): string
272 if (!empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {
278 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
279 $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
281 $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
287 * Initializes Page->page['footer'].
290 * - Javascript homebase
291 * - Mobile toggle link
292 * - Registered footer scripts (through App->registerFooterScript())
293 * - footer.tpl template
295 * @param App $app The Friendica App instance
296 * @param Mode $mode The Friendica runtime mode
297 * @param L10n $l10n The l10n instance
299 * @throws HTTPException\InternalServerErrorException
301 private function initFooter(App $app, Mode $mode, L10n $l10n)
303 // If you're just visiting, let javascript take you home
304 if (!empty($_SESSION['visitor_home'])) {
305 $homebase = $_SESSION['visitor_home'];
306 } elseif (!empty($app->getLoggedInUserNickname())) {
307 $homebase = 'profile/' . $app->getLoggedInUserNickname();
310 if (isset($homebase)) {
311 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
315 * Add a "toggle mobile" link if we're using a mobile device
317 if ($mode->isMobile() || $mode->isTablet()) {
318 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
319 $link = 'toggle_mobile?address=' . urlencode($this->curPageURL());
321 $link = 'toggle_mobile?off=1&address=' . urlencode($this->curPageURL());
323 $this->page['footer'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
324 '$toggle_link' => $link,
325 '$toggle_text' => $l10n->t('toggle mobile')
329 Hook::callAll('footer', $this->page['footer']);
331 $tpl = Renderer::getMarkupTemplate('footer.tpl');
332 $this->page['footer'] = Renderer::replaceMacros($tpl, [
333 '$footerScripts' => array_unique($this->footerScripts),
334 ]) . $this->page['footer'];
338 * Initializes Page->page['content'].
342 * - hooks for content
344 * @param ResponseInterface $response The Module response class
345 * @param Mode $mode The Friendica execution mode
347 * @throws HTTPException\InternalServerErrorException
349 private function initContent(ResponseInterface $response, Mode $mode)
351 // initialise content region
352 if ($mode->isNormal()) {
353 Hook::callAll('page_content_top', $this->page['content']);
356 $this->page['content'] .= (string)$response->getBody();
360 * Register a javascript file path to be included in the <footer> tag of every page.
361 * Inclusion is done in App->initFooter().
362 * The path can be absolute or relative to the Friendica installation base folder.
364 * @param string $path
366 * @see Page::initFooter()
369 public function registerFooterScript($path)
371 $path = Network::appendQueryParam($path, ['v' => App::VERSION]);
373 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
375 $this->footerScripts[] = trim($url, '/');
379 * Directly exit with the current response (include setting all headers)
381 * @param ResponseInterface $response
383 public function exit(ResponseInterface $response)
385 header(sprintf("HTTP/%s %s %s",
386 $response->getProtocolVersion(),
387 $response->getStatusCode(),
388 $response->getReasonPhrase())
391 foreach ($response->getHeaders() as $key => $header) {
392 if (is_array($header)) {
393 $header_str = implode(',', $header);
395 $header_str = $header;
401 header("$key: $header_str");
405 echo $response->getBody();
409 * Executes the creation of the current page and prints it to the screen
411 * @param App $app The Friendica App
412 * @param BaseURL $baseURL The Friendica Base URL
413 * @param Arguments $args The Friendica App arguments
414 * @param Mode $mode The current node mode
415 * @param ResponseInterface $response The Response of the module class, including type, content & headers
416 * @param L10n $l10n The l10n language class
417 * @param Profiler $profiler
418 * @param IManageConfigValues $config The Configuration of this node
419 * @param IManagePersonalConfigValues $pconfig The personal/user configuration
421 * @param int $localUID
422 * @throws HTTPException\MethodNotAllowedException
423 * @throws HTTPException\InternalServerErrorException
424 * @throws HTTPException\ServiceUnavailableException
426 public function run(App $app, BaseURL $baseURL, Arguments $args, Mode $mode, ResponseInterface $response, L10n $l10n, Profiler $profiler, IManageConfigValues $config, IManagePersonalConfigValues $pconfig, Nav $nav, int $localUID)
428 $moduleName = $args->getModuleName();
430 $this->command = $moduleName;
431 $this->method = $args->getMethod();
433 /* Create the page content.
434 * Calls all hooks which are including content operations
436 * Sets the $Page->page['content'] variable
438 $timestamp = microtime(true);
439 $this->initContent($response, $mode);
441 // Load current theme info after module has been initialized as theme could have been set in module
442 $currentTheme = $app->getCurrentTheme();
443 $theme_info_file = 'view/theme/' . $currentTheme . '/theme.php';
444 if (file_exists($theme_info_file)) {
445 require_once $theme_info_file;
448 if (function_exists(str_replace('-', '_', $currentTheme) . '_init')) {
449 $func = str_replace('-', '_', $currentTheme) . '_init';
453 /* Create the page head after setting the language
454 * and getting any auth credentials.
456 * Moved initHead() and initFooter() to after
457 * all the module functions have executed so that all
458 * theme choices made by the modules can take effect.
460 $this->initHead($app, $args, $l10n, $config, $pconfig, $localUID);
462 /* Build the page ending -- this is stuff that goes right before
463 * the closing </body> tag
465 $this->initFooter($app, $mode, $l10n);
467 $profiler->set(microtime(true) - $timestamp, 'aftermath');
469 if (!$mode->isAjax()) {
470 Hook::callAll('page_end', $this->page['content']);
473 // Add the navigation (menu) template
474 if ($moduleName != 'install' && $moduleName != 'maintenance') {
475 $this->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('nav_head.tpl'), []);
476 $this->page['nav'] = $nav->getHtml();
479 foreach ($response->getHeaders() as $key => $header) {
480 if (is_array($header)) {
481 $header_str = implode(',', $header);
483 $header_str = $header;
489 header("$key: $header_str");
493 // Build the page - now that we have all the components
494 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
495 $doc = new DOMDocument();
497 $target = new DOMDocument();
498 $target->loadXML("<root></root>");
500 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
502 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
503 @$doc->loadHTML($content);
505 $xpath = new DOMXPath($doc);
507 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
509 foreach ($list as $item) {
510 $item = $target->importNode($item, true);
512 // And then append it to the target
513 $target->documentElement->appendChild($item);
516 if ($_GET["mode"] == "raw") {
517 System::httpExit(substr($target->saveHTML(), 6, -8), Response::TYPE_HTML);
523 // add and escape some common but crucial content for direct "echo" in HTML (security)
524 $page['title'] = htmlspecialchars($page['title'] ?? '');
525 $page['section'] = htmlspecialchars($args->get(0) ?? 'generic');
526 $page['module'] = htmlspecialchars($args->getModuleName() ?? '');
528 header("X-Friendica-Version: " . App::VERSION);
529 header("Content-type: text/html; charset=utf-8");
531 if ($config->get('system', 'hsts') && ($baseURL->getScheme() === 'https')) {
532 header("Strict-Transport-Security: max-age=31536000");
535 // Some security stuff
536 header('X-Content-Type-Options: nosniff');
537 header('X-XSS-Protection: 1; mode=block');
538 header('X-Permitted-Cross-Domain-Policies: none');
539 header('X-Frame-Options: sameorigin');
541 // Things like embedded OSM maps don't work, when this is enabled
542 // 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'");
544 /* We use $_GET["mode"] for special page templates. So we will check if we have
545 * to load another page template than the default one.
546 * The page templates are located in /view/php/ or in the theme directory.
548 if (isset($_GET['mode'])) {
549 $template = Theme::getPathForFile('php/' . Strings::sanitizeFilePathItem($_GET['mode']) . '.php');
552 // If there is no page template use the default page template
553 if (empty($template)) {
554 $template = Theme::getPathForFile('php/default.php');
557 // Theme templates expect $a as an App instance
560 // Used as is in view/php/default.php
561 $lang = $l10n->getCurrentLang();
563 require_once $template;