]> git.mxchange.org Git - friendica.git/blob - src/App/Page.php
Merge pull request #9602 from AndyHee/patch-20201125
[friendica.git] / src / App / Page.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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\IConfig;
30 use Friendica\Core\PConfig\IPConfig;
31 use Friendica\Core\Hook;
32 use Friendica\Core\L10n;
33 use Friendica\Core\Renderer;
34 use Friendica\Core\Theme;
35 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
36 use Friendica\Network\HTTPException;
37 use Friendica\Util\Network;
38 use Friendica\Util\Strings;
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 Module   $module  The loaded Friendica module
194          * @param L10n     $l10n    The l10n language instance
195          * @param IConfig  $config  The Friendica configuration
196          * @param IPConfig $pConfig The Friendica personal configuration (for user)
197          *
198          * @throws HTTPException\InternalServerErrorException
199          */
200         private function initHead(App $app, Module $module, L10n $l10n, IConfig $config, IPConfig $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']) && $module->getName()) {
215                         $this->page['title'] = ucfirst($module->getName());
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                         '$update_interval' => $interval,
251                         '$shortcut_icon'   => $shortcut_icon,
252                         '$touch_icon'      => $touch_icon,
253                         '$block_public'    => intval($config->get('system', 'block_public')),
254                         '$stylesheets'     => $this->stylesheets,
255                 ]) . $this->page['htmlhead'];
256         }
257
258         /**
259          * Initializes Page->page['footer'].
260          *
261          * Includes:
262          * - Javascript homebase
263          * - Mobile toggle link
264          * - Registered footer scripts (through App->registerFooterScript())
265          * - footer.tpl template
266          *
267          * @param App  $app  The Friendica App instance
268          * @param Mode $mode The Friendica runtime mode
269          * @param L10n $l10n The l10n instance
270          *
271          * @throws HTTPException\InternalServerErrorException
272          */
273         private function initFooter(App $app, Mode $mode, L10n $l10n)
274         {
275                 // If you're just visiting, let javascript take you home
276                 if (!empty($_SESSION['visitor_home'])) {
277                         $homebase = $_SESSION['visitor_home'];
278                 } elseif (!empty($app->user['nickname'])) {
279                         $homebase = 'profile/' . $app->user['nickname'];
280                 }
281
282                 if (isset($homebase)) {
283                         $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
284                 }
285
286                 /*
287                  * Add a "toggle mobile" link if we're using a mobile device
288                  */
289                 if ($mode->isMobile() || $mode->isTablet()) {
290                         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
291                                 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
292                         } else {
293                                 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
294                         }
295                         $this->page['footer'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
296                                 '$toggle_link' => $link,
297                                 '$toggle_text' => $l10n->t('toggle mobile')
298                         ]);
299                 }
300
301                 Hook::callAll('footer', $this->page['footer']);
302
303                 $tpl                  = Renderer::getMarkupTemplate('footer.tpl');
304                 $this->page['footer'] = Renderer::replaceMacros($tpl, [
305                         '$footerScripts' => array_unique($this->footerScripts),
306                 ]) . $this->page['footer'];
307         }
308
309         /**
310          * Initializes Page->page['content'].
311          *
312          * Includes:
313          * - module content
314          * - hooks for content
315          *
316          * @param Module $module The module
317          * @param Mode   $mode   The Friendica execution mode
318          *
319          * @throws HTTPException\InternalServerErrorException
320          */
321         private function initContent(Module $module, Mode $mode)
322         {
323                 $content = '';
324
325                 try {
326                         $moduleClass = $module->getClassName();
327
328                         $arr = ['content' => $content];
329                         Hook::callAll($moduleClass . '_mod_content', $arr);
330                         $content = $arr['content'];
331                         $arr     = ['content' => call_user_func([$moduleClass, 'content'], $module->getParameters())];
332                         Hook::callAll($moduleClass . '_mod_aftercontent', $arr);
333                         $content .= $arr['content'];
334                 } catch (HTTPException $e) {
335                         $content = ModuleHTTPException::content($e);
336                 }
337
338                 // initialise content region
339                 if ($mode->isNormal()) {
340                         Hook::callAll('page_content_top', $this->page['content']);
341                 }
342
343                 $this->page['content'] .= $content;
344         }
345
346         /**
347          * Register a javascript file path to be included in the <footer> tag of every page.
348          * Inclusion is done in App->initFooter().
349          * The path can be absolute or relative to the Friendica installation base folder.
350          *
351          * @param string $path
352          *
353          * @see Page::initFooter()
354          *
355          */
356         public function registerFooterScript($path)
357         {
358                 $path = Network::appendQueryParam($path, ['v' => FRIENDICA_VERSION]);
359
360                 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
361
362                 $this->footerScripts[] = trim($url, '/');
363         }
364
365         /**
366          * Executes the creation of the current page and prints it to the screen
367          *
368          * @param App      $app     The Friendica App
369          * @param BaseURL  $baseURL The Friendica Base URL
370          * @param Mode     $mode    The current node mode
371          * @param Module   $module  The loaded Friendica module
372          * @param L10n     $l10n    The l10n language class
373          * @param IConfig  $config  The Configuration of this node
374          * @param IPConfig $pconfig The personal/user configuration
375          *
376          * @throws HTTPException\InternalServerErrorException
377          */
378         public function run(App $app, BaseURL $baseURL, Mode $mode, Module $module, L10n $l10n, IConfig $config, IPConfig $pconfig)
379         {
380                 $moduleName = $module->getName();
381
382                 /* Create the page content.
383                  * Calls all hooks which are including content operations
384                  *
385                  * Sets the $Page->page['content'] variable
386                  */
387                 $this->initContent($module, $mode);
388
389                 // Load current theme info after module has been initialized as theme could have been set in module
390                 $currentTheme = $app->getCurrentTheme();
391                 $theme_info_file = 'view/theme/' . $currentTheme . '/theme.php';
392                 if (file_exists($theme_info_file)) {
393                         require_once $theme_info_file;
394                 }
395
396                 if (function_exists(str_replace('-', '_', $currentTheme) . '_init')) {
397                         $func = str_replace('-', '_', $currentTheme) . '_init';
398                         $func($app);
399                 }
400
401                 /* Create the page head after setting the language
402                  * and getting any auth credentials.
403                  *
404                  * Moved initHead() and initFooter() to after
405                  * all the module functions have executed so that all
406                  * theme choices made by the modules can take effect.
407                  */
408                 $this->initHead($app, $module, $l10n, $config, $pconfig);
409
410                 /* Build the page ending -- this is stuff that goes right before
411                  * the closing </body> tag
412                  */
413                 $this->initFooter($app, $mode, $l10n);
414
415                 if (!$mode->isAjax()) {
416                         Hook::callAll('page_end', $this->page['content']);
417                 }
418
419                 // Add the navigation (menu) template
420                 if ($moduleName != 'install' && $moduleName != 'maintenance') {
421                         $this->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('nav_head.tpl'), []);
422                         $this->page['nav']      = Nav::build($app);
423                 }
424
425                 // Build the page - now that we have all the components
426                 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
427                         $doc = new DOMDocument();
428
429                         $target = new DOMDocument();
430                         $target->loadXML("<root></root>");
431
432                         $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
433
434                         /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
435                         @$doc->loadHTML($content);
436
437                         $xpath = new DOMXPath($doc);
438
439                         $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]");  /* */
440
441                         foreach ($list as $item) {
442                                 $item = $target->importNode($item, true);
443
444                                 // And then append it to the target
445                                 $target->documentElement->appendChild($item);
446                         }
447
448                         if ($_GET["mode"] == "raw") {
449                                 header("Content-type: text/html; charset=utf-8");
450
451                                 echo substr($target->saveHTML(), 6, -8);
452
453                                 exit();
454                         }
455                 }
456
457                 $page    = $this->page;
458                 $profile = $app->profile;
459
460                 header("X-Friendica-Version: " . FRIENDICA_VERSION);
461                 header("Content-type: text/html; charset=utf-8");
462
463                 if ($config->get('system', 'hsts') && ($baseURL->getSSLPolicy() == BaseURL::SSL_POLICY_FULL)) {
464                         header("Strict-Transport-Security: max-age=31536000");
465                 }
466
467                 // Some security stuff
468                 header('X-Content-Type-Options: nosniff');
469                 header('X-XSS-Protection: 1; mode=block');
470                 header('X-Permitted-Cross-Domain-Policies: none');
471                 header('X-Frame-Options: sameorigin');
472
473                 // Things like embedded OSM maps don't work, when this is enabled
474                 // 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'");
475
476                 /* We use $_GET["mode"] for special page templates. So we will check if we have
477                  * to load another page template than the default one.
478                  * The page templates are located in /view/php/ or in the theme directory.
479                  */
480                 if (isset($_GET['mode'])) {
481                         $template = Theme::getPathForFile('php/' . Strings::sanitizeFilePathItem($_GET['mode']) . '.php');
482                 }
483
484                 // If there is no page template use the default page template
485                 if (empty($template)) {
486                         $template = Theme::getPathForFile('php/default.php');
487                 }
488
489                 // Theme templates expect $a as an App instance
490                 $a = $app;
491
492                 // Used as is in view/php/default.php
493                 $lang = $l10n->getCurrentLang();
494
495                 require_once $template;
496         }
497 }