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