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