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