]> git.mxchange.org Git - friendica.git/blob - src/App/Page.php
Make PHP-CS happy
[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         // ArrayAccess interface
119
120         /**
121          * @inheritDoc
122          */
123         #[\ReturnTypeWillChange]
124         public function offsetExists($offset): bool
125         {
126                 return isset($this->page[$offset]);
127         }
128
129         /**
130          * @inheritDoc
131          */
132         #[\ReturnTypeWillChange]
133         public function offsetGet($offset)
134         {
135                 return $this->page[$offset] ?? null;
136         }
137
138         /**
139          * @inheritDoc
140          */
141         #[\ReturnTypeWillChange]
142         public function offsetSet($offset, $value): void
143         {
144                 $this->page[$offset] = $value;
145         }
146
147         /**
148          * @inheritDoc
149          */
150         #[\ReturnTypeWillChange]
151         public function offsetUnset($offset): void
152         {
153                 if (isset($this->page[$offset])) {
154                         unset($this->page[$offset]);
155                 }
156         }
157
158         /**
159          * Register a stylesheet file path to be included in the <head> tag of every page.
160          * Inclusion is done in App->initHead().
161          * The path can be absolute or relative to the Friendica installation base folder.
162          *
163          * @param string $path
164          * @param string $media
165          * @see Page::initHead()
166          */
167         public function registerStylesheet(string $path, string $media = 'screen')
168         {
169                 $path = Network::appendQueryParam($path, ['v' => App::VERSION]);
170
171                 if (mb_strpos($path, $this->basePath . DIRECTORY_SEPARATOR) === 0) {
172                         $path = mb_substr($path, mb_strlen($this->basePath . DIRECTORY_SEPARATOR));
173                 }
174
175                 $this->stylesheets[trim($path, '/')] = $media;
176         }
177
178         /**
179          * Initializes Page->page['htmlhead'].
180          *
181          * Includes:
182          * - Page title
183          * - Favicons
184          * - Registered stylesheets (through App->registerStylesheet())
185          * - Infinite scroll data
186          * - head.tpl template
187          *
188          * @param App                         $app      The Friendica App instance
189          * @param Arguments                   $args     The Friendica App Arguments
190          * @param L10n                        $l10n     The l10n language instance
191          * @param IManageConfigValues         $config   The Friendica configuration
192          * @param IManagePersonalConfigValues $pConfig  The Friendica personal configuration (for user)
193          * @param int                         $localUID The local user id
194          *
195          * @throws HTTPException\InternalServerErrorException
196          */
197         private function initHead(App $app, Arguments $args, L10n $l10n, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, int $localUID)
198         {
199                 $interval = ($localUID ? $pConfig->get($localUID, 'system', 'update_interval') : 40000);
200
201                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
202                 if ($interval < 0) {
203                         $interval = 2147483647;
204                 }
205
206                 if ($interval < 10000) {
207                         $interval = 40000;
208                 }
209
210                 // Default title: current module called
211                 if (empty($this->page['title']) && $args->getModuleName()) {
212                         $this->page['title'] = ucfirst($args->getModuleName());
213                 }
214
215                 // Prepend the sitename to the page title
216                 $this->page['title'] = $config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
217
218                 if (!empty(Renderer::$theme['stylesheet'])) {
219                         $stylesheet = Renderer::$theme['stylesheet'];
220                 } else {
221                         $stylesheet = $app->getCurrentThemeStylesheetPath();
222                 }
223
224                 $this->registerStylesheet($stylesheet);
225
226                 $shortcut_icon = $config->get('system', 'shortcut_icon');
227                 if ($shortcut_icon == '') {
228                         $shortcut_icon = 'images/friendica.svg';
229                 }
230
231                 $touch_icon = $config->get('system', 'touch_icon');
232                 if ($touch_icon == '') {
233                         $touch_icon = 'images/friendica-192.png';
234                 }
235
236                 Hook::callAll('head', $this->page['htmlhead']);
237
238                 $tpl = Renderer::getMarkupTemplate('head.tpl');
239                 /* put the head template at the beginning of page['htmlhead']
240                  * since the code added by the modules frequently depends on it
241                  * being first
242                  */
243                 $this->page['htmlhead'] = Renderer::replaceMacros($tpl, [
244                         '$local_nickname'  => $app->getLoggedInUserNickname(),
245                         '$local_user'      => $localUID,
246                         '$generator'       => 'Friendica' . ' ' . App::VERSION,
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                         '$update_interval' => $interval,
250                         '$shortcut_icon'   => $shortcut_icon,
251                         '$touch_icon'      => $touch_icon,
252                         '$block_public'    => intval($config->get('system', 'block_public')),
253                         '$stylesheets'     => $this->stylesheets,
254                 ]) . $this->page['htmlhead'];
255         }
256
257         /**
258          * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
259          *
260          * Taken from http://webcheatsheet.com/php/get_current_page_url.php
261          */
262         private function curPageURL(): string
263         {
264                 $pageURL = 'http';
265                 if (!empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {
266                         $pageURL .= "s";
267                 }
268
269                 $pageURL .= "://";
270
271                 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
272                         $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
273                 } else {
274                         $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
275                 }
276                 return $pageURL;
277         }
278
279         /**
280          * Initializes Page->page['footer'].
281          *
282          * Includes:
283          * - Javascript homebase
284          * - Mobile toggle link
285          * - Registered footer scripts (through App->registerFooterScript())
286          * - footer.tpl template
287          *
288          * @param App  $app  The Friendica App instance
289          * @param Mode $mode The Friendica runtime mode
290          * @param L10n $l10n The l10n instance
291          *
292          * @throws HTTPException\InternalServerErrorException
293          */
294         private function initFooter(App $app, Mode $mode, L10n $l10n)
295         {
296                 // If you're just visiting, let javascript take you home
297                 if (!empty($_SESSION['visitor_home'])) {
298                         $homebase = $_SESSION['visitor_home'];
299                 } elseif (!empty($app->getLoggedInUserNickname())) {
300                         $homebase = 'profile/' . $app->getLoggedInUserNickname();
301                 }
302
303                 if (isset($homebase)) {
304                         $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
305                 }
306
307                 /*
308                  * Add a "toggle mobile" link if we're using a mobile device
309                  */
310                 if ($mode->isMobile() || $mode->isTablet()) {
311                         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
312                                 $link = 'toggle_mobile?address=' . urlencode($this->curPageURL());
313                         } else {
314                                 $link = 'toggle_mobile?off=1&address=' . urlencode($this->curPageURL());
315                         }
316                         $this->page['footer'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
317                                 '$toggle_link' => $link,
318                                 '$toggle_text' => $l10n->t('toggle mobile')
319                         ]);
320                 }
321
322                 Hook::callAll('footer', $this->page['footer']);
323
324                 $tpl                  = Renderer::getMarkupTemplate('footer.tpl');
325                 $this->page['footer'] = Renderer::replaceMacros($tpl, [
326                         '$footerScripts' => array_unique($this->footerScripts),
327                 ]) . $this->page['footer'];
328         }
329
330         /**
331          * Initializes Page->page['content'].
332          *
333          * Includes:
334          * - module content
335          * - hooks for content
336          *
337          * @param ResponseInterface  $response The Module response class
338          * @param Mode               $mode     The Friendica execution mode
339          *
340          * @throws HTTPException\InternalServerErrorException
341          */
342         private function initContent(ResponseInterface $response, Mode $mode)
343         {
344                 // initialise content region
345                 if ($mode->isNormal()) {
346                         Hook::callAll('page_content_top', $this->page['content']);
347                 }
348
349                 $this->page['content'] .= (string)$response->getBody();
350         }
351
352         /**
353          * Register a javascript file path to be included in the <footer> tag of every page.
354          * Inclusion is done in App->initFooter().
355          * The path can be absolute or relative to the Friendica installation base folder.
356          *
357          * @param string $path
358          *
359          * @see Page::initFooter()
360          *
361          */
362         public function registerFooterScript($path)
363         {
364                 $path = Network::appendQueryParam($path, ['v' => App::VERSION]);
365
366                 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
367
368                 $this->footerScripts[] = trim($url, '/');
369         }
370
371         /**
372          * Directly exit with the current response (include setting all headers)
373          *
374          * @param ResponseInterface $response
375          */
376         public function exit(ResponseInterface $response)
377         {
378                 header(sprintf("HTTP/%s %s %s",
379                         $response->getProtocolVersion(),
380                         $response->getStatusCode(),
381                         $response->getReasonPhrase())
382                 );
383
384                 foreach ($response->getHeaders() as $key => $header) {
385                         if (is_array($header)) {
386                                 $header_str = implode(',', $header);
387                         } else {
388                                 $header_str = $header;
389                         }
390
391                         if (empty($key)) {
392                                 header($header_str);
393                         } else {
394                                 header("$key: $header_str");
395                         }
396                 }
397
398                 echo $response->getBody();
399         }
400
401         /**
402          * Executes the creation of the current page and prints it to the screen
403          *
404          * @param App                         $app      The Friendica App
405          * @param BaseURL                     $baseURL  The Friendica Base URL
406          * @param Arguments                   $args     The Friendica App arguments
407          * @param Mode                        $mode     The current node mode
408          * @param ResponseInterface           $response The Response of the module class, including type, content & headers
409          * @param L10n                        $l10n     The l10n language class
410          * @param IManageConfigValues         $config   The Configuration of this node
411          * @param IManagePersonalConfigValues $pconfig  The personal/user configuration
412          * @param int                         $localUID The UID of the local user
413          *
414          * @throws HTTPException\InternalServerErrorException|HTTPException\ServiceUnavailableException
415          */
416         public function run(App $app, BaseURL $baseURL, Arguments $args, Mode $mode, ResponseInterface $response, L10n $l10n, Profiler $profiler, IManageConfigValues $config, IManagePersonalConfigValues $pconfig, int $localUID)
417         {
418                 $moduleName = $args->getModuleName();
419
420                 $this->command = $moduleName;
421                 $this->method  = $args->getMethod();
422
423                 /* Create the page content.
424                  * Calls all hooks which are including content operations
425                  *
426                  * Sets the $Page->page['content'] variable
427                  */
428                 $timestamp = microtime(true);
429                 $this->initContent($response, $mode);
430
431                 // Load current theme info after module has been initialized as theme could have been set in module
432                 $currentTheme = $app->getCurrentTheme();
433                 $theme_info_file = 'view/theme/' . $currentTheme . '/theme.php';
434                 if (file_exists($theme_info_file)) {
435                         require_once $theme_info_file;
436                 }
437
438                 if (function_exists(str_replace('-', '_', $currentTheme) . '_init')) {
439                         $func = str_replace('-', '_', $currentTheme) . '_init';
440                         $func($app);
441                 }
442
443                 /* Create the page head after setting the language
444                  * and getting any auth credentials.
445                  *
446                  * Moved initHead() and initFooter() to after
447                  * all the module functions have executed so that all
448                  * theme choices made by the modules can take effect.
449                  */
450                 $this->initHead($app, $args, $l10n, $config, $pconfig, $localUID);
451
452                 /* Build the page ending -- this is stuff that goes right before
453                  * the closing </body> tag
454                  */
455                 $this->initFooter($app, $mode, $l10n);
456
457                 $profiler->set(microtime(true) - $timestamp, 'aftermath');
458
459                 if (!$mode->isAjax()) {
460                         Hook::callAll('page_end', $this->page['content']);
461                 }
462
463                 // Add the navigation (menu) template
464                 if ($moduleName != 'install' && $moduleName != 'maintenance') {
465                         $this->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('nav_head.tpl'), []);
466                         $this->page['nav']      = Nav::build($app);
467                 }
468
469                 foreach ($response->getHeaders() as $key => $header) {
470                         if (is_array($header)) {
471                                 $header_str = implode(',', $header);
472                         } else {
473                                 $header_str = $header;
474                         }
475
476                         if (empty($key)) {
477                                 header($header_str);
478                         } else {
479                                 header("$key: $header_str");
480                         }
481                 }
482
483                 // Build the page - now that we have all the components
484                 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
485                         $doc = new DOMDocument();
486
487                         $target = new DOMDocument();
488                         $target->loadXML("<root></root>");
489
490                         $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
491
492                         /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
493                         @$doc->loadHTML($content);
494
495                         $xpath = new DOMXPath($doc);
496
497                         $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]");  /* */
498
499                         foreach ($list as $item) {
500                                 $item = $target->importNode($item, true);
501
502                                 // And then append it to the target
503                                 $target->documentElement->appendChild($item);
504                         }
505
506                         if ($_GET["mode"] == "raw") {
507                                 System::httpExit(substr($target->saveHTML(), 6, -8), Response::TYPE_HTML);
508                         }
509                 }
510
511                 $page    = $this->page;
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->getSSLPolicy() == BaseURL::SSL_POLICY_FULL)) {
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                 require_once $template;
549         }
550 }