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