]> git.mxchange.org Git - friendica.git/blob - src/App/Page.php
Fix OPTIONS
[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\Renderer;
34 use Friendica\Core\Theme;
35 use Friendica\DI;
36 use Friendica\Network\HTTPException;
37 use Friendica\Util\Network;
38 use Friendica\Util\Strings;
39 use Friendica\Util\Profiler;
40 use Psr\Http\Message\ResponseInterface;
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 ResponseInterface  $response The Module response class
342          * @param Mode               $mode     The Friendica execution mode
343          *
344          * @throws HTTPException\InternalServerErrorException
345          */
346         private function initContent(ResponseInterface $response, Mode $mode)
347         {
348                 // initialise content region
349                 if ($mode->isNormal()) {
350                         Hook::callAll('page_content_top', $this->page['content']);
351                 }
352
353                 $this->page['content'] .= (string)$response->getBody();
354         }
355
356         /**
357          * Register a javascript file path to be included in the <footer> tag of every page.
358          * Inclusion is done in App->initFooter().
359          * The path can be absolute or relative to the Friendica installation base folder.
360          *
361          * @param string $path
362          *
363          * @see Page::initFooter()
364          *
365          */
366         public function registerFooterScript($path)
367         {
368                 $path = Network::appendQueryParam($path, ['v' => FRIENDICA_VERSION]);
369
370                 $url = str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path);
371
372                 $this->footerScripts[] = trim($url, '/');
373         }
374
375         /**
376          * Directly exit with the current response (include setting all headers)
377          *
378          * @param ResponseInterface $response
379          */
380         public function exit(ResponseInterface $response)
381         {
382                 header(sprintf("HTTP/%s %s %s",
383                         $response->getProtocolVersion(),
384                         $response->getStatusCode(),
385                         $response->getReasonPhrase())
386                 );
387
388                 foreach ($response->getHeaders() as $key => $header) {
389                         if (is_array($header)) {
390                                 $header_str = implode(',', $header);
391                         } else {
392                                 $header_str = $header;
393                         }
394
395                         if (empty($key)) {
396                                 header($header_str);
397                         } else {
398                                 header("$key: $header_str");
399                         }
400                 }
401
402                 echo $response->getBody();
403         }
404
405         /**
406          * Executes the creation of the current page and prints it to the screen
407          *
408          * @param App                         $app      The Friendica App
409          * @param BaseURL                     $baseURL  The Friendica Base URL
410          * @param Arguments                   $args     The Friendica App arguments
411          * @param Mode                        $mode     The current node mode
412          * @param ResponseInterface           $response The Response of the module class, including type, content & headers
413          * @param L10n                        $l10n     The l10n language class
414          * @param IManageConfigValues         $config   The Configuration of this node
415          * @param IManagePersonalConfigValues $pconfig  The personal/user configuration
416          *
417          * @throws HTTPException\InternalServerErrorException|HTTPException\ServiceUnavailableException
418          */
419         public function run(App $app, BaseURL $baseURL, Arguments $args, Mode $mode, ResponseInterface $response, L10n $l10n, Profiler $profiler, IManageConfigValues $config, IManagePersonalConfigValues $pconfig)
420         {
421                 $moduleName = $args->getModuleName();
422
423                 /* Create the page content.
424                  * Calls all hooks which are including content operations
425                  *
426                  * Sets the $Page->page['content'] variable
427                  */
428                 $timestamp = microtime(true);
429                 $this->initContent($response, $mode);
430
431                 // Load current theme info after module has been initialized as theme could have been set in module
432                 $currentTheme = $app->getCurrentTheme();
433                 $theme_info_file = 'view/theme/' . $currentTheme . '/theme.php';
434                 if (file_exists($theme_info_file)) {
435                         require_once $theme_info_file;
436                 }
437
438                 if (function_exists(str_replace('-', '_', $currentTheme) . '_init')) {
439                         $func = str_replace('-', '_', $currentTheme) . '_init';
440                         $func($app);
441                 }
442
443                 /* Create the page head after setting the language
444                  * and getting any auth credentials.
445                  *
446                  * Moved initHead() and initFooter() to after
447                  * all the module functions have executed so that all
448                  * theme choices made by the modules can take effect.
449                  */
450                 $this->initHead($app, $args, $l10n, $config, $pconfig);
451
452                 /* Build the page ending -- this is stuff that goes right before
453                  * the closing </body> tag
454                  */
455                 $this->initFooter($app, $mode, $l10n);
456
457                 $profiler->set(microtime(true) - $timestamp, 'aftermath');
458
459                 if (!$mode->isAjax()) {
460                         Hook::callAll('page_end', $this->page['content']);
461                 }
462
463                 // Add the navigation (menu) template
464                 if ($moduleName != 'install' && $moduleName != 'maintenance') {
465                         $this->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('nav_head.tpl'), []);
466                         $this->page['nav']      = Nav::build($app);
467                 }
468
469                 foreach ($response->getHeaders() as $key => $header) {
470                         if (is_array($header)) {
471                                 $header_str = implode(',', $header);
472                         } else {
473                                 $header_str = $header;
474                         }
475
476                         if (empty($key)) {
477                                 header($header_str);
478                         } else {
479                                 header("$key: $header_str");
480                         }
481                 }
482
483                 // Build the page - now that we have all the components
484                 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
485                         $doc = new DOMDocument();
486
487                         $target = new DOMDocument();
488                         $target->loadXML("<root></root>");
489
490                         $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
491
492                         /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
493                         @$doc->loadHTML($content);
494
495                         $xpath = new DOMXPath($doc);
496
497                         $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]");  /* */
498
499                         foreach ($list as $item) {
500                                 $item = $target->importNode($item, true);
501
502                                 // And then append it to the target
503                                 $target->documentElement->appendChild($item);
504                         }
505
506                         if ($_GET["mode"] == "raw") {
507                                 header("Content-type: text/html; charset=utf-8");
508
509                                 echo substr($target->saveHTML(), 6, -8);
510
511                                 exit();
512                         }
513                 }
514
515                 $page    = $this->page;
516
517                 header("X-Friendica-Version: " . FRIENDICA_VERSION);
518                 header("Content-type: text/html; charset=utf-8");
519
520                 if ($config->get('system', 'hsts') && ($baseURL->getSSLPolicy() == BaseURL::SSL_POLICY_FULL)) {
521                         header("Strict-Transport-Security: max-age=31536000");
522                 }
523
524                 // Some security stuff
525                 header('X-Content-Type-Options: nosniff');
526                 header('X-XSS-Protection: 1; mode=block');
527                 header('X-Permitted-Cross-Domain-Policies: none');
528                 header('X-Frame-Options: sameorigin');
529
530                 // Things like embedded OSM maps don't work, when this is enabled
531                 // 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'");
532
533                 /* We use $_GET["mode"] for special page templates. So we will check if we have
534                  * to load another page template than the default one.
535                  * The page templates are located in /view/php/ or in the theme directory.
536                  */
537                 if (isset($_GET['mode'])) {
538                         $template = Theme::getPathForFile('php/' . Strings::sanitizeFilePathItem($_GET['mode']) . '.php');
539                 }
540
541                 // If there is no page template use the default page template
542                 if (empty($template)) {
543                         $template = Theme::getPathForFile('php/default.php');
544                 }
545
546                 // Theme templates expect $a as an App instance
547                 $a = $app;
548
549                 // Used as is in view/php/default.php
550                 $lang = $l10n->getCurrentLang();
551
552                 require_once $template;
553         }
554 }