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