]> git.mxchange.org Git - friendica.git/blob - src/App/Page.php
63314561191a672b9ed8aced03a99bb3382e62b5
[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\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\Strings;
41 use Friendica\Util\Profiler;
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         ];
77         /**
78          * @var string The basepath of the page
79          */
80         private $basePath;
81
82         private $timestamp = 0;
83         private $method    = '';
84         private $module    = '';
85         private $command   = '';
86
87         /**
88          * @param string $basepath The Page basepath
89          */
90         public function __construct(string $basepath)
91         {
92                 $this->timestamp = microtime(true);
93                 $this->basePath = $basepath;
94         }
95
96         public function setLogging(string $method, string $module, string $command)
97         {
98                 $this->method  = $method;
99                 $this->module  = $module;
100                 $this->command = $command;
101         }
102
103         public function logRuntime(IManageConfigValues $config, string $origin = '')
104         {
105                 $ignore = $config->get('system', 'runtime_ignore');
106                 if (in_array($this->module, $ignore) || in_array($this->command, $ignore)) {
107                         return;
108                 }
109
110                 $signature = !empty($_SERVER['HTTP_SIGNATURE']);
111                 $load      = number_format(System::currentLoad(), 2);
112                 $runtime   = number_format(microtime(true) - $this->timestamp, 3);
113                 if ($runtime > $config->get('system', 'runtime_loglimit')) {
114                         Logger::debug('Runtime', ['method' => $this->method, 'module' => $this->module, 'runtime' => $runtime, 'load' => $load, 'origin' => $origin, 'signature' => $signature, 'request' => $_SERVER['REQUEST_URI'] ?? '']);
115                 }
116         }
117
118         /**
119          * Whether a offset exists
120          *
121          * @link  https://php.net/manual/en/arrayaccess.offsetexists.php
122          *
123          * @param mixed $offset <p>
124          *                      An offset to check for.
125          *                      </p>
126          *
127          * @return boolean true on success or false on failure.
128          * </p>
129          * <p>
130          * The return value will be casted to boolean if non-boolean was returned.
131          * @since 5.0.0
132          */
133         public function offsetExists($offset)
134         {
135                 return isset($this->page[$offset]);
136         }
137
138         /**
139          * Offset to retrieve
140          *
141          * @link  https://php.net/manual/en/arrayaccess.offsetget.php
142          *
143          * @param mixed $offset <p>
144          *                      The offset to retrieve.
145          *                      </p>
146          *
147          * @return mixed Can return all value types.
148          * @since 5.0.0
149          */
150         public function offsetGet($offset)
151         {
152                 return $this->page[$offset] ?? null;
153         }
154
155         /**
156          * Offset to set
157          *
158          * @link  https://php.net/manual/en/arrayaccess.offsetset.php
159          *
160          * @param mixed $offset <p>
161          *                      The offset to assign the value to.
162          *                      </p>
163          * @param mixed $value  <p>
164          *                      The value to set.
165          *                      </p>
166          *
167          * @return void
168          * @since 5.0.0
169          */
170         public function offsetSet($offset, $value)
171         {
172                 $this->page[$offset] = $value;
173         }
174
175         /**
176          * Offset to unset
177          *
178          * @link  https://php.net/manual/en/arrayaccess.offsetunset.php
179          *
180          * @param mixed $offset <p>
181          *                      The offset to unset.
182          *                      </p>
183          *
184          * @return void
185          * @since 5.0.0
186          */
187         public function offsetUnset($offset)
188         {
189                 if (isset($this->page[$offset])) {
190                         unset($this->page[$offset]);
191                 }
192         }
193
194         /**
195          * Register a stylesheet file path to be included in the <head> tag of every page.
196          * Inclusion is done in App->initHead().
197          * The path can be absolute or relative to the Friendica installation base folder.
198          *
199          * @param string $path
200          * @param string $media
201          * @see Page::initHead()
202          */
203         public function registerStylesheet(string $path, string $media = 'screen')
204         {
205                 $path = Network::appendQueryParam($path, ['v' => FRIENDICA_VERSION]);
206
207                 if (mb_strpos($path, $this->basePath . DIRECTORY_SEPARATOR) === 0) {
208                         $path = mb_substr($path, mb_strlen($this->basePath . DIRECTORY_SEPARATOR));
209                 }
210
211                 $this->stylesheets[trim($path, '/')] = $media;
212         }
213
214         /**
215          * Initializes Page->page['htmlhead'].
216          *
217          * Includes:
218          * - Page title
219          * - Favicons
220          * - Registered stylesheets (through App->registerStylesheet())
221          * - Infinite scroll data
222          * - head.tpl template
223          *
224          * @param App                         $app     The Friendica App instance
225          * @param Arguments                   $args    The Friendica App Arguments
226          * @param L10n                        $l10n    The l10n language instance
227          * @param IManageConfigValues         $config  The Friendica configuration
228          * @param IManagePersonalConfigValues $pConfig The Friendica personal configuration (for user)
229          *
230          * @throws HTTPException\InternalServerErrorException
231          */
232         private function initHead(App $app, Arguments $args, L10n $l10n, IManageConfigValues $config, IManagePersonalConfigValues $pConfig)
233         {
234                 $interval = ((local_user()) ? $pConfig->get(local_user(), 'system', 'update_interval') : 40000);
235
236                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
237                 if ($interval < 0) {
238                         $interval = 2147483647;
239                 }
240
241                 if ($interval < 10000) {
242                         $interval = 40000;
243                 }
244
245                 // Default title: current module called
246                 if (empty($this->page['title']) && $args->getModuleName()) {
247                         $this->page['title'] = ucfirst($args->getModuleName());
248                 }
249
250                 // Prepend the sitename to the page title
251                 $this->page['title'] = $config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
252
253                 if (!empty(Renderer::$theme['stylesheet'])) {
254                         $stylesheet = Renderer::$theme['stylesheet'];
255                 } else {
256                         $stylesheet = $app->getCurrentThemeStylesheetPath();
257                 }
258
259                 $this->registerStylesheet($stylesheet);
260
261                 $shortcut_icon = $config->get('system', 'shortcut_icon');
262                 if ($shortcut_icon == '') {
263                         $shortcut_icon = 'images/friendica.svg';
264                 }
265
266                 $touch_icon = $config->get('system', 'touch_icon');
267                 if ($touch_icon == '') {
268                         $touch_icon = 'images/friendica-192.png';
269                 }
270
271                 Hook::callAll('head', $this->page['htmlhead']);
272
273                 $tpl = Renderer::getMarkupTemplate('head.tpl');
274                 /* put the head template at the beginning of page['htmlhead']
275                  * since the code added by the modules frequently depends on it
276                  * being first
277                  */
278                 $this->page['htmlhead'] = Renderer::replaceMacros($tpl, [
279                         '$local_user'      => local_user(),
280                         '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
281                         '$delitem'         => $l10n->t('Delete this item?'),
282                         '$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.'),
283                         '$update_interval' => $interval,
284                         '$shortcut_icon'   => $shortcut_icon,
285                         '$touch_icon'      => $touch_icon,
286                         '$block_public'    => intval($config->get('system', 'block_public')),
287                         '$stylesheets'     => $this->stylesheets,
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' => FRIENDICA_VERSION]);
399
400                 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
401
402                 $this->footerScripts[] = trim($url, '/');
403         }
404
405         /**
406          * Directly exit with the current response (include setting all headers)
407          *
408          * @param ResponseInterface $response
409          */
410         public function exit(ResponseInterface $response)
411         {
412                 header(sprintf("HTTP/%s %s %s",
413                         $response->getProtocolVersion(),
414                         $response->getStatusCode(),
415                         $response->getReasonPhrase())
416                 );
417
418                 foreach ($response->getHeaders() as $key => $header) {
419                         if (is_array($header)) {
420                                 $header_str = implode(',', $header);
421                         } else {
422                                 $header_str = $header;
423                         }
424
425                         if (empty($key)) {
426                                 header($header_str);
427                         } else {
428                                 header("$key: $header_str");
429                         }
430                 }
431
432                 echo $response->getBody();
433         }
434
435         /**
436          * Executes the creation of the current page and prints it to the screen
437          *
438          * @param App                         $app      The Friendica App
439          * @param BaseURL                     $baseURL  The Friendica Base URL
440          * @param Arguments                   $args     The Friendica App arguments
441          * @param Mode                        $mode     The current node mode
442          * @param ResponseInterface           $response The Response of the module class, including type, content & headers
443          * @param L10n                        $l10n     The l10n language class
444          * @param IManageConfigValues         $config   The Configuration of this node
445          * @param IManagePersonalConfigValues $pconfig  The personal/user configuration
446          *
447          * @throws HTTPException\InternalServerErrorException|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)
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);
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::build($app);
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-surpressing @ 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                 header("X-Friendica-Version: " . FRIENDICA_VERSION);
547                 header("Content-type: text/html; charset=utf-8");
548
549                 if ($config->get('system', 'hsts') && ($baseURL->getSSLPolicy() == BaseURL::SSL_POLICY_FULL)) {
550                         header("Strict-Transport-Security: max-age=31536000");
551                 }
552
553                 // Some security stuff
554                 header('X-Content-Type-Options: nosniff');
555                 header('X-XSS-Protection: 1; mode=block');
556                 header('X-Permitted-Cross-Domain-Policies: none');
557                 header('X-Frame-Options: sameorigin');
558
559                 // Things like embedded OSM maps don't work, when this is enabled
560                 // 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'");
561
562                 /* We use $_GET["mode"] for special page templates. So we will check if we have
563                  * to load another page template than the default one.
564                  * The page templates are located in /view/php/ or in the theme directory.
565                  */
566                 if (isset($_GET['mode'])) {
567                         $template = Theme::getPathForFile('php/' . Strings::sanitizeFilePathItem($_GET['mode']) . '.php');
568                 }
569
570                 // If there is no page template use the default page template
571                 if (empty($template)) {
572                         $template = Theme::getPathForFile('php/default.php');
573                 }
574
575                 // Theme templates expect $a as an App instance
576                 $a = $app;
577
578                 // Used as is in view/php/default.php
579                 $lang = $l10n->getCurrentLang();
580
581                 require_once $template;
582         }
583 }