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