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