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