]> git.mxchange.org Git - friendica.git/blob - src/App/Page.php
d1aa17ad072ad0cc7dfa42b3628015c732508f82
[friendica.git] / src / App / Page.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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\PConfig\Capability\IManagePersonalConfigValues;
31 use Friendica\Core\Hook;
32 use Friendica\Core\L10n;
33 use Friendica\Core\Logger;
34 use Friendica\Core\Renderer;
35 use Friendica\Core\Session;
36 use Friendica\Core\System;
37 use Friendica\Core\Theme;
38 use Friendica\Module\Response;
39 use Friendica\Network\HTTPException;
40 use Friendica\Util\Network;
41 use Friendica\Util\Strings;
42 use Friendica\Util\Profiler;
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         ];
78         /**
79          * @var string The basepath of the page
80          */
81         private $basePath;
82
83         private $timestamp = 0;
84         private $method    = '';
85         private $module    = '';
86         private $command   = '';
87
88         /**
89          * @param string $basepath The Page basepath
90          */
91         public function __construct(string $basepath)
92         {
93                 $this->timestamp = microtime(true);
94                 $this->basePath = $basepath;
95         }
96
97         public function setLogging(string $method, string $module, string $command)
98         {
99                 $this->method  = $method;
100                 $this->module  = $module;
101                 $this->command = $command;
102         }
103
104         public function logRuntime(IManageConfigValues $config, string $origin = '')
105         {
106                 $ignore = $config->get('system', 'runtime_ignore');
107                 if (in_array($this->module, $ignore) || in_array($this->command, $ignore)) {
108                         return;
109                 }
110
111                 $signature = !empty($_SERVER['HTTP_SIGNATURE']);
112                 $load      = number_format(System::currentLoad(), 2);
113                 $runtime   = number_format(microtime(true) - $this->timestamp, 3);
114                 if ($runtime > $config->get('system', 'runtime_loglimit')) {
115                         Logger::debug('Runtime', ['method' => $this->method, 'module' => $this->module, 'runtime' => $runtime, 'load' => $load, 'origin' => $origin, 'signature' => $signature, 'request' => $_SERVER['REQUEST_URI'] ?? '']);
116                 }
117         }
118
119         /**
120          * Whether a offset exists
121          *
122          * @link  https://php.net/manual/en/arrayaccess.offsetexists.php
123          *
124          * @param mixed $offset <p>
125          *                      An offset to check for.
126          *                      </p>
127          *
128          * @return boolean true on success or false on failure.
129          * </p>
130          * <p>
131          * The return value will be casted to boolean if non-boolean was returned.
132          * @since 5.0.0
133          */
134         public function offsetExists($offset)
135         {
136                 return isset($this->page[$offset]);
137         }
138
139         /**
140          * Offset to retrieve
141          *
142          * @link  https://php.net/manual/en/arrayaccess.offsetget.php
143          *
144          * @param mixed $offset <p>
145          *                      The offset to retrieve.
146          *                      </p>
147          *
148          * @return mixed Can return all value types.
149          * @since 5.0.0
150          */
151         public function offsetGet($offset)
152         {
153                 return $this->page[$offset] ?? null;
154         }
155
156         /**
157          * Offset to set
158          *
159          * @link  https://php.net/manual/en/arrayaccess.offsetset.php
160          *
161          * @param mixed $offset <p>
162          *                      The offset to assign the value to.
163          *                      </p>
164          * @param mixed $value  <p>
165          *                      The value to set.
166          *                      </p>
167          *
168          * @return void
169          * @since 5.0.0
170          */
171         public function offsetSet($offset, $value)
172         {
173                 $this->page[$offset] = $value;
174         }
175
176         /**
177          * Offset to unset
178          *
179          * @link  https://php.net/manual/en/arrayaccess.offsetunset.php
180          *
181          * @param mixed $offset <p>
182          *                      The offset to unset.
183          *                      </p>
184          *
185          * @return void
186          * @since 5.0.0
187          */
188         public function offsetUnset($offset)
189         {
190                 if (isset($this->page[$offset])) {
191                         unset($this->page[$offset]);
192                 }
193         }
194
195         /**
196          * Register a stylesheet file path to be included in the <head> tag of every page.
197          * Inclusion is done in App->initHead().
198          * The path can be absolute or relative to the Friendica installation base folder.
199          *
200          * @param string $path
201          * @param string $media
202          * @see Page::initHead()
203          */
204         public function registerStylesheet(string $path, string $media = 'screen')
205         {
206                 $path = Network::appendQueryParam($path, ['v' => App::VERSION]);
207
208                 if (mb_strpos($path, $this->basePath . DIRECTORY_SEPARATOR) === 0) {
209                         $path = mb_substr($path, mb_strlen($this->basePath . DIRECTORY_SEPARATOR));
210                 }
211
212                 $this->stylesheets[trim($path, '/')] = $media;
213         }
214
215         /**
216          * Initializes Page->page['htmlhead'].
217          *
218          * Includes:
219          * - Page title
220          * - Favicons
221          * - Registered stylesheets (through App->registerStylesheet())
222          * - Infinite scroll data
223          * - head.tpl template
224          *
225          * @param App                         $app     The Friendica App instance
226          * @param Arguments                   $args    The Friendica App Arguments
227          * @param L10n                        $l10n    The l10n language instance
228          * @param IManageConfigValues         $config  The Friendica configuration
229          * @param IManagePersonalConfigValues $pConfig The Friendica personal configuration (for user)
230          *
231          * @throws HTTPException\InternalServerErrorException
232          */
233         private function initHead(App $app, Arguments $args, L10n $l10n, IManageConfigValues $config, IManagePersonalConfigValues $pConfig)
234         {
235                 $interval = ((Session::getLocalUser()) ? $pConfig->get(Session::getLocalUser(), 'system', 'update_interval') : 40000);
236
237                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
238                 if ($interval < 0) {
239                         $interval = 2147483647;
240                 }
241
242                 if ($interval < 10000) {
243                         $interval = 40000;
244                 }
245
246                 // Default title: current module called
247                 if (empty($this->page['title']) && $args->getModuleName()) {
248                         $this->page['title'] = ucfirst($args->getModuleName());
249                 }
250
251                 // Prepend the sitename to the page title
252                 $this->page['title'] = $config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
253
254                 if (!empty(Renderer::$theme['stylesheet'])) {
255                         $stylesheet = Renderer::$theme['stylesheet'];
256                 } else {
257                         $stylesheet = $app->getCurrentThemeStylesheetPath();
258                 }
259
260                 $this->registerStylesheet($stylesheet);
261
262                 $shortcut_icon = $config->get('system', 'shortcut_icon');
263                 if ($shortcut_icon == '') {
264                         $shortcut_icon = 'images/friendica.svg';
265                 }
266
267                 $touch_icon = $config->get('system', 'touch_icon');
268                 if ($touch_icon == '') {
269                         $touch_icon = 'images/friendica-192.png';
270                 }
271
272                 Hook::callAll('head', $this->page['htmlhead']);
273
274                 $tpl = Renderer::getMarkupTemplate('head.tpl');
275                 /* put the head template at the beginning of page['htmlhead']
276                  * since the code added by the modules frequently depends on it
277                  * being first
278                  */
279                 $this->page['htmlhead'] = Renderer::replaceMacros($tpl, [
280                         '$local_user'      => Session::getLocalUser(),
281                         '$generator'       => 'Friendica' . ' ' . App::VERSION,
282                         '$delitem'         => $l10n->t('Delete this item?'),
283                         '$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.'),
284                         '$update_interval' => $interval,
285                         '$shortcut_icon'   => $shortcut_icon,
286                         '$touch_icon'      => $touch_icon,
287                         '$block_public'    => intval($config->get('system', 'block_public')),
288                         '$stylesheets'     => $this->stylesheets,
289                 ]) . $this->page['htmlhead'];
290         }
291
292         /**
293          * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
294          *
295          * Taken from http://webcheatsheet.com/php/get_current_page_url.php
296          */
297         private function curPageURL(): string
298         {
299                 $pageURL = 'http';
300                 if (!empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {
301                         $pageURL .= "s";
302                 }
303
304                 $pageURL .= "://";
305
306                 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
307                         $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
308                 } else {
309                         $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
310                 }
311                 return $pageURL;
312         }
313       
314         /**
315          * Initializes Page->page['footer'].
316          *
317          * Includes:
318          * - Javascript homebase
319          * - Mobile toggle link
320          * - Registered footer scripts (through App->registerFooterScript())
321          * - footer.tpl template
322          *
323          * @param App  $app  The Friendica App instance
324          * @param Mode $mode The Friendica runtime mode
325          * @param L10n $l10n The l10n instance
326          *
327          * @throws HTTPException\InternalServerErrorException
328          */
329         private function initFooter(App $app, Mode $mode, L10n $l10n)
330         {
331                 // If you're just visiting, let javascript take you home
332                 if (!empty($_SESSION['visitor_home'])) {
333                         $homebase = $_SESSION['visitor_home'];
334                 } elseif (!empty($app->getLoggedInUserNickname())) {
335                         $homebase = 'profile/' . $app->getLoggedInUserNickname();
336                 }
337
338                 if (isset($homebase)) {
339                         $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
340                 }
341
342                 /*
343                  * Add a "toggle mobile" link if we're using a mobile device
344                  */
345                 if ($mode->isMobile() || $mode->isTablet()) {
346                         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
347                                 $link = 'toggle_mobile?address=' . urlencode($this->curPageURL());
348                         } else {
349                                 $link = 'toggle_mobile?off=1&address=' . urlencode($this->curPageURL());
350                         }
351                         $this->page['footer'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
352                                 '$toggle_link' => $link,
353                                 '$toggle_text' => $l10n->t('toggle mobile')
354                         ]);
355                 }
356
357                 Hook::callAll('footer', $this->page['footer']);
358
359                 $tpl                  = Renderer::getMarkupTemplate('footer.tpl');
360                 $this->page['footer'] = Renderer::replaceMacros($tpl, [
361                         '$footerScripts' => array_unique($this->footerScripts),
362                 ]) . $this->page['footer'];
363         }
364
365         /**
366          * Initializes Page->page['content'].
367          *
368          * Includes:
369          * - module content
370          * - hooks for content
371          *
372          * @param ResponseInterface  $response The Module response class
373          * @param Mode               $mode     The Friendica execution mode
374          *
375          * @throws HTTPException\InternalServerErrorException
376          */
377         private function initContent(ResponseInterface $response, Mode $mode)
378         {
379                 // initialise content region
380                 if ($mode->isNormal()) {
381                         Hook::callAll('page_content_top', $this->page['content']);
382                 }
383
384                 $this->page['content'] .= (string)$response->getBody();
385         }
386
387         /**
388          * Register a javascript file path to be included in the <footer> tag of every page.
389          * Inclusion is done in App->initFooter().
390          * The path can be absolute or relative to the Friendica installation base folder.
391          *
392          * @param string $path
393          *
394          * @see Page::initFooter()
395          *
396          */
397         public function registerFooterScript($path)
398         {
399                 $path = Network::appendQueryParam($path, ['v' => App::VERSION]);
400
401                 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
402
403                 $this->footerScripts[] = trim($url, '/');
404         }
405
406         /**
407          * Directly exit with the current response (include setting all headers)
408          *
409          * @param ResponseInterface $response
410          */
411         public function exit(ResponseInterface $response)
412         {
413                 header(sprintf("HTTP/%s %s %s",
414                         $response->getProtocolVersion(),
415                         $response->getStatusCode(),
416                         $response->getReasonPhrase())
417                 );
418
419                 foreach ($response->getHeaders() as $key => $header) {
420                         if (is_array($header)) {
421                                 $header_str = implode(',', $header);
422                         } else {
423                                 $header_str = $header;
424                         }
425
426                         if (empty($key)) {
427                                 header($header_str);
428                         } else {
429                                 header("$key: $header_str");
430                         }
431                 }
432
433                 echo $response->getBody();
434         }
435
436         /**
437          * Executes the creation of the current page and prints it to the screen
438          *
439          * @param App                         $app      The Friendica App
440          * @param BaseURL                     $baseURL  The Friendica Base URL
441          * @param Arguments                   $args     The Friendica App arguments
442          * @param Mode                        $mode     The current node mode
443          * @param ResponseInterface           $response The Response of the module class, including type, content & headers
444          * @param L10n                        $l10n     The l10n language class
445          * @param IManageConfigValues         $config   The Configuration of this node
446          * @param IManagePersonalConfigValues $pconfig  The personal/user configuration
447          *
448          * @throws HTTPException\InternalServerErrorException|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)
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);
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::build($app);
501                 }
502
503                 foreach ($response->getHeaders() as $key => $header) {
504                         if (is_array($header)) {
505                                 $header_str = implode(',', $header);
506                         } else {
507                                 $header_str = $header;
508                         }
509
510                         if (empty($key)) {
511                                 header($header_str);
512                         } else {
513                                 header("$key: $header_str");
514                         }
515                 }
516
517                 // Build the page - now that we have all the components
518                 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
519                         $doc = new DOMDocument();
520
521                         $target = new DOMDocument();
522                         $target->loadXML("<root></root>");
523
524                         $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
525
526                         /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
527                         @$doc->loadHTML($content);
528
529                         $xpath = new DOMXPath($doc);
530
531                         $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]");  /* */
532
533                         foreach ($list as $item) {
534                                 $item = $target->importNode($item, true);
535
536                                 // And then append it to the target
537                                 $target->documentElement->appendChild($item);
538                         }
539
540                         if ($_GET["mode"] == "raw") {
541                                 System::httpExit(substr($target->saveHTML(), 6, -8), Response::TYPE_HTML);
542                         }
543                 }
544
545                 $page    = $this->page;
546
547                 header("X-Friendica-Version: " . App::VERSION);
548                 header("Content-type: text/html; charset=utf-8");
549
550                 if ($config->get('system', 'hsts') && ($baseURL->getSSLPolicy() == BaseURL::SSL_POLICY_FULL)) {
551                         header("Strict-Transport-Security: max-age=31536000");
552                 }
553
554                 // Some security stuff
555                 header('X-Content-Type-Options: nosniff');
556                 header('X-XSS-Protection: 1; mode=block');
557                 header('X-Permitted-Cross-Domain-Policies: none');
558                 header('X-Frame-Options: sameorigin');
559
560                 // Things like embedded OSM maps don't work, when this is enabled
561                 // 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'");
562
563                 /* We use $_GET["mode"] for special page templates. So we will check if we have
564                  * to load another page template than the default one.
565                  * The page templates are located in /view/php/ or in the theme directory.
566                  */
567                 if (isset($_GET['mode'])) {
568                         $template = Theme::getPathForFile('php/' . Strings::sanitizeFilePathItem($_GET['mode']) . '.php');
569                 }
570
571                 // If there is no page template use the default page template
572                 if (empty($template)) {
573                         $template = Theme::getPathForFile('php/default.php');
574                 }
575
576                 // Theme templates expect $a as an App instance
577                 $a = $app;
578
579                 // Used as is in view/php/default.php
580                 $lang = $l10n->getCurrentLang();
581
582                 require_once $template;
583         }
584 }