]> git.mxchange.org Git - friendica.git/blob - src/App/Page.php
96bb59425efd151f405bd025d41dfb98a1058f70
[friendica.git] / src / App / Page.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\App;
23
24 use ArrayAccess;
25 use DOMDocument;
26 use DOMXPath;
27 use 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 GuzzleHttp\Psr7\Utils;
43 use Psr\Http\Message\ResponseInterface;
44
45 /**
46  * Contains the page specific environment variables for the current Page
47  * - Contains all stylesheets
48  * - Contains all footer-scripts
49  * - Contains all page specific content (header, footer, content, ...)
50  *
51  * The run() method is the single point where the page will get printed to the screen
52  */
53 class Page implements ArrayAccess
54 {
55         /**
56          * @var array Contains all stylesheets, which should get loaded during page
57          */
58         private $stylesheets = [];
59         /**
60          * @var array Contains all scripts, which are added to the footer at last
61          */
62         private $footerScripts = [];
63         /**
64          * @var array The page content, which are showed directly
65          */
66         private $page = [
67                 'aside'       => '',
68                 'bottom'      => '',
69                 'content'     => '',
70                 'footer'      => '',
71                 'htmlhead'    => '',
72                 'nav'         => '',
73                 'page_title'  => '',
74                 'right_aside' => '',
75                 'template'    => '',
76                 'title'       => '',
77                 'section'     => '',
78                 'module'      => '',
79         ];
80         /**
81          * @var string The basepath of the page
82          */
83         private $basePath;
84
85         private $timestamp = 0;
86         private $method    = '';
87         private $module    = '';
88         private $command   = '';
89
90         /**
91          * @param string $basepath The Page basepath
92          */
93         public function __construct(string $basepath)
94         {
95                 $this->timestamp = microtime(true);
96                 $this->basePath = $basepath;
97         }
98
99         public function setLogging(string $method, string $module, string $command)
100         {
101                 $this->method  = $method;
102                 $this->module  = $module;
103                 $this->command = $command;
104         }
105
106         public function logRuntime(IManageConfigValues $config, string $origin = '')
107         {
108                 $ignore = $config->get('system', 'runtime_ignore');
109                 if (in_array($this->module, $ignore) || in_array($this->command, $ignore)) {
110                         return;
111                 }
112
113                 $signature = !empty($_SERVER['HTTP_SIGNATURE']);
114                 $load      = number_format(System::currentLoad(), 2);
115                 $runtime   = number_format(microtime(true) - $this->timestamp, 3);
116                 if ($runtime > $config->get('system', 'runtime_loglimit')) {
117                         Logger::debug('Runtime', ['method' => $this->method, 'module' => $this->module, 'runtime' => $runtime, 'load' => $load, 'origin' => $origin, 'signature' => $signature, 'request' => $_SERVER['REQUEST_URI'] ?? '']);
118                 }
119         }
120
121         // ArrayAccess interface
122
123         /**
124          * @inheritDoc
125          */
126         #[\ReturnTypeWillChange]
127         public function offsetExists($offset): bool
128         {
129                 return isset($this->page[$offset]);
130         }
131
132         /**
133          * @inheritDoc
134          */
135         #[\ReturnTypeWillChange]
136         public function offsetGet($offset)
137         {
138                 return $this->page[$offset] ?? null;
139         }
140
141         /**
142          * @inheritDoc
143          */
144         #[\ReturnTypeWillChange]
145         public function offsetSet($offset, $value): void
146         {
147                 $this->page[$offset] = $value;
148         }
149
150         /**
151          * @inheritDoc
152          */
153         #[\ReturnTypeWillChange]
154         public function offsetUnset($offset): void
155         {
156                 if (isset($this->page[$offset])) {
157                         unset($this->page[$offset]);
158                 }
159         }
160
161         /**
162          * Register a stylesheet file path to be included in the <head> tag of every page.
163          * Inclusion is done in App->initHead().
164          * The path can be absolute or relative to the Friendica installation base folder.
165          *
166          * @param string $path
167          * @param string $media
168          * @see Page::initHead()
169          */
170         public function registerStylesheet(string $path, string $media = 'screen')
171         {
172                 $path = Network::appendQueryParam($path, ['v' => App::VERSION]);
173
174                 if (mb_strpos($path, $this->basePath . DIRECTORY_SEPARATOR) === 0) {
175                         $path = mb_substr($path, mb_strlen($this->basePath . DIRECTORY_SEPARATOR));
176                 }
177
178                 $this->stylesheets[trim($path, '/')] = $media;
179         }
180
181         /**
182          * Initializes Page->page['htmlhead'].
183          *
184          * Includes:
185          * - Page title
186          * - Favicons
187          * - Registered stylesheets (through App->registerStylesheet())
188          * - Infinite scroll data
189          * - head.tpl template
190          *
191          * @param App                         $app      The Friendica App instance
192          * @param Arguments                   $args     The Friendica App Arguments
193          * @param L10n                        $l10n     The l10n language instance
194          * @param IManageConfigValues         $config   The Friendica configuration
195          * @param IManagePersonalConfigValues $pConfig  The Friendica personal configuration (for user)
196          * @param int                         $localUID The local user id
197          *
198          * @throws HTTPException\InternalServerErrorException
199          */
200         private function initHead(App $app, Arguments $args, L10n $l10n, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, int $localUID)
201         {
202                 $interval = ($localUID ? $pConfig->get($localUID, 'system', 'update_interval') : 40000);
203
204                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
205                 if ($interval < 0) {
206                         $interval = 2147483647;
207                 }
208
209                 if ($interval < 10000) {
210                         $interval = 40000;
211                 }
212
213                 // Default title: current module called
214                 if (empty($this->page['title']) && $args->getModuleName()) {
215                         $this->page['title'] = ucfirst($args->getModuleName());
216                 }
217
218                 // Prepend the sitename to the page title
219                 $this->page['title'] = $config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
220
221                 if (!empty(Renderer::$theme['stylesheet'])) {
222                         $stylesheet = Renderer::$theme['stylesheet'];
223                 } else {
224                         $stylesheet = $app->getCurrentThemeStylesheetPath();
225                 }
226
227                 $this->registerStylesheet($stylesheet);
228
229                 $shortcut_icon = $config->get('system', 'shortcut_icon');
230                 if ($shortcut_icon == '') {
231                         $shortcut_icon = 'images/friendica.svg';
232                 }
233
234                 $touch_icon = $config->get('system', 'touch_icon');
235                 if ($touch_icon == '') {
236                         $touch_icon = 'images/friendica-192.png';
237                 }
238
239                 Hook::callAll('head', $this->page['htmlhead']);
240
241                 $tpl = Renderer::getMarkupTemplate('head.tpl');
242                 /* put the head template at the beginning of page['htmlhead']
243                  * since the code added by the modules frequently depends on it
244                  * being first
245                  */
246                 $this->page['htmlhead'] = Renderer::replaceMacros($tpl, [
247                         '$l10n' => [
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                                 'collapseAuthor' => $l10n->t('Collapse this author\'s posts?'),
252
253                                 'likeError'     => $l10n->t('Like not successful'),
254                                 'dislikeError'  => $l10n->t('Dislike not successful'),
255                                 'announceError' => $l10n->t('Sharing not successful'),
256                                 'attendError'   => $l10n->t('Attendance unsuccessful'),
257                                 'srvError'      => $l10n->t('Backend error'),
258                                 'netError'      => $l10n->t('Network error'),
259
260                                 // Dropzone
261                                 'dictDefaultMessage'           => $l10n->t('Drop files here to upload'),
262                                 'dictFallbackMessage'          => $l10n->t("Your browser does not support drag and drop file uploads."),
263                                 'dictFallbackText'             => $l10n->t('Please use the fallback form below to upload your files like in the olden days.'),
264                                 'dictFileTooBig'               => $l10n->t('File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.'),
265                                 'dictInvalidFileType'          => $l10n->t("You can't upload files of this type."),
266                                 'dictResponseError'            => $l10n->t('Server responded with {{statusCode}} code.'),
267                                 'dictCancelUpload'             => $l10n->t('Cancel upload'),
268                                 'dictUploadCanceled'           => $l10n->t('Upload canceled.'),
269                                 'dictCancelUploadConfirmation' => $l10n->t('Are you sure you want to cancel this upload?'),
270                                 'dictRemoveFile'               => $l10n->t('Remove file'),
271                                 'dictMaxFilesExceeded'         => $l10n->t("You can't upload any more files."),
272                         ],
273
274                         '$local_user'      => $localUID,
275                         '$generator'       => 'Friendica' . ' ' . App::VERSION,
276                         '$update_interval' => $interval,
277                         '$shortcut_icon'   => $shortcut_icon,
278                         '$touch_icon'      => $touch_icon,
279                         '$block_public'    => intval($config->get('system', 'block_public')),
280                         '$stylesheets'     => $this->stylesheets,
281
282                         // Dropzone
283                         '$max_imagesize' => round(\Friendica\Util\Strings::getBytesFromShorthand($config->get('system', 'maximagesize')) / 1000000, 1),
284
285                 ]) . $this->page['htmlhead'];
286         }
287
288         /**
289          * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
290          *
291          * Taken from http://webcheatsheet.com/php/get_current_page_url.php
292          */
293         private function curPageURL(): string
294         {
295                 $pageURL = 'http';
296                 if (!empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {
297                         $pageURL .= "s";
298                 }
299
300                 $pageURL .= "://";
301
302                 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
303                         $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
304                 } else {
305                         $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
306                 }
307                 return $pageURL;
308         }
309
310         /**
311          * Initializes Page->page['footer'].
312          *
313          * Includes:
314          * - JavaScript homebase
315          * - Mobile toggle link
316          * - Registered footer scripts (through App->registerFooterScript())
317          * - footer.tpl template
318          *
319          * @param App  $app  The Friendica App instance
320          * @param Mode $mode The Friendica runtime mode
321          * @param L10n $l10n The l10n instance
322          *
323          * @throws HTTPException\InternalServerErrorException
324          */
325         private function initFooter(App $app, Mode $mode, L10n $l10n)
326         {
327                 // If you're just visiting, let javascript take you home
328                 if (!empty($_SESSION['visitor_home'])) {
329                         $homebase = $_SESSION['visitor_home'];
330                 } elseif (!empty($app->getLoggedInUserNickname())) {
331                         $homebase = 'profile/' . $app->getLoggedInUserNickname();
332                 }
333
334                 if (isset($homebase)) {
335                         $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
336                 }
337
338                 /*
339                  * Add a "toggle mobile" link if we're using a mobile device
340                  */
341                 if ($mode->isMobile() || $mode->isTablet()) {
342                         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
343                                 $link = 'toggle_mobile?address=' . urlencode($this->curPageURL());
344                         } else {
345                                 $link = 'toggle_mobile?off=1&address=' . urlencode($this->curPageURL());
346                         }
347                         $this->page['footer'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
348                                 '$toggle_link' => $link,
349                                 '$toggle_text' => $l10n->t('toggle mobile')
350                         ]);
351                 }
352
353                 Hook::callAll('footer', $this->page['footer']);
354
355                 $tpl                  = Renderer::getMarkupTemplate('footer.tpl');
356                 $this->page['footer'] = Renderer::replaceMacros($tpl, [
357                         '$footerScripts' => array_unique($this->footerScripts),
358                 ]) . $this->page['footer'];
359         }
360
361         /**
362          * Initializes Page->page['content'].
363          *
364          * Includes:
365          * - module content
366          * - hooks for content
367          *
368          * @param ResponseInterface  $response The Module response class
369          * @param Mode               $mode     The Friendica execution mode
370          *
371          * @throws HTTPException\InternalServerErrorException
372          */
373         private function initContent(ResponseInterface $response, Mode $mode)
374         {
375                 // initialise content region
376                 if ($mode->isNormal()) {
377                         Hook::callAll('page_content_top', $this->page['content']);
378                 }
379
380                 $this->page['content'] .= (string)$response->getBody();
381         }
382
383         /**
384          * Register a javascript file path to be included in the <footer> tag of every page.
385          * Inclusion is done in App->initFooter().
386          * The path can be absolute or relative to the Friendica installation base folder.
387          *
388          * @param string $path
389          *
390          * @see Page::initFooter()
391          *
392          */
393         public function registerFooterScript($path)
394         {
395                 $path = Network::appendQueryParam($path, ['v' => App::VERSION]);
396
397                 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
398
399                 $this->footerScripts[] = trim($url, '/');
400         }
401
402         /**
403          * Directly exit with the current response (include setting all headers)
404          *
405          * @param ResponseInterface $response
406          */
407         public function exit(ResponseInterface $response)
408         {
409                 header(sprintf("HTTP/%s %s %s",
410                         $response->getProtocolVersion(),
411                         $response->getStatusCode(),
412                         $response->getReasonPhrase())
413                 );
414
415                 foreach ($response->getHeaders() as $key => $header) {
416                         if (is_array($header)) {
417                                 $header_str = implode(',', $header);
418                         } else {
419                                 $header_str = $header;
420                         }
421
422                         if (empty($key)) {
423                                 header($header_str);
424                         } else {
425                                 header("$key: $header_str");
426                         }
427                 }
428
429                 echo $response->getBody();
430         }
431
432         /**
433          * Executes the creation of the current page and prints it to the screen
434          *
435          * @param App                         $app      The Friendica App
436          * @param BaseURL                     $baseURL  The Friendica Base URL
437          * @param Arguments                   $args     The Friendica App arguments
438          * @param Mode                        $mode     The current node mode
439          * @param ResponseInterface           $response The Response of the module class, including type, content & headers
440          * @param L10n                        $l10n     The l10n language class
441          * @param Profiler                    $profiler
442          * @param IManageConfigValues         $config   The Configuration of this node
443          * @param IManagePersonalConfigValues $pconfig  The personal/user configuration
444          * @param Nav                         $nav
445          * @param int                         $localUID
446          * @throws HTTPException\MethodNotAllowedException
447          * @throws HTTPException\InternalServerErrorException
448          * @throws HTTPException\ServiceUnavailableException
449          */
450         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)
451         {
452                 $moduleName = $args->getModuleName();
453
454                 $this->command = $moduleName;
455                 $this->method  = $args->getMethod();
456
457                 /* Create the page content.
458                  * Calls all hooks which are including content operations
459                  *
460                  * Sets the $Page->page['content'] variable
461                  */
462                 $timestamp = microtime(true);
463                 $this->initContent($response, $mode);
464
465                 // Load current theme info after module has been initialized as theme could have been set in module
466                 $currentTheme = $app->getCurrentTheme();
467                 $theme_info_file = 'view/theme/' . $currentTheme . '/theme.php';
468                 if (file_exists($theme_info_file)) {
469                         require_once $theme_info_file;
470                 }
471
472                 if (function_exists(str_replace('-', '_', $currentTheme) . '_init')) {
473                         $func = str_replace('-', '_', $currentTheme) . '_init';
474                         $func($app);
475                 }
476
477                 /* Create the page head after setting the language
478                  * and getting any auth credentials.
479                  *
480                  * Moved initHead() and initFooter() to after
481                  * all the module functions have executed so that all
482                  * theme choices made by the modules can take effect.
483                  */
484                 $this->initHead($app, $args, $l10n, $config, $pconfig, $localUID);
485
486                 /* Build the page ending -- this is stuff that goes right before
487                  * the closing </body> tag
488                  */
489                 $this->initFooter($app, $mode, $l10n);
490
491                 $profiler->set(microtime(true) - $timestamp, 'aftermath');
492
493                 if (!$mode->isAjax()) {
494                         Hook::callAll('page_end', $this->page['content']);
495                 }
496
497                 // Add the navigation (menu) template
498                 if ($moduleName != 'install' && $moduleName != 'maintenance') {
499                         $this->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('nav_head.tpl'), []);
500                         $this->page['nav']      = $nav->getHtml();
501                 }
502
503                 // Build the page - now that we have all the components
504                 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
505                         $doc = new DOMDocument();
506
507                         $target = new DOMDocument();
508                         $target->loadXML("<root></root>");
509
510                         $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
511
512                         /// @TODO one day, kill those error-suppressing @ stuff, or PHP should ban it
513                         @$doc->loadHTML($content);
514
515                         $xpath = new DOMXPath($doc);
516
517                         $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]");  /* */
518
519                         foreach ($list as $item) {
520                                 $item = $target->importNode($item, true);
521
522                                 // And then append it to the target
523                                 $target->documentElement->appendChild($item);
524                         }
525
526                         if ($_GET["mode"] == "raw") {
527                                 System::httpExit(substr($target->saveHTML(), 6, -8), Response::TYPE_HTML);
528                         }
529                 }
530
531                 $page    = $this->page;
532
533                 // add and escape some common but crucial content for direct "echo" in HTML (security)
534                 $page['title']   = htmlspecialchars($page['title'] ?? '');
535                 $page['section'] = htmlspecialchars($args->get(0) ?? 'generic');
536                 $page['module']  = htmlspecialchars($args->getModuleName() ?? '');
537
538                 header("X-Friendica-Version: " . App::VERSION);
539                 header("Content-type: text/html; charset=utf-8");
540
541                 if ($config->get('system', 'hsts') && ($baseURL->getScheme() === 'https')) {
542                         header("Strict-Transport-Security: max-age=31536000");
543                 }
544
545                 // Some security stuff
546                 header('X-Content-Type-Options: nosniff');
547                 header('X-XSS-Protection: 1; mode=block');
548                 header('X-Permitted-Cross-Domain-Policies: none');
549                 header('X-Frame-Options: sameorigin');
550
551                 // Things like embedded OSM maps don't work, when this is enabled
552                 // 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'");
553
554                 /* We use $_GET["mode"] for special page templates. So we will check if we have
555                  * to load another page template than the default one.
556                  * The page templates are located in /view/php/ or in the theme directory.
557                  */
558                 if (isset($_GET['mode'])) {
559                         $template = Theme::getPathForFile('php/' . Strings::sanitizeFilePathItem($_GET['mode']) . '.php');
560                 }
561
562                 // If there is no page template use the default page template
563                 if (empty($template)) {
564                         $template = Theme::getPathForFile('php/default.php');
565                 }
566
567                 // Theme templates expect $a as an App instance
568                 $a = $app;
569
570                 // Used as is in view/php/default.php
571                 $lang = $l10n->getCurrentLang();
572
573                 ob_start();
574                 require_once $template;
575                 $body = ob_get_clean();
576
577                 return $response->withBody(Utils::streamFor($body));
578         }
579 }